這段時間閑來沒事,突然對opencv的Face Service比較感興趣,但因學習能力有限,目前只能做到臉部偵測的部分,要是加識別的話,就需要神經網路、模式識別等相關學科了,下面來看程式。
# coding: UTF-8
#引入dlib和opencv這兩個庫 import dlib
import 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()