Opencv 入门学习之图片人脸识别

读入图片,算法检测,画出矩形框

 

import cv2
from PIL import Image,ImageDraw 
import os 

def detectFaces(image_name):
    img = cv2.imread(image_name)
    face_cascade = cv2.CascadeClassifier('../opencv-2.4.9/data/haarcascades/haarcascade_frontalface_default.xml')
    if img.ndim==3: # 如果是三维就转换成二维
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    else:
        gray = img
    faces = face_cascade.detectMultiScale(gray,scaleFactor = 1.3,minNeighbors=4)
    result = []
    for (x,y,width,height) in faces:
        result.append((x,y,x+width,y+height))
    return result


def saveFaces(image_name):
    faces = detectFaces(image_name)
    if faces:
        save_dir = image_name.split('.')[0]+"_faces"
        os.mkdir(save_dir)
        count = 0
        for (x1,y1,x2,y2) in faces:
            file_name = os.path.join(save_dir,str(count)+".jpg")
            Image.open(image_name).crop((x1,y1,x2,y2)).save(file_name)  
            count +=1

#在原图像上画矩形,框出所有人脸。
#调用Image模块的draw方法,Image.open获取图像句柄, ImageDraw获取该图像的draw实例,然后调用该draw实例的rectangle方法画矩形 (矩形的坐标即mZdetectFaces返回的坐标),outline是矩
形线条颜色(B,G,R)。
#注:原始图像如果是灰度图,则去掉outline,因为灰度图没有RGB可言。drawEyes、detectSmiles也一样

def drawFaces(image_name):
    faces = detectFaces(image_name)
    if faces:
        img = Image.open(image_name)
        draw_instance = ImageDraw.Draw(img)
        for(x1,y1,x2,y2) in faces:
            draw_instance.rectangle((x1,y1,x2,y2),outline=(25,255,0))
        img.save('drawFaces_'+image_name)
        saveFaces(image_name)
        image = cv2.imread('drawFaces_'+image_name)
        return image

if __name__=="__main__":
    img = drawFaces('obama.jpg')
    cv2.imshow("drawFaces",img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()



运行 python faceDetect.py 后效果如图:前2个识别错误!

生成人脸文件:

 

 

参考: http://blog.csdn.net/u012162613/article/details/43523507

posted on 2015-04-19 22:04  星空守望者--jkmiao  阅读(1035)  评论(0编辑  收藏  举报