Use opcv face detection

System development environment

  • Windows11
  • Python 3.8
  • Pycharm 2021.3 Community Edition

required environment library

  • numpy==1.22.1
  • opencv-contrib-python==4.5.5.62
  • opencv-python==4.5.5.62

Install the environment library

Just use pip to install directly. It is recommended to use a lower version of Python for development with openCV. It is not easy to encounter various strange problems. Windows systems can install multiple versions of Python. Be careful not to check Add to Path during installation. Create a virtual environment, it can be created directly using interpreters of different versions.
Coexistence of different versions of Python

Code

import cv2
import numpy as np

#人脸识别分类器
faceCascade = cv2.CascadeClassifier(
    r"C:\Users\TOM\.virtualenvs\smart-home\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml")
#人眼识别分类器
eyesCascade = cv2.CascadeClassifier(
    r"C:\Users\TOM\.virtualenvs\smart-home\Lib\site-packages\cv2\data\haarcascade_eye.xml")

#调用本地摄像头
cap = cv2.VideoCapture(0)
flag = True
while flag:
    #read返回两个值,第一个值True代表获取到数据,后一个值为摄像头数据流
    flag, img = cap.read()
    #翻转图像
    img = cv2.flip(img, 1)
    # 转换为灰度图像
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    #人脸检测,返回值为人脸的box参数,左上角坐标(x,y),矩形框的长、宽共4个参数
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.2,
        minNeighbors=5,
        minSize=(32,32)
    )
    # 在检测人脸的基础上检测眼睛
    for (x, y, w, h) in faces:
        fac_gray = gray[y: (y + h), x: (x + w)]
        result = []
        eyes = eyesCascade.detectMultiScale(fac_gray, 1.3, 2)

        # 眼睛坐标的换算,将相对位置换成绝对位置
        for (ex, ey, ew, eh) in eyes:
            result.append((x + ex, y + ey, ew, eh))

    for(x, y, w, h) in faces:
        cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2)

    cv2.imshow('video', img)

    hot_key = cv2.waitKey(1)
    #判断按下的热键是否为Esc
    if hot_key == 27:
        break
#释放摄像头资源
cap.release()
#销毁窗口
cv2.destroyWindow()

It should be noted here that the xml file of the classifier is generally in the data folder of the cv2 installation directory of the openCV library. If the path cannot be found, you can install everything and use cv2 as a keyword to search.
insert image description here
insert image description here
Just replace the path in the code with your own path

achieve effect

insert image description here

Follow-up work plan

  • face recognition
  • Face entry and management
  • Voice Message System
  • GUI

Reference URL:

Code Reference
Image Flip

Guess you like

Origin blog.csdn.net/qq_20728575/article/details/122802740