Python 3 利用 Dlib 實現攝像頭實時人臉檢測和平鋪顯示


 

1. 引言

  在某些場景下,我們不僅需要進行實時人臉檢測追蹤,還要進行再加工;這里進行攝像頭實時人臉檢測,並對於實時檢測的人臉進行初步提取;

  單個/多個人臉檢測,並依次在攝像頭窗口,實時平鋪顯示檢測到的人臉;

圖 1 動態實時檢測效果圖

 

  檢測到的人臉矩形圖像,會依次 平鋪顯示 在攝像頭的左上方;

  當多個人臉時候,也能夠依次鋪開顯示;

  左上角窗口的大小會根據捕獲到的人臉大小實時變化;

圖 2 單個/多個人臉情況下攝像頭識別顯示結果

 

2. 代碼實現

  主要分為三個部分:

 

2.1 攝像頭調用

  Python 中利用 OpenCv 調用攝像頭的一個例子 how_to_use_camera.py :

 1 # OpenCv 調用攝像頭
 2 # 默認調用筆記本攝像頭
 3 
 4 # Author:   coneypo
 5 # Blog:     http://www.cnblogs.com/AdaminXie
 6 # GitHub:   https://github.com/coneypo/Dlib_face_cut
 7 # Mail:     coneypo@foxmail.com
 8 
 9 import cv2
10 
11 cap = cv2.VideoCapture(0)
12 
13 # cap.set(propId, value)
14 # 設置視頻參數: propId - 設置的視頻參數, value - 設置的參數值
15 cap.set(3, 480)
16 
17 # cap.isOpened() 返回 true/false, 檢查攝像頭初始化是否成功
18 print(cap.isOpened())
19 
20 # cap.read()
21 """ 
22 返回兩個值
23     先返回一個布爾值, 如果視頻讀取正確, 則為 True, 如果錯誤, 則為 False; 
24     也可用來判斷是否到視頻末尾;
25     
26     再返回一個值, 為每一幀的圖像, 該值是一個三維矩陣;
27     
28     通用接收方法為: 
29         ret,frame = cap.read();
30         ret: 布爾值;
31         frame: 圖像的三維矩陣;
32         這樣 ret 存儲布爾值, frame 存儲圖像;
33         
34         若使用一個變量來接收兩個值, 如:
35             frame = cap.read()
36         則 frame 為一個元組, 原來使用 frame 處需更改為 frame[1]
37 """
38 
39 while cap.isOpened():
40     ret_flag, img_camera = cap.read()
41     cv2.imshow("camera", img_camera)
42 
43     # 每幀數據延時 1ms, 延時為0, 讀取的是靜態幀
44     k = cv2.waitKey(1)
45 
46     # 按下 's' 保存截圖
47     if k == ord('s'):
48         cv2.imwrite("test.jpg", img_camera)
49 
50     # 按下 'q' 退出
51     if k == ord('q'):
52         break
53 
54 # 釋放所有攝像頭
55 cap.release()
56 
57 # 刪除建立的所有窗口
58 cv2.destroyAllWindows()

 

2.2 人臉檢測

  利用 Dlib 正向人臉檢測器, dlib.get_frontal_face_detector()

  對於本地人臉圖像文件,一個利用 Dlib 進行人臉檢測的例子:

  face_detector_v2_use_opencv.py :

 1 # created at 2017-11-27
 2 # updated at 2018-09-06
 3 
 4 # Author:   coneypo
 5 # Dlib:     http://dlib.net/
 6 # Blog:     http://www.cnblogs.com/AdaminXie/
 7 # Github:   https://github.com/coneypo/Dlib_examples
 8 
 9 # create object of OpenCv
10 # use OpenCv to read and show images
11 
12 import dlib
13 import cv2
14 
15 # 使用 Dlib 的正面人臉檢測器 frontal_face_detector
16 detector = dlib.get_frontal_face_detector()
17 
18 # 圖片所在路徑
19 # read image
20 img = cv2.imread("imgs/faces_2.jpeg")
21 
22 # 使用 detector 檢測器來檢測圖像中的人臉
23 # use detector of Dlib to detector faces
24 faces = detector(img, 1)
25 print("人臉數 / Faces in all: ", len(faces))
26 
27 # Traversal every face
28 for i, d in enumerate(faces):
29     print("", i+1, "個人臉的矩形框坐標:",
30           "left:", d.left(), "right:", d.right(), "top:", d.top(), "bottom:", d.bottom())
31     cv2.rectangle(img, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]), (0, 255, 255), 2)
32 
33 cv2.namedWindow("img", 2)
34 cv2.imshow("img", img)
35 cv2.waitKey(0)

 

圖 3 參數 d.top(), d.right(), d.left(), d.bottom() 位置坐標說明

 

2.3 圖像裁剪

  如果想訪問圖像的某點像素,對於 opencv 對象可以利用索引 img [height] [width]

    存儲像素其實是一個三維數組,先 高度 height,然后 寬度 width;

    返回的是一個顏色數組( 0-255,0-255,0-255 ),按照( B, G, R )的順序;

    比如 藍色 就是(255,0,0),紅色 是(0,0,255);

  所以要做的就是對於檢測到的人臉,要依次平鋪填充到攝像頭顯示的實時幀 img_rd 中;

  所以進行圖像裁剪填充這塊的代碼如下(注意要防止截切平鋪的圖像不能超出 640x480 ):

