hand_landmarks_single_hand.py
# この作品はMITライセンスの下で提供されています。
# Copyright (c) 2013-2025 OpenMV LLC. 全著作権所有。
# https://github.com/openmv/openmv/blob/master/LICENSE
#
# この例は、単一の手を対象としたGoogleのMediaPipe Hand Landmarks Detectionモデルを紹介します。
#
# 注記:この例をリアルタイムで実行するには、AE3やN6のようなNPU搭載のOpenMV Camが必要です。
import csi
import time
import ml
from ml.preprocessing import Normalization
from ml.postprocessing.mediapipe import BlazePalm
from ml.postprocessing.mediapipe import HandLandmarks
# センサーを初期化します。
csi0 = csi.CSI()
csi0.reset()
csi0.pixformat(csi.RGB565)
csi0.framesize(csi.VGA)
# BlazePalmは、最良の結果を得るために正方形の画像を必要とします。
# HandLandmarksは、BlazePalmでクロップされた非正方形の画像でも動作します。
csi0.window((400, 400))
# 内蔵の手のひら検出モデルをロード
palm_detection = ml.Model("/rom/palm_detection_full_192.tflite", postprocess=BlazePalm(threshold=0.4))
print(palm_detection)
# 内蔵の手のランドマーク検出モデルをロード
hand_landmarks = ml.Model("/rom/hand_landmarks_full_224.tflite", postprocess=HandLandmarks(threshold=0.4))
print(hand_landmarks)
# 手の骨格を描画するための、手の関節間を結ぶ線。
hand_lines = ((0, 1), (1, 2), (2, 3), (3, 4), (0, 5), (5, 6), (6, 7), (7, 8),
(5, 9), (9, 10), (10, 11), (11, 12), (9, 13), (13, 14), (14, 15), (15, 16),
(13, 17), (17, 18), (18, 19), (19, 20), (0, 17))
# トラッキング用変数。
n = None
clock = time.clock()
while True:
clock.tick()
img = csi0.snapshot()
if n is None:
# palms は ((x, y, w, h), score, keypoints) タプルのリストです
for r, score, keypoints in palm_detection.predict([img]):
# rect は (x, y, w, h) - 手のランドマークモデル用に3倍に拡大
wider_rect = (r[0] - r[2], r[1] - r[3], r[2] * 3, r[3] * 3)
# 検出された手のひらのROIのみを対象に処理
n = Normalization(roi=wider_rect)
else:
# hands は ((x, y, w, h), score, keypoints) タプルのリストです
# インデックス0(存在する場合)は左手
# インデックス1(存在する場合)は右手
hands = hand_landmarks.predict([n(img)])
# 手が検出されなかった場合、トラッカーをリセットします。
if not hands:
n = None
continue
# 検出された手とキーポイントの周囲にバウンディングボックスを描画します。
for i, detections in enumerate(hands):
for r, score, keypoints in detections:
ml.utils.draw_predictions(img, [r], ("right",) if i else ("left",), ((0, 0, 255),), format=None)
# keypoints:手の関節の (x, y, z) を表す ndarray (21, 3)
# インデックスはMediaPipeの規則に従います:
# 0:手首
# 親指:1 cmc、2 mcp、3 ip、4 tip
# 人差し指:5 mcp、6 pip、7 dip、8 tip
# 中指:9 mcp、10 pip、11 dip、12 tip
# 薬指:13 mcp、14 pip、15 dip、16 tip
# 小指:17 mcp、18 pip、19 dip、20 tip
# (cmc=付け根、mcp=関節、pip=中節、dip=末節、ip=親指関節、tip=指先)
ml.utils.draw_skeleton(img, keypoints, hand_lines, kp_color=(255, 0, 0), line_color=(0, 255, 0))
# トラッキングのため、new_wider_rect を手の中心に合わせる
new_wider_rect = (r[0] + (r[2] // 2) - (wider_rect[2] // 2),
r[1] + (r[3] // 2) - (wider_rect[3] // 2),
wider_rect[2],
wider_rect[3])
# 検出された手のROIのみを対象に処理
n = Normalization(roi=new_wider_rect)
print(clock.fps(), "fps")