python中使用OpenCV进行人脸检测的例子

yipeiwu_com5年前Python基础

OpenCV的人脸检测功能在一般场合还是不错的。而ubuntu正好提供了python-opencv这个包,用它可以方便地实现人脸检测的代码。

写代码之前应该先安装python-opencv:

复制代码 代码如下:

$ sudo apt-get install python-opencv

具体原理就不多说了,可以参考一下这篇文章。直接上源码。

复制代码 代码如下:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# face_detect.py

# Face Detection using OpenCV. Based on sample code from:
# http://python.pastebin.com/m76db1d6b

# Usage: python face_detect.py <image_file>

import sys, os
from opencv.cv import *
from opencv.highgui import *
from PIL import Image, ImageDraw
from math import sqrt

def detectObjects(image):
    """Converts an image to grayscale and prints the locations of any faces found"""
    grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1)
    cvCvtColor(image, grayscale, CV_BGR2GRAY)

    storage = cvCreateMemStorage(0)
    cvClearMemStorage(storage)
    cvEqualizeHist(grayscale, grayscale)

    cascade = cvLoadHaarClassifierCascade(
        '/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml',
        cvSize(1,1))
    faces = cvHaarDetectObjects(grayscale, cascade, storage, 1.1, 2,
        CV_HAAR_DO_CANNY_PRUNING, cvSize(20,20))

    result = []
    for f in faces:
        result.append((f.x, f.y, f.x+f.width, f.y+f.height))

    return result

def grayscale(r, g, b):
    return int(r * .3 + g * .59 + b * .11)

def process(infile, outfile):

    image = cvLoadImage(infile);
    if image:
        faces = detectObjects(image)

    im = Image.open(infile)

    if faces:
        draw = ImageDraw.Draw(im)
        for f in faces:
            draw.rectangle(f, outline=(255, 0, 255))

        im.save(outfile, "JPEG", quality=100)
    else:
        print "Error: cannot detect faces on %s" % infile

if __name__ == "__main__":
    process('input.jpg', 'output.jpg')

相关文章

pytorch 实现在预训练模型的 input上增减通道

如何把imagenet预训练的模型,输入层的通道数随心所欲的修改,从而来适应自己的任务 #增加一个通道 w = layers[0].weight layers[0] = nn.Con...

Python在Matplotlib图中显示中文字体的操作方法

1.    说明 本篇主要针对在Ubuntu系统中,matplotlib显示不了中文的问题,尤其是在无法安装系统字体的情况下,解决Python绘图时中文显示...

python 快速把超大txt文件转存为csv的实例

今天项目有个需求,就是把txt文件转为csv,txt之间是空格隔开,转为csv时需要把空格转换为逗号,网上找的一个版本,只需要三行代码,特别犀利: import numpy as n...

在pandas中遍历DataFrame行的实现方法

在pandas中遍历DataFrame行的实现方法

有如下 Pandas DataFrame: import pandas as pd inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {...

对Python+opencv将图片生成视频的实例详解

如下所示: import cv2 fps = 16 size = (width,height) videowriter = cv2.VideoWriter("a.avi",c...