一、识别图像中的人脸
haarcascade_frontalface_alt_tree.xml
lbpcascade_frontalcatface.xml
GitHub上有Haar级联检测器源代码可自行下载,lbp级联检测器也一样有源码可自行下载
也一样
import cv2 as cv
import numpy as npdef face_detect(image):gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)#转成灰度图face_detector = cv.CascadeClassifier(r"G:\Juptyer_workspace\study\opencv\opencv3\haarcascade_frontalface_alt_tree.xml")#级联检测器faces = face_detector.detectMultiScale(gray, 1.1, 2)#多个尺度空间进行查找人脸#第三个参数2 表示附近出现两个检测结果即可,两个矩形框for x, y, w, h in faces:cv.rectangle(image, (x, y), (x+w, y+h), (0, 0, 255), 2)#绘制矩形框cv.imshow("result", image)src = cv.imread(r"G:\Juptyer_workspace\study\opencv\opencv3\pyy.jpg")
cv.namedWindow("result", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
face_detect(src)
cv.waitKey(0)
cv.destroyAllWindows()
效果图如下:
(我的男神)
二、识别视频中的人脸
import cv2 as cv
import numpy as npdef face_detect(image):gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)#转成灰度图face_detector = cv.CascadeClassifier(r"G:\Juptyer_workspace\study\opencv\opencv3\haarcascade_frontalface_alt_tree.xml")#级联检测器faces = face_detector.detectMultiScale(gray, 1.1, 2)#多个尺度空间进行查找人脸#第三个参数2 表示附近出现两个检测结果即可,两个矩形框for x, y, w, h in faces:cv.rectangle(image, (x, y), (x+w, y+h), (0, 0, 255), 1)#绘制矩形框cv.imshow("result", image)capture = cv.VideoCapture(r"G:\Juptyer_workspace\study\opencv\opencv3\beyond.mp4")#参数为0。表示调用本地摄像头
cv.namedWindow("result", cv.WINDOW_AUTOSIZE)
while(True):ret, frame = capture.read()frame = cv.flip(frame, 1)face_detect(frame)c = cv.waitKey(10)if c == 27: # ESCbreakcv.waitKey(0)
cv.destroyAllWindows()
效果图如下:
(我的信仰)