原文地址:https://www.jb51.net/article/160197.htm
第一种:
1 # -*- coding:utf-8 -*- 2 import cv2 as cv 3 import numpy as np 4 5 src = cv.imread('test1.jpg') 6 path = r'D:face' 7 8 def face_detect_demo(): 9 gray = cv.cvtColor(src,cv.COLOR_BGR2GRAY) 10 11 face_detector = cv.CascadeClassifier('haarcascade_frontalface_default.xml') 12 face_detector.load(path + 'haarcascade_frontalface_default.xml') 13 faces = face_detector.detectMultiScale(gray,1.3,5) 14 for x,y,w,h in faces: 15 cv.rectangle(src,(x,y),(x+w,y+h),(0,0,255),2) 16 cv.imshow("result",src) 17 18 print("--------------python face detect-------------") 19 cv.namedWindow("input image",0) 20 cv.namedWindow("result",0) 21 cv.imshow("input image",src) 22 face_detect_demo() 23 cv.waitKey(0) 24 cv.destroyAllWindows()
效果:
第二种:
1 # -*- coding:utf-8 -*- 2 import cv2 as cv 3 import numpy as np 4 5 src = cv.imread('test1.jpg') 6 path = r'D:face' 7 8 def face_detect_demo(): 9 gray = cv.cvtColor(src,cv.COLOR_BGR2GRAY) 10 11 face_detector = cv.CascadeClassifier('haarcascade_frontalface_default.xml') 12 face_detector.load(path + 'haarcascade_frontalface_default.xml') 13 faces = face_detector.detectMultiScale(gray,1.3,5) 14 for x,y,w,h in faces: 15 cv.rectangle(src,(x,y),(x+w,y+h),(0,0,255),2) 16 cv.imshow("result",src) 17 18 print("--------------python face detect-------------") 19 cv.namedWindow("input image",0) 20 cv.namedWindow("result",0) 21 cv.imshow("input image",src) 22 face_detect_demo() 23 cv.waitKey(0) 24 cv.destroyAllWindows()
效果: