1 import cv2 as cv 2 def face_detect_demo(): 3 # 将图片转化为灰度图片 4 gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY) 5 # 加载特征数据 6 face_detector = cv.CascadeClassifier('D:/Opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml') 7 faces = face_detector.detectMultiScale(gray,scaleFactor=1.01,minNeighbors=4,maxSize=(30,30)) 8 for x,y,w,h in faces: 9 print(x,y,w,h) 10 cv.rectangle(img,(x,y),(x+w,y+h),color=(0,255,0),thickness=2) 11 cv.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,0,255),thickness=2) 12 cv.imshow('result',img) 13 # 加载图片 14 img = cv.imread('C:/Users/87823/Desktop/NBA2.jfif') 15 face_detect_demo() 16 cv.waitKey(0) 17 cv.destroyAllWindows()