OpenCV 人脸检测

来自CloudWiki
跳转至: 导航搜索

安装包

C:\Users\thinkpad>pip3 install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple

Collecting opencv-python
  Downloading https://files.pythonhosted.org/packages/1f/51/e0b9cef23098bc31c77b0e06221dd8d05119b9782d4c2b1d1482e22b5f5e/opencv_python-4.1.1.26-cp37-cp37m-win_amd64.whl (39.0MB)

代码

 
import cv2
# the path of target image for face detection 
imagePath = r"./face2.jpg" 
facedetect = r"./haarcascade_frontalface_alt2.xml"

# Create the haarcascade
faceCascade = cv2.CascadeClassifier(facedetect)

# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(gray, 1.3,5)

# Draw a rectangle around the faces
for (x, y, w ,h) in faces:
    img = cv2.rectangle(image, (x,y), (x+w, y+h), (0,255,0) , 2)

cv2.imshow("Faces  found" ,image)
cv2.waitKey(0)