python3 2. 通过摄像头进行人脸和眼睛检测 学习笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mcyJacky/article/details/84932784

前言

     计算机视觉系列之学习笔记主要是本人进行学习人工智能(计算机视觉方向)的代码整理。本系列所有代码是用python3编写,在平台Anaconda中运行实现,在使用代码时,默认你已经安装相关的python库,这方面不做多余的说明。本系列所涉及的所有代码和资料可在我的github或者码云上下载到,gitbub地址:https://github.com/mcyJacky/DeepLearning-CV,如有问题,欢迎指出~。

一、构建摄像头检测函数

1.1 构建简单的读取图片的模块

     先构建一个通用模块,用来读取并显示图片,模块命名为imutils
     使用到python的相关库包括:计算机视觉库cv2、绘图库matplotlib.

import cv2
import matplotlib.pyplot as plt

def show(image):
    plt.imshow(image)
    plt.axis('off')
    plt.show()
    
def imread(image):
    image = cv2.imread(image)
    image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
    return image

1.2 目标检测函数

from imutils import *

def detector_object(name):
    #摄像头捕捉
    cap = cv2.VideoCapture(0)
    def _capture_face():
        print('capture face begin!')
        while True:
            #根据帧来读
            ret, frame = cap.read()
            if ret != True:
                break
            
            #级联分类器进行人脸识别
            detector = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
            rects = detector.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=2, minSize=(10,10), flags=cv2.CASCADE_SCALE_IMAGE)
            for (x,y,w,h) in rects:
                cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2)
            
            cv2.imshow('frame', frame)   
            #检测间隔为20毫秒,并且可以按键盘键“q”退出检测窗口
            if cv2.waitKey(20) & 0xff == ord('q'):
                break
                
    def _capture_eye():
        print('capture eye begin!')
        while True:
            #根据帧来读
            ret, frame = cap.read()
            if ret != True:
                break
            #级联分类器进行眼睛识别
            detector = cv2.CascadeClassifier('haarcascade_eye_tree_eyeglasses.xml')
            rects = detector.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=3, minSize=(10,10), flags=cv2.CASCADE_SCALE_IMAGE)
            for (x,y,w,h) in rects:
                cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
            
            cv2.imshow('frame', frame)   
            if cv2.waitKey(20) & 0xff == ord('q'):
                break
    
    if name == 'face':
        _capture_face()
    elif name == 'eye':
        _capture_eye()
    
    #释放并关闭窗口
    cap.release()
    cv2.destroyAllWindows()

     上述函数中整体构建了一个目标检测函数detector_objec(),其中包括人脸检测_capture_face()和眼睛检测_capture_eye()两种,两个函数的区别是级联分类器不同。

1.3 进行检测

#人脸检测
detector_object('face')

# 眼睛检测
detector_object('eye')

     分别运行上述检测函数后,电脑摄像头会打开,并检测到你的人脸或者眼睛用绿色矩形框画出。因涉及个人照片,这边就不上传相关图片。

【参考】:
     1. 城市数据团课程《AI工程师》计算机视觉方向
     2. 《OpenCV3编程入门》 毛星云
     3. 《OpenCV3计算机视觉:Python语言实现》 JoeMinichino


转载声明:
版权声明:非商用自由转载-保持署名-注明出处
署名 :mcyJacky
文章出处:https://blog.csdn.net/mcyJacky

猜你喜欢

转载自blog.csdn.net/mcyJacky/article/details/84932784