✅ MediaPipe face_detection + drawing_utils + PiCamera2:完整教學(在 RP5 可跑的版本)
📦 安裝套件(若你能成功安裝 mediapipe)
pip install mediapipe==0.10.9 opencv-python
sudo apt install python3-picamera2
📁 程式碼:face_detection_picamera2_mediapipe.py
import cv2
import mediapipe as mp
from picamera2 import Picamera2
import time
# 初始化 MediaPipe 的 face detection 和 drawing utils
mp_face_detection = mp.solutions.face_detection
mp_drawing = mp.solutions.drawing_utils
# 初始化 PiCamera2
picam2 = Picamera2()
picam2.preview_configuration.main.size = (640, 480)
picam2.preview_configuration.main.format = "RGB888"
picam2.configure("preview")
picam2.start()
time.sleep(2)
# 建立 FaceDetection 模組
with mp_face_detection.FaceDetection(model_selection=0, min_detection_confidence=0.5) as face_detection:
while True:
# 捕捉影像
frame = picam2.capture_array()
image = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
# 偵測人臉
results = face_detection.process(image)
# 畫出人臉方框與關鍵點
if results.detections:
for detection in results.detections:
mp_drawing.draw_detection(image, detection)
cv2.imshow('MediaPipe Face Detection (PiCamera2)', image)
if cv2.waitKey(1) & 0xFF == 27:
break
cv2.destroyAllWindows()
picam2.stop()
🎯 關鍵說明
| 元件 | 說明 |
|---|---|
FaceDetection(model_selection=0) |
適用近距離(自拍距離)的人臉偵測 |
draw_detection(image, detection) |
會畫出偵測到的人臉方框與關鍵點 |
min_detection_confidence=0.5 |
只顯示高信心的人臉 |
✅ 成功畫面會看到什麼?
-
綠色或紫色方框標示人臉
-
鼻子 / 嘴角 / 眼睛上方可能會標出關鍵點
⚠️ 注意:如果你在 Raspberry Pi 5 上出現以下錯誤
ERROR: No matching distribution found for mediapipe
請改用上一版的 mediapipe.tasks 解法,因為 mediapipe 原版不支援 ARM 安裝,除非你:
-
使用 特定 Docker + Build wheel
-
或從原始碼用 Bazel 自行編譯(需耗時數小時)
📌 如果你仍想用這版,提供我你的 Python 架構與 OS:
請下指令:
python3 -c "import platform; print(platform.machine())"
若為:
-
x86_64:可以直接使用mediapipe(桌機版 OK) -
aarch64:請用mediapipe[tasks]替代(Raspberry Pi 較穩)
文章標籤
全站熱搜
