Day10 面部關鍵點檢測 Face Landmark Detection
🟡 先看看程式的效果
今天這個程式碼範例展示了如何使用 OpenCV 和 MediaPipe 來進行即時面部偵測。程式首先透過攝影機捕捉即時影像, 並會偵測影像中的面部,並使用 MediaPipe 的繪圖工具在影像上標示出偵測到的面部 Landmarks, 比昨天的例子更細緻, 不過需要處理的數據會變得更多。
Today’s code example demonstrates how to perform real-time facial detection using OpenCV and MediaPipe. The program first captures real-time images through the camera and detects faces in the images. It then uses MediaPipe’s drawing tools to mark the detected facial landmarks on the image. This example is more detailed than yesterday’s, but it also involves processing more data.
🟡 學習目標
使用 MediaPipe 進行面部偵測,理解如何初始化和使用其模組來偵測面部 Landmarks。
🟡 程式碼
請先下載 “Face Landmark Detection 面部關鍵點檢測.py”
請按此下載
'''
Python + AI in 21 days
https://jasonworkshop.com/python
Designed by Jason Workshop
[請勿修改以上內容]
---
預備工作:
首先,請確保已安裝 opencv-python, mediapipe 模組
如不確定可直接在 Windows 的 cmd prompt 執行以下指定
pip install opencv-python mediapipe
'''
import cv2
import mediapipe as mp
# 初始化 MediaPipe Face Mesh 模組
mp_face_mesh = mp.solutions.face_mesh
face_mesh = mp_face_mesh.FaceMesh(static_image_mode=False, max_num_faces=1, min_detection_confidence=0.7) # max_num_faces 為最多面部偵測量, min_detection_confidence 為最低可信度
mp_drawing = mp.solutions.drawing_utils
# 開啟攝影機
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 轉換 BGR 圖像到 RGB
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 偵測面部
result = face_mesh.process(rgb_frame)
# 繪製面部關鍵點和連線
if result.multi_face_landmarks:
for face_landmarks in result.multi_face_landmarks:
mp_drawing.draw_landmarks(
image=frame,
landmark_list=face_landmarks,
connections=mp_face_mesh.FACEMESH_TESSELATION,
landmark_drawing_spec=mp_drawing.DrawingSpec(color=(0, 255, 0), thickness=1, circle_radius=1),
connection_drawing_spec=mp_drawing.DrawingSpec(color=(255, 255, 255), thickness=1, circle_radius=1))
# 顯示圖像
cv2.imshow('Face Landmark Detection', frame)
if cv2.waitKey(1) & 0xFF == 27: # 按下 ESC 鍵退出
break
# 釋放攝影機並關閉所有視窗
cap.release()
cv2.destroyAllWindows()
😁 明天見!