1 import cv2 as cv 2 def face_detect_demo(img): 3 #将图片灰度 4 gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY) 5 #加载特征数据 6 face_detector = cv.CascadeClassifier( 7 'D:/Opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml') 8 faces = face_detector.detectMultiScale(gray) 9 for x,y,w,h in faces: 10 cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2) 11 cv.circle(img,center=(x+w//2,y+h//2),radius=(w//2),color=(0,255,0),thickness=2) 12 cv.imshow('result',img) 13 #读取视频 14 cap = cv.VideoCapture('C:/Users/87823/Desktop/video.mp4') 15 while True: 16 flag,frame=cap.read() 17 print('flag:',flag,'frame.shape:',frame.shape) 18 if not flag: 19 break 20 face_detect_demo(frame) 21 if ord('q') == cv.waitKey(10): 22 break 23 cv.destroyAllWindows() 24 cap.release()