参考OpenCV自带的例子,30行Python代码实现人脸检测,不得不说,Python这个语言的优势太明显了,几乎把所有复杂的细节都屏蔽了,虽然效率较差,不过在调用OpenCV的模块时,因为模块都是C语言编写,所以在效率上并不会比用C或者C++编写慢太多。本例子使用自带的级联分类器。
#!/usr/bin/env python
import cv2
def faceDetect(img, face_cascade):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
return img
def main():
cap = cv2.VideoCapture(1)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
#frame = imread("2017-02-26-200818.jpg")
# Our operations on the frame come here
if ret == True:
frame = faceDetect(frame, face_cascade)
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()