• 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

    每天一小步,人生一大步!Good luck~
  • 相关阅读:
    智能网关de_GWD的一次排障经历
    盛唐领土争夺战读后感
    Unreal Open Day游记
    虚幻4随笔7 未知的未来
    虚幻4随笔6 Object和序列化
    虚幻4随笔5 使用中的一些发现
    虚幻4随笔4 从工程开始
    松口气,近一段时间的工作学习情况
    虚幻4随笔 三 从UE3到UE4
    关卡原型制作思路
  • 原文地址:https://www.cnblogs.com/jkmiao/p/4440127.html
Copyright © 2020-2023  润新知