人臉特征提取
本文主要使用dlib庫中的人臉特征識別功能,
dlib庫使用68個特征點標注出人臉特征,通過對應序列的特征點,獲得對應的臉部特征,下圖展示了68個特征點,比如我們要提
取眼睛特征,獲取37到46這幾個特征點即可,

在代碼中增加類似的映射,直接通過呼叫對應部位,
Python學習交流Q群:906715085##3 FACIAL_LANDMARKS_68_IDXS = OrderedDict([ ("mouth", (48, 68)), ("right_eyebrow", (17, 22)), ("left_eyebrow", (22, 27)), ("right_eye", (36, 42)), ("left_eye", (42, 48)), ("nose", (27, 36)), ("jaw", (0, 17))])FACIAL_LANDMARKS_5_IDXS = OrderedDict([ ("right_eye", (2, 3)), ("left_eye", (0, 1)), ("nose", (4))
資料預處理與模型加載
我們按照輸入影像的要求對影像進行變形處理,這里需要轉化為灰度圖,加載get_frontal_face_detector模型和特征庫進行檢測,
Python學習交流Q群:906715085### #加載人臉檢測與關鍵點定位 detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(args["shape_predictor"]) #讀取輸入資料,預處理 image = cv2.imread(args["image"]) (h, w) = image.shape[:2] width=500 r = width / float(w) dim = (width, int(h * r)) image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #人臉檢測rects = detector(gray, 1)
遍歷每個臉部關鍵點
對提取出來的人臉進行特征點預測,對人臉關鍵部位進行定位,同時將其轉化為np_array的形式,
shape = predictor(gray, rect)
shape = shape_to_np(shape)
遍歷每一個部分,復制一個副本進行操作,將當前檢測的類別標識在影像上,
#遍歷每一個部分 for (name, (i, j)) in FACIAL_LANDMARKS_68_IDXS.items(): clone = image.copy() cv2.putText(clone, name, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
根據識別出來的位置,將特征點畫在影像上,
for (x, y) in shape[i:j]: cv2.circle(clone, (x, y), 3, (0, 0, 255), -1)
提取出該五官部位,
(x, y, w, h) = cv2.boundingRect(np.array([shape[i:j]])) roi = image[y:y + h, x:x + w] (h, w) = roi.shape[:2] width=250 r = width / float(w) dim = (width, int(h * r)) roi = cv2.resize(roi, dim, interpolation=cv2.INTER_AREA)
最后展示出來即可,
cv2.imshow("ROI", roi) cv2.imshow("Image", clone) cv2.waitKey(0)
最終效果
原圖
臉部檢測

全部五官檢測


關鍵部位檢測






轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458485.html
標籤:Python