# 檢測到人臉
if len(faces) != 0:
    # 記錄每次開始寫入人臉像素的寬度位置
    faces_start_width = 0

    for face in faces:
        # 繪制矩形框
        cv2.rectangle(img_rd, tuple([face.left(), face.top()]), tuple([face.right(), face.bottom()]),
                      (0, 255, 255), 2)

        height = face.bottom() - face.top()
        width = face.right() - face.left()

        ### 進行人臉裁減 ###
        # 如果沒有超出攝像頭邊界
        if (face.bottom() < 480) and (face.right() < 640) and \
                ((face.top() + height) < 480) and ((face.left() + width) < 640):
            # 填充
            for i in range(height):
                for j in range(width):
                    img_rd[i][faces_start_width + j] = \
                        img_rd[face.top() + i][face.left() + j]

        # 更新 faces_start_width 的坐標
        faces_start_width += width

 

   記得要更新 faces_start_width 的坐標,達到依次平鋪的效果:

 

 

圖 4 平鋪顯示的人臉

 

2.4. 完整源碼

  faces_from_camera.py:

 1 # 調用攝像頭實時單個/多個人臉檢測,並依次在攝像頭窗口,實時平鋪顯示檢測到的人臉;
 2 
 3 # Author:   coneypo
 4 # Blog:     http://www.cnblogs.com/AdaminXie
 5 # GitHub:   https://github.com/coneypo/Dlib_face_cut
 6 
 7 import dlib
 8 import cv2
 9 import time
10 
11 # 儲存截圖的目錄
12 path_screenshots = "data/images/screenshots/"
13 
14 detector = dlib.get_frontal_face_detector()
15 predictor = dlib.shape_predictor('data/dlib/shape_predictor_68_face_landmarks.dat')
16 
17 # 創建 cv2 攝像頭對象
18 cap = cv2.VideoCapture(0)
19 
20 # 設置視頻參數,propId 設置的視頻參數,value 設置的參數值
21 cap.set(3, 960)
22 
23 # 截圖 screenshots 的計數器
24 ss_cnt = 0
25 
26 while cap.isOpened():
27     flag, img_rd = cap.read()
28 
29     # 每幀數據延時 1ms,延時為 0 讀取的是靜態幀
30     k = cv2.waitKey(1)
31 
32     # 取灰度
33     img_gray = cv2.cvtColor(img_rd, cv2.COLOR_RGB2GRAY)
34 
35     # 人臉數
36     faces = detector(img_gray, 0)
37 
38     # 待會要寫的字體
39     font = cv2.FONT_HERSHEY_SIMPLEX
40 
41     # 按下 'q' 鍵退出
42     if k == ord('q'):
43         break
44     else:
45         # 檢測到人臉
46         if len(faces) != 0:
47             # 記錄每次開始寫入人臉像素的寬度位置
48             faces_start_width = 0
49 
50             for face in faces:
51                 # 繪制矩形框
52                 cv2.rectangle(img_rd, tuple([face.left(), face.top()]), tuple([face.right(), face.bottom()]),
53                               (0, 255, 255), 2)
54 
55                 height = face.bottom() - face.top()
56                 width = face.right() - face.left()
57 
58                 ### 進行人臉裁減 ###
59                 # 如果沒有超出攝像頭邊界
60                 if (face.bottom() < 480) and (face.right() < 640) and \
61                         ((face.top() + height) < 480) and ((face.left() + width) < 640):
62                     # 填充
63                     for i in range(height):
64                         for j in range(width):
65                             img_rd[i][faces_start_width + j] = \
66                                 img_rd[face.top() + i][face.left() + j]
67 
68                 # 更新 faces_start_width 的坐標
69                 faces_start_width += width
70 
71             cv2.putText(img_rd, "Faces in all: " + str(len(faces)), (20, 350), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)
72 
73         else:
74             # 沒有檢測到人臉
75             cv2.putText(img_rd, "no face", (20, 350), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)
76 
77         # 添加說明
78         img_rd = cv2.putText(img_rd, "Press 'S': Screen shot", (20, 400), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)
79         img_rd = cv2.putText(img_rd, "Press 'Q': Quit", (20, 450), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)
80 
81     # 按下 's' 鍵保存
82     if k == ord('s'):
83         ss_cnt += 1
84         print(path_screenshots + "screenshot" + "_" + str(ss_cnt) + "_" + time.strftime("%Y-%m-%d-%H-%M-%S",
85                                                                                         time.localtime()) + ".jpg")
86         cv2.imwrite(path_screenshots + "screenshot" + "_" + str(ss_cnt) + "_" + time.strftime("%Y-%m-%d-%H-%M-%S",
87                                                                                               time.localtime()) + ".jpg",
88                     img_rd)
89 
90     cv2.namedWindow("camera", 1)
91     cv2.imshow("camera", img_rd)
92 
93 # 釋放攝像頭
94 cap.release()
95 
96 # 刪除建立的窗口
97 cv2.destroyAllWindows()

 

這個代碼就是把之前做的人臉檢測,圖像拼接幾個結合起來,代碼量也很少,只有100行,如有問題可以參考之前博客:

  Python 3 利用 Dlib 進行人臉檢測

  Python 3 利用 Dlib 實現人臉檢測和剪切

 

人臉檢測對於機器性能占用不高,但是如果要進行實時的圖像裁剪拼接,計算量可能比較大,所以可能會出現卡頓; 

 

# 請尊重他人勞動成果,轉載或者使用源碼請注明出處:http://www.cnblogs.com/AdaminXie

# 如果對您有幫助,歡迎在 GitHub 上 Star 支持下: https://github.com/coneypo/Dlib_face_cut

# 如有問題請留言或者聯系郵箱 coneypo@foxmail.com,商業合作勿擾


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM