美文网首页
opencv-python摄像头实时检测人脸和眼部

opencv-python摄像头实时检测人脸和眼部

作者: Moneys | 来源:发表于2019-03-15 15:31 被阅读0次

    实现比较简单,直接上代码

    import cv2
    
    def main():
        # 加载人脸检测联级文件
        face_detect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    
        # 加载眼部检测联级文件
        eye_detect = cv2.CascadeClassifier('haarcascade_eye.xml')
    
        # 打开摄像头
        camera = cv2.VideoCapture(0)
    
        while(True):
            # 从摄像头读取图片
            ret, image = camera.read()
            if not ret:
                print('failed to read camera data.')
                break
    
            # BRG转灰度图
            image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
            # 检测人脸
            faces = face_detect.detectMultiScale(image_gray, scaleFactor=1.15, minNeighbors=5, minSize=(5, 5))
            for (x, y, width, height) in faces:
                # 根据检测结果绘制矩形框
                cv2.rectangle(image, (x, y), (x + width, y + height), (255, 0, 0), 2)
    
            # 检测眼睛
            eyes = eye_detect.detectMultiScale(image_gray, scaleFactor=2.50, minNeighbors=5, minSize=(5, 5))
            for (x, y, width, height) in eyes:
                # 根据检测结果绘制矩形框
                cv2.rectangle(image, (x, y), (x + width, y + height), (255, 0, 0), 2)
    
            # 显示图片
            cv2.imshow('Face And Eye Detect', image)
    
            # 捕捉按键,如果是Q退出
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    
        # 释放摄像头
        camera.release()
    
        # 销毁窗口
        cv2.destroyAllWindows()
    
    if __name__ == '__main__':
        main()
    

    效果图

    Baby

    备注

    上述代码用到的联级文件可以在Pyhton安装目录下搜索到,比如Mac OS下Pyhton 3.6的路径 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/cv2/data,前提是已经安装了opencv-python。

    如何安装opencv-python?

    pip3 install opencv-python
    

    或者参考 https://pypi.org/project/opencv-python/

    相关文章

      网友评论

          本文标题:opencv-python摄像头实时检测人脸和眼部

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