此工作為本人近期做人臉情緒識別,CBAM模塊前是否能加人臉關鍵點檢測而做的嘗試。由于創新點不是在于檢測點的標注,而是CBAM的改進,因此,只是借用了現成庫Dilb與cv2進行。
首先,下載人臉關鍵點預測模型:Index of /files,文件:shape_predictor_68_face_landmarks.dat
邏輯如下:
? ?使用cv2庫進行圖像讀取--->
? ?將讀取的圖像轉為灰度圖--->
? ?判斷該圖是否存在face--->否--->return
? ?將讀取的圖像輸入預測模型--->
? ?進行關鍵點預測--->(存儲關鍵點位置)
? ?在原圖上進行關鍵點標識--->
? ?保存預測后的圖。
效果圖如下:(使用fer2013數據集)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
Python代碼如下:
import os
import cv2
import dlib
import numpy as np# init
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("./shape_predictor_68_face_landmarks.dat")def process_image(image_path, output_dir="output", point_radius=0.1):os.makedirs(output_dir, exist_ok=True)# cv2 read imageimage = cv2.imread(image_path)# image to graygray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)faces = detector(gray, 1)if len(faces) == 0:print(f"no face!:{image_path}")return None# get pointlandmarks = predictor(gray, faces[0])landmarks = np.array([[p.x, p.y] for p in landmarks.parts()])# draw key point for facefor (x, y) in landmarks:cv2.circle(image, (x, y), radius=point_radius, color=(0, 255, 0), thickness=-1)output_path = os.path.join(output_dir, f"processed_{os.path.basename(image_path)}")cv2.imwrite(output_path, image)print(f"Saved:{output_path}")return landmarksif __name__=="__main__":landmarks = process_image(image_path="./00001.png",output_dir="./processed_00001",point_radius=1 # 關鍵點半徑 只能為整型)