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 <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 opencv对目录下图片进行去重的方法
-
python中使用OpenCV进行人脸检测的例子
-
OpenCV中的新函数connectedComponentsWithStats使用(python和c++实例)
-
基于jupyter notebook的python编程(Win10通过OpenCv-3.4.1进行人脸口罩数据集的模型训练并进行戴口罩识别检测)
-
Android OpenCV使用2_使用OpenCV并进行人脸检测
-
Python 使用PIL中的resize进行缩放的实例讲解
-
Python使用Opencv实现边缘检测以及轮廓检测的实现
-
浅谈Python Opencv中gamma变换的使用详解
-
使用python对文件中的数值进行累加的实例
-
在python3.5中使用OpenCV的实例讲解