movenet_singlepose_detection.py

# 本作品采用MIT许可证授权。
# 版权所有 (c) 2013-2026 OpenMV LLC。保留所有权利。
# https://github.com/openmv/openmv/blob/master/LICENSE
#
# 此示例展示了Google的MoveNet姿态估计模型。
#
# 注意:此示例需要带NPU的OpenMV摄像头(如AE3或N6)才能实时运行。

import csi
import time
import ml
from ml.postprocessing.mediapipe import MoveNet

# 初始化传感器。
csi0 = csi.CSI()
csi0.reset()
csi0.pixformat(csi.RGB565)
csi0.framesize(csi.VGA)

# 加载内置的姿态检测模型
model = ml.Model("/rom/movenet_singlepose_192.tflite", postprocess=MoveNet(threshold=0.4))
print(model)

# 身体关节之间的连线,用于绘制人体骨架。
body_lines = ((0, 1), (0, 2), (1, 3), (2, 4), (0, 5), (0, 6), (5, 6), (5, 7),
              (7, 9), (6, 8), (8, 10), (5, 11), (6, 12), (11, 12), (11, 13), (13, 15),
              (12, 14), (14, 16))


# 移除低置信度的关键点以及与之相连的骨架线。
def filter_keypoints(keypoints, threshold=0.4):
    valid = {i for i, kp in enumerate(keypoints) if kp[2] > threshold}
    remap = {old: new for new, old in enumerate(sorted(valid))}
    f_keypoints = [kp for i, kp in enumerate(keypoints) if i in valid]
    f_body_lines = [(remap[a], remap[b]) for a, b in body_lines if a in valid and b in valid]
    return f_keypoints, f_body_lines


clock = time.clock()
while True:
    clock.tick()
    img = csi0.snapshot()

    # joints是由((x, y, w, h), score, keypoints)元组组成的列表
    joints = model.predict([img])

    # 在检测到的人周围绘制边界框和关键点。
    for r, score, keypoints in joints:
        ml.utils.draw_predictions(img, [r], ("person",), ((0, 0, 255),), format=None)

        # keypoints:身体关节的ndarray (17, 3),每个为(x, y, score)
        # 索引遵循COCO约定:
        # 0:鼻子
        # 1:左眼,2:右眼
        # 3:左耳,4:右耳
        # 5:左肩,6:右肩
        # 7:左肘,8:右肘
        # 9:左腕,10:右腕
        # 11:左髋,12:右髋
        # 13:左膝,14:右膝
        # 15:左踝,16:右踝
        f_keypoints, f_body_lines = filter_keypoints(keypoints)
        ml.utils.draw_skeleton(img, f_keypoints, f_body_lines,
                               kp_color=(255, 0, 0), line_color=(0, 255, 0))

    print(clock.fps(), "fps")

results matching ""

    No results matching ""