python用dlib關鍵點將人臉背景區域去除

2021-08-04 02:03:09 字數 1932 閱讀 8043

話不多說,先上**:

shape = list(img.shape) + [3] # 將影象轉化為列表,便於訪問

img1 = img.copy()

for i in xrange(shape[0]):

for j in xrange(shape[1]):

ifnot inside(j, i, region):

img1[i, j] = (0, 0, 0)

win.set_image(img1)

def

get_landmarks

(img):

dets = detector(img, 1)

landmarks = np.zeros((19,2))

for k, d in enumerate(dets):

shape = predictor(img, d)

for i in range(17):

landmarks[i] = (shape.part(i).x, shape.part(i).y)

landmarks[17] = (shape.part(24).x, shape.part(24).y - 20)

landmarks[18] = (shape.part(19).x, shape.part(19).y - 20)

return landmarks

這裡不需要之前dlib所有的68個關鍵點,重新構建了乙個landmarks矩陣,儲存臉頰17個點和眉毛2個中間點,總共19個關鍵點; 注意這裡landmarks 要用 np.zeros((19,2))來建立;

為了後面訪問landmarks的邊,這裡需要將19,24兩個眉毛的位置調一下位置,放入landmarks中17,18兩個位置。

獲取完關鍵點後,複製img1 = img.copy(),img1用於獲取我們所需的目標。遍歷img1,用inside(j, i, region)判斷不在關鍵點區域內的點(注意這裡由於shape[0]和shape[1]的問題,呼叫inside()函式時需要將i,j順序變換一下),將這些點的畫素置0(img1[i, j] = (0, 0, 0));

inside(j, i, region)函式如下:

def

inside

(x,y,region):

j=len(region)-1

flag=false

for i in range(len(region)):

if (region[i][1]and region[j][1]>=y or region[j][1]and region[i][1]>=y):

if (region[i][0] + (y - region[i][1]) / (region[j][1] - region[i][1]) * (region[j][0] - region[i][0]) < x):

flag =not flag

j=ireturn flag

這個函式網上有很多解釋,邊的遍歷順序為(18->0->1->2->3->4->5->6->7->8->9->10->11->12->13->14->15->16->17->18)。

下面是背景區域去除後的效果:

python安裝dlib,關鍵點檢測

python 安裝dlib face landmark detection dlib是人臉識別比較有名的庫,有c python的介面。使用dlib可以大大簡化開發,比如人臉識別,特徵點檢測之類的工作都可以很輕鬆實現。關於dlib的安裝,直接執行pip install dlib即可。e.g.pip i...

dlib人臉關鍵點檢測器訓練 194關鍵點

68個關鍵點的訓練資料集 1.7gb 194個關鍵點的資料集 需要翻牆 dlib中examples中的 dlib examples train shape predictor ex.cpp dlib examples train shape predictor ex.cpp include incl...

Opencv與dlib聯合進行人臉關鍵點檢測與識別

依賴庫 opencv 2.4.9 dlib 19.0 libfacedetection 本篇不記錄如何配置,重點在實現上。使用libfacedetection實現人臉區域檢測,聯合dlib標記人臉特徵點,最後使用opencv的facerecognizer實現人臉識別。訓練模組 人臉檢測 獲取人臉區域...