介紹一種實現人臉識別最簡單的調包方法。
這裏的人臉分類原理:使用級聯分類器
這裏我們只使用opencv封裝好的api 。
一、首先在github官網上下載用於識別的分類器
地址:https://github.com/opencv/opencv/tree/master/data 這裏的haar和lbp數據文件都是可以使用的,我先下載到本地。
這裏的分類器都是可以使用的。我們就選擇其中一個來使用。
二、代碼如下
1.讀取視頻
def video_io_demo():
capture = cv.VideoCapture(0)
height = capture.get(cv.CAP_PROP_FRAME_HEIGHT)
weight = capture.get(cv.CAP_PROP_FRAME_WIDTH)
count = capture.get(cv.CAP_PROP_FRAME_COUNT) #幀數
fps = capture.get(cv.CAP_PROP_FPS) #頻率:每秒播放幾幀
print(height,weight,count,fps)
type = 0
while(True):
ret,frame = capture.read()
if ret is True:
cv.imshow("video_input",frame)
result = process_frame(frame,type)
cv.imshow("result",result)
c = cv.waitKey(2)
if c > 0:
type = np.abs(c)%3
if c==27:
break
else:
break
2.加載分類器
face_detector = cv.CascadeClassifier("D:/opencv-data/opencv-master/data/haarcascades/haarcascade_frontalface_alt_tree.xml")
這裏也可以改變加載的分類器,可以多嘗試幾種包裏的分類器
3.輸出邊框
def process_frame(frame,type):
if type == 0:
return detect_face(frame)
else:
return frame
def detect_face(frame):
gray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
cv.equalizeHist(gray,gray)
faces = face_detector.detectMultiScale(gray,1.02,1,minSize=(200,200),maxSize=(400,400))
for x,y,w,h in faces:
cv.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2,8,0)
return frame
得到的效果如下:
需要注意的地方:
faces = face_detector.detectMultiScale(gray,1.02,1,minSize=(100,100),maxSize=(300,300)) 裏的參數需要重點關注,用於調整。
(二值圖,
每次圖像尺寸減小的一個比例,
表示每一個目標至少要被檢測到幾次纔會輸出,
設置目標的最小檢測尺寸,
設置目標的最大檢測尺寸。)
調整好目標檢測尺寸可以更有效更快的去檢測和識別。