Python和OpenCV简单的人脸检测程序

    最近想要搞人脸识别的东西,所以先弄了个简单的人脸检测的程序,网上找的许多都无法使用,不知道是不是Opencv版本的关系,或者是和Python结合后产生的问题,感觉很多API都是错的,这里用的是opencv2.3.1和python2.7。Python需要安装numpy,和PIL(不装应该也行,我这里使用到了),废话不多说上代码。

参考了:http://creatingwithcode.com/howto/face-detection-in-static-images-with-python/

from PIL import Image, ImageDraw
from math import sqrt
import cv
import os
import sys

def detect_object(image):

    grayscale = cv.CreateImage((image.width, image.height), 8, 1)
    cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY)

    cascade = cv.Load("D:\\opencv\\data\\haarcascades\\haarcascade_frontalface_default.xml")
    rect = cv.HaarDetectObjects(grayscale, cascade, cv.CreateMemStorage(), 1.1, 2,
        cv.CV_HAAR_DO_CANNY_PRUNING, (20,20))
    
    result = []
    for r in rect:
        result.append((r[0][0], r[0][1], r[0][0]+r[0][2], r[0][1]+r[0][3]))

    return result

def process(infile, outfile):
    image = cv.LoadImage(infile);
    if image:
        faces = detect_object(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')
代码不难懂,不理解的地方去搜下相关的API即可。

结果如下:


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值