用OpenCv来做人脸识别

参考这篇文章: http://tech.idv2.com/2012/01/20/face-detection-with-python-opencv/

python比较简单,只需安装 python-opencv 就行:

$ sudo apt-get install python-opencv

python的实现也很简单,参考:http://opencv.willowgarage.com/documentation/python/objdetect_cascade_classification.html

代码:

#!/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
import cv
from PIL import Image, ImageDraw

def detectObjects(image):
"""Converts an image to grayscale and prints the locations of any faces found"""
storage = cv.CreateMemStorage()

cascade = cv.Load('haarcascade_frontalface_alt.xml')
faces = cv.HaarDetectObjects(image, cascade, storage)

result = []
for (x,y,w,h),n in faces:
result.append((x, y, x+w, y+h))

return result

def process(infile, outfile):

image = cv.LoadImage(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')

注:haarcascade_frontalface_alt.xml 可以在 https://github.com/talvarez/Face.js/tree/master/cascades 找到

 

Node.js的话,有一个叫Face.js的项目,对OpenCv做了简单封装,地址是: https://github.com/talvarez/Face.js 
这个需要先安装OpenCv库,目前版本是2.3.1,按照可以参考: UBUNTU 下编译安装opencv 2.3.1

Face.js的具体的示例代码可以在Face.js里面的example里面找到,这里贴个简单的: 

var Face = require('../build/default/face.node'),
detector = new Face.init();

detector.img = './samples/frame1.png';
detector.maxsize = 20;
detector.pathto = '../cascades/'

detector.oncomplete = function(faces){
console.log("I found " + faces.length + " faces");
for(var i = 0; i < faces.length; i++) {
console.log(faces[i].x, faces[i].y, faces[i].width, faces[i].height);
}
};

detector.run();


最后贴张识别后的图:




posted on 2012-02-08 22:10  Q.Lee.lulu  阅读(8025)  评论(0编辑  收藏  举报