Python--Dlib庫人臉檢測

Dlib

一些關於dlib的介紹
在這裏主要實現一下人臉檢測,dlib人臉檢測主要是基於HOG-SVM,與opencv人臉檢測【之前寫的博客】的人臉檢測有區別,相比之下,dlib識別精度更高,在微小遮擋的情況下也能識別。(不過也要具體情況具體分析,某些人臉反而opencv能檢測出來)但是dlib人臉識別的圖片大小最好大於80X80,纔會有比較好的識別效果。另外,dlib還能進行一個68個關鍵點的定位。
如果想要更高的識別精度,因爲我之前做實驗識別的數據都是單人頭像,所以我直接簡單粗暴的把這兩個結合在一起了。寫個if else哈哈哈哈哈
不過話說,安裝dlib庫還真麻煩,需要另外下載好多其他庫,還要下載個VS。我記得我安裝找了好多教程,廢了點功夫才裝好。
實現:

import dlib
import cv2

# 使用 Dlib 的正面人臉檢測器 frontal_face_detector
detector = dlib.get_frontal_face_detector()

# 圖片所在路徑
img = cv2.imread(r'C:\Users\lenovo\Desktop\0.jpg')
# img = cv2.resize(img,(64,64))
# img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)


# 生成 Dlib 的圖像窗口
# win = dlib.image_window()
# win.set_image(img)

# 使用detector檢測器來檢測圖像中的人臉
# dlib.pyramid_up(img)
faces = detector(img, 1)
if len(faces) >= 1:
    print("人臉數 / faces in all:", len(faces))
    for i, d in enumerate(faces):
        print("第", i + 1, "個人臉的矩形框座標:",
              "left:", d.left(), '\t', "right:", d.right(), '\t', "top:", d.top(), '\t', "bottom:", d.bottom())
        img=cv2.rectangle(img, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]), (0, 255, 255), 2)

else:
    print("no face")

cv2.namedWindow("img", 2)
cv2.imshow("img", img)
cv2.waitKey(0)

# 繪製矩陣輪廓
# win.add_overlay(faces)
# 保持圖像
# dlib.hit_enter_to_continue()

測試一張圖:
和我上一篇博客測試的圖一樣,結果我發現dlib並沒有全部識別出。所以說還是看具體自己要識別的數據集的。
在這裏插入圖片描述
我又換了一張像素比較大的試了一下,可以全部識別了。
在這裏插入圖片描述
關鍵點定位:

# 實例化 detector
	detector = dlib.get_frontal_face_detector()
	predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
    img = cv2.imread(r'C:\Users\lenovo\Desktop\2.JPG')

    # 人臉數rects
    rects = detector(img, 1)
    print(len(rects))
    print(rects)
    for i in range(len(rects)):
        landmarks = np.matrix([[p.x, p.y] for p in predictor(img, rects[i]).parts()])
        print(predictor(img, rects[i]).parts())
        for idx, point in enumerate(landmarks):
            # 68點的座標
            pos = (point[0, 0], point[0, 1])
            print(idx, pos)

            # 利用cv2.circle給每個特徵點畫一個圈,共68個
            cv2.circle(img, pos, 5, color=(0, 255, 0))
            # 利用cv2.putText輸出1-68
            font = cv2.FONT_HERSHEY_SIMPLEX
            # cv2.putText(img, str(idx + 1), pos, font, 0.8, (0, 0, 255), 1, cv2.LINE_AA)

    cv2.namedWindow("img", 2)
    cv2.imshow("img", img)
    cv2.waitKey(0)

測試一張圖
原圖
在這裏插入圖片描述
結果
在這裏插入圖片描述
關鍵點要加載的參數:
鏈接:https://pan.baidu.com/s/1KcdIckj9vfs1sMka87EJRg
提取碼:ju3e
完整版見my github
其中有實現批量處理的代碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章