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

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

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

article_wechat2021.jpg?1111

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值