一、图片中的人脸检测
import cv2 as cv
image = cv.imread("D:/by2.png")
cv.imshow("input",image)
h,w = image.shape[:2]
detector = cv.CascadeClassifier(cv.data.haarcascades+"haarcascade_frontalface_alt.xml")
faces = detector.detectMultiScale(image,scaleFactor=1.10,minNeighbors=3,
minSize=(30,30),maxSize=(w//2,h//2))
for x,y,width,heigh in faces:
cv.rectangle(image,(x,y),(x+width,y+heigh),(0,0,255),2,cv.LINE_8,0)
cv.imshow("faces",image)
cv.waitKey(0)
cv.destroyAllWindows()
在上面的代码中,我们人脸检测使用的是cv2…CascadeClassifier()函数,它可以检测图片中所有的人脸。在该函数中,各参数和返回值的含义为:
①image:待检测图像,通常为灰度图像。
②scaleFactor:表示前后两次的扫描中,搜索窗口的缩放比例。
③minNeighbors:表示构成检测目标的相邻矩形的最小个数,一般默认为3,如果把这个值设置更大,那么有可能会检测不到人脸。
④minSize:目标的最小尺寸,小于这个尺寸的目标会被忽略。
⑤maxSize:目标的最大尺寸,大于这个尺寸的目标会被忽略。
二、视频中的人脸检测
import cv2 as cv
#image = cv.imread("D:/by2.png")
capture = cv.VideoCapture("D:/renlian.mp4")
detector = cv.CascadeClassifier(cv.data.haarcascades+"haarcascade_frontalface_alt.xml")
while True:
ret,image = capture.read()
if ret is True:
cv.imshow("input",image)
faces = detector.detectMultiScale(image,scaleFactor=1.10,minNeighbors=5,
minSize=(30,30),maxSize=(200,200))#加载人脸检测器
for x,y,width,heigh in faces:
cv.rectangle(image,(x,y),(x+width,y+heigh),(0,0,255),2,cv.LINE_8,0)
cv.imshow("faces",image)
c = cv.waitKey(20)
if c == 27:
break
else:
break
cv.waitKey()
cv.destroyAllWindows()
我用的是领导人十八大报告的视频,就不放出来了。