这段时间闲来没事,突然对opencv的人脸识别比较感兴趣,但因学习能力有限,目前只能做到人脸检测的部分,要是加识别的话,就需要神经网络、模式识别等相关学科了,下面来看程序。
# coding: UTF-8
#引入dlib和opencv这两个库
import dlibimport cv2
#t第一个函数,功能是从图像中检测人脸部分
def detectFact(img):
#利用自带的检测器
detector = dlib.get_frontal_face_detector()
#对目标图像进行采样,貌似是第二个参数越大识别精度越高。
dects = detector(img,1)
#对检测出的模型进行计算
for i,rect in enumerate(dects):
#读取人脸区域坐标
left,right,top,bottom = rect.left(),rect.right(),rect.top(),rect.bottom()print '脸部坐标:(%d,%d),(%d,%d)'%(left,top,right,bottom)
#利用opencv中的函数进行画出人脸方框。(另:dlib库中有自带的方法可以画出人脸)
cv2.rectangle(img,(left,top),(right,bottom),0,0,255),2)# cv2.putText(img,str(i),((left+right)/2,bottom+20),cv2.FONT_HERSHEY_PLAIN,1,(0,255,0),2)
#返回检测出人脸的图像
return img
#从摄像头中获取目标图像
def getVideoFrame():capture = cv2.VideoCapture(1)
cnt = 0
while True:
ret,frame = capture.read()
#这里我设定的是每隔20帧进行一次人脸检测 ,正常情况下的视频中1秒钟是24~30帧。
if cnt%20==0:frame = detectFact(frame)
cv2.imshow('Video',frame)
if cv2.waitKey(10)&0xff == ord('q'):
break
cnt += 1
capture.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
getVideoFrame()