版权声明:本文为博主原创文章,博主欢迎各位转载。 https://blog.csdn.net/tuwenqi2013/article/details/80106722
推荐博文:
3、《Face Recognition with Python》
代码:
import cv2
import sys
# Get user supplied values
imagePath = 'test.png' # sys.argv[1]
cascPath = "haarcascade_frontalface_default.xml" #训练后的分类器
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2, #比例因子
minNeighbors=2, #最小邻脸数
minSize=(30, 30) #窗口大小
#flags = cv2.CV_HAAR_SCALE_IMAGE
)
print("Found {0} faces!".format(len(faces)))
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Faces found", image)
cv2.waitKey(0)
效果:
修改成实时人脸识别模式(有点容易误判)
代码:
import cv2
import sys
import numpy as np
# Get user supplied values
cap =cv2.VideoCapture(0) # sys.argv[1]
cascPath = "haarcascade_frontalface_default.xml" #训练后的分类器
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1, #比例因子
minNeighbors=3, #最小邻距
minSize=(30, 30) #窗口大小
)
print("Found {0} faces!".format(len(faces)))
for (x, y, w, h) in faces:
cv2.rectangle( frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Faces found", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
效果: