[python]代码库
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
def detect_faces(image):
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
return faces
def main():
image = cv2.imread('test.jpg')
faces = detect_faces(image)
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('Faces Detected', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
[代码运行效果截图]