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')

相关文章

python中异常捕获方法详解

在Python中处理异常使用的是try-except代码块,try-except代码块放入让python执行的操作,同时告诉python程序如果发生了异常该怎么办,try-except这...

在Linux下使用Python的matplotlib绘制数据图的教程

在Linux下使用Python的matplotlib绘制数据图的教程

如果你想要在Linxu中获得一个高效、自动化、高质量的科学画图的解决方案,应该考虑尝试下matplotlib库。Matplotlib是基于python的开源科学测绘包,基于python软...

简单了解python 邮件模块的使用方法

我们在开发程序的时候,有时候需要开发一些自动化的任务,执行完之后,将结果自动的发送一份邮件,python发送邮件使用smtplib模块,是一个标准包,直接import导入使用即可,代码如...

python中yaml配置文件模块的使用详解

简述 和GNU一样,YAML是一个递归着说“不”的名字。不同的是,GNU对UNIX说不,YAML说不的对象是XML。 YAML不是XML。 为什么不是XML呢?因为: YAML...

pytorch 更改预训练模型网络结构的方法

一个继承nn.module的model它包含一个叫做children()的函数,这个函数可以用来提取出model每一层的网络结构,在此基础上进行修改即可,修改方法如下(去除后两层):...