Minimal Python: Use opencv to realize face detection, and use a local camera to realize face recognition in video streams

Including face detection at the picture level and calling the local camera to realize face recognition at the video stream level.

Not most nonsense, just upload the code directly, and the students you like can collect it!

1. Image face recognition

Use Haar cascade detection in OpenCV

import cv2

# 读取图片,并获得灰度图
img = cv2.imread('/Users/robin/.../7_surprise2.jpg', 0)  #(-1:原图、0:灰度图、1:彩色图、-1:原图)
print(img.shape) # 检验图片是否OK(返回None则地址错误)

# 载入分类器(获取训练好的人脸的参数数据,这里是数据是opencv自带的)
face_cascade = cv2.CascadeClassifier('/Users/robin/software/anaconda3/pkgs/libopencv-3.4.2-h7c891bd_1/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')

# 检测人脸,返回人脸的坐标(x,y,w,h)——(起始列、起始行、宽度、高度)
faces = face_cascade.detectMultiScale(img,scaleFactor=1.15,minNeighbors=5,minSize=(5,5))

# 画图
for(x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),4)   #参数:图像 + 左上角坐标 + 右下角坐标 + 颜色 + 线的类型

# 显示图片
cv2.imshow('face', img)
k = cv2.waitKey(0)  # 0代表一直等待,其他数值代表等待的毫秒数
if k == 27:      # 用按键Esc来控制关闭窗口(27是键盘上Esc的值 )
    cv2.destroyAllWindows()
    for i in range (1,5):     #用4次循环来帮助关闭卡住的窗口
        cv2.waitKey(1)

# 保存图片
# cv2.imwrite('./face.jpg', img) #默认的地址在该ipybn文件所在目录
cv2.imwrite('/Users/robin/MLcode/.../face.jpg', img)

Insert picture description here

2. Picture face detection + eye detection

import cv2
# image loading
gray_image = cv2.imread('/Users/robin/.../3_neutral2.jpg',0)
print(gray_image)

# classifier loading
face_cascade = cv2.CascadeClassifier('/Users/robin/software/anaconda3/pkgs/libopencv-3.4.2-h7c891bd_1/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/Users/robin/software/anaconda3/pkgs/libopencv-3.4.2-h7c891bd_1/share/OpenCV/haarcascades/haarcascade_eye.xml')

# face and eye detect and drawing
faces = face_cascade.detectMultiScale(gray_image,scaleFactor=1.15,minNeighbors=5,minSize=(5,5))
for (x,y,w,h) in faces:
    cv2.rectangle(gray_image,(x,y),(x+w,y+h),(255,0,0),3)
    roi_gray = gray_image[y:y+h,x:x+w]   # 循环画矩形的时候,也要取出roi(整个下面的步骤都要在第一个for循环中进行)
    
    eyes = eye_cascade.detectMultiScale(roi_gray,scaleFactor=1.15,minNeighbors=5,minSize=(5,5))
    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi_gray,(ex,ey),(ex+ew,ey+eh),(0,255,0),3)  #注意此时是画在roi图像上

# image show
cv2.imshow('gray_image',gray_image)
k = cv2.waitKey(0)
if k == 27:
    cv2.destroyAllWindows()
    for i in range(1,5):          #辅助关闭窗口
        cv2.waitKey(1)
        

Insert picture description here

3. Face recognition in video streaming

import numpy as np
import cv2

cascPath = '/Users/robin/software/anaconda3/pkgs/libopencv-3.4.2-h7c891bd_1/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml'

face_Cascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)   # 参数0 :内置摄像头;也可以是视频文件地址

while(True):    # 死循环;也可以用 while(1)
    # Capture frame-by-frame
    ret, frame = video_capture.read()      #参数:第一个参数ret的值为True或False,代表有没有读到图片(读完了就是False)。第二个参数是frame,是当前截取一帧的图片。 

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # 注意了,有两种灰度转化的方法 (这里可以想办法一步到位?)

    faces = face_Cascade.detectMultiScale(

       gray,

       scaleFactor=1.1,

       minNeighbors=5,

       minSize=(30, 30),

       flags=cv2.CASCADE_SCALE_IMAGE         # 这个什么意思:CV_HAAR_SCALE_IMAGE,这个值告诉分类器不要缩放分类器。而是缩放图像(处理好内存和缓存的使用问题,这可以提高性能。)就是按比例正常检测

   )
    
    # Draw a rectangle around the faces

    for (x, y, w, h) in faces:

        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
    
        
    # Display the resulting frame

    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):

        break

# When everything is done, release the capture

video_capture.release()
cv2.destroyAllWindows()

Insert picture description here

Guess you like

Origin blog.csdn.net/Robin_Pi/article/details/114964535