美文网首页
基于OpenCV 使用Python实现简单的人脸识别-macOS

基于OpenCV 使用Python实现简单的人脸识别-macOS

作者: 时间之友 | 来源:发表于2019-02-23 14:12 被阅读2次

    一、环境搭建

    安装OpenCV(使用pycharm的建议在pycharm终端内安装)

    pip3 install opencv-python
    

    二、实现图片人脸识别

    import cv2 as cv
    import numpy as np
    
    def face_detect_demo():
        gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
        face_detector = cv.CascadeClassifier("/Users/jkx/PycharmProjects/awesome_web/venv/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_default.xml")
        faces = face_detector.detectMultiScale(gray, 1.02, 5)   # 改变数字可调人脸检测的灵敏度
        for x, y, w, h in faces:
            cv.rectangle(src, (x, y), (x+w, y+h), (0, 0, 255), 1)
        cv.imshow("result", src)
    
    print("--------- the face detection ---------")
    src = cv.imread("/Users/jkx/Desktop/太祖.png")
    cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
    cv.namedWindow("result", cv.WINDOW_AUTOSIZE)
    
    cv.imshow("input image", src)
    face_detect_demo()
    cv.waitKey(0)
    
    cv.destroyAllWindows()
    

    效果如下:

    识别毛主席

    三、电脑前置摄像头人脸识别

    def face_detect_demo(image):   # 视频识别部分
        gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
        face_detector = cv.CascadeClassifier("/Users/jkx/PycharmProjects/awesome_web/venv/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_default.xml")
        faces = face_detector.detectMultiScale(gray, 1.02, 50)   # 最后一个数字越小,越容易误判,越大,越容易不判
        for x, y, w, h in faces:
            cv.rectangle(image, (x, y), (x+w, y+h), (0, 0, 255), 1)
        cv.imshow("result", image)
    
    print("--------- the face detection ---------")
    capture = cv.VideoCapture(0)
    cv.namedWindow("result", cv.WINDOW_AUTOSIZE)
    
    while(True):
        ret, frame = capture.read()
        frame = cv.flip(frame, 1)
        face_detect_demo(frame)
        c = cv.waitKey(10)
        if c == 27: # ESC
            break
    
    cv.waitKey(0)   # 识别成功,但是很卡
    
    随手画的小人不识别

    相关文章

      网友评论

          本文标题:基于OpenCV 使用Python实现简单的人脸识别-macOS

          本文链接:https://www.haomeiwen.com/subject/nofpyqtx.html