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使用struct处理二进制的实例详解

Python使用struct处理二进制的实例详解 有的时候需要用python处理二进制数据,比如,存取文件,socket操作时.这时候,可以使用python的struct模块来完成.可以...

Python 给屏幕打印信息加上颜色的实现方法

Python 给屏幕打印信息加上颜色的实现方法

语法 print('\033[显示方式;字体色;背景色m文本\033[0m') # 三种设置都可以忽略不写,都不写则为默认输出 配置如下 # 字体 背景 颜色 # ------...

python去除字符串中的换行符

今天写这个,要用python去除字符串中的换行符并写入文件,网上查阅,就一句代码replace("\n",""),加上之后,搞了半天,还是不对。 以上是我今天遇到的问题,以下是解决方案。...

python读取目录下最新的文件夹方法

如下所示: def new_report(test_report): lists = os.listdir(test_report) # 列出目录的下所有文件和文件...

python3 property装饰器实现原理与用法示例

本文实例讲述了python3 property装饰器实现原理与用法。分享给大家供大家参考,具体如下: 学习python的同学,慢慢的都会接触到装饰器,装饰器在python里是功能强大的语...