用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();


最后貼張識別后的圖:





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM