1. 程式人生 > >dlib 呼叫cnn人臉檢測

dlib 呼叫cnn人臉檢測

本文呼叫訓練好的卷積神經網路進行人臉檢測,首先需要下載訓練好的模型mmod_human_face_detector.dat,模型下載連結為:http://dlib.net/files/mmod_human_face_detector.dat.bz2

程式碼實現:

import dlib
import cv2

# 匯入cnn模型
cnn_face_detector = dlib.cnn_face_detection_model_v1('mmod_human_face_detector.dat')    #呼叫訓練好的cnn進行人臉檢測

img = cv2.imread("b.jpg")        # opencv 讀取圖片,並顯示
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)        # 取灰度

rects = cnn_face_detector(img, 1)       # 進行檢測
print("Number of faces detected: {}".format(len(rects)))     # 列印檢測到的人臉數

# 遍歷返回的結果
# 返回的結果是一個mmod_rectangles物件。這個物件包含有2個成員變數:dlib.rectangle類,表示物件的位置;dlib.confidence,表示置信度。
for i, d in enumerate(rects):
    face = d.rect
    print("Detection {}: Left: {} Top: {} Right: {} Bottom: {} Confidence: {}".format(i, face.left(), face.top(), face.right(), d.rect.bottom(), d.confidence))
    
    #cv2.rectangle()畫出矩形,引數1:影象,引數2:矩形左上角座標,引數3:矩形右下角座標,引數4:畫線對應的rgb顏色,引數5:線的寬度
    cv2.rectangle(img, (face.left(),face.top()), (face.right(),face.bottom()), (0,0,255),2)

cv2.namedWindow("img", 2)      # #圖片視窗可調節大小  
cv2.imshow("img", img)       #顯示影象
cv2.waitKey(0)      #等待按鍵,然後退出

執行結果: