原文towardsdatascience.com/real-time-hand-tracking-and-gesture-recognition-with-mediapipe-rerun-showcase-9ec57cb0c831?sourcecollection_archive---------4-----------------------#2024-03-05如何使用 Rerun 可视化 MediaPipe 的手部追踪与手势识别https://andreasnaoum.medium.com/?sourcepost_page---byline--9ec57cb0c831--------------------------------https://towardsdatascience.com/?sourcepost_page---byline--9ec57cb0c831-------------------------------- Andreas Naoum·发布于 Towards Data Science ·8 分钟阅读·2024 年 3 月 5 日–https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/8ec748453f3b800b051414e9d6c7ca7b.png手部追踪与手势识别 | 作者提供的图片在这篇文章中我将展示一个使用MediaPipePython和Rerun SDK进行的手部追踪和手势识别示例。如果你有兴趣深入了解并扩展你的理解我将指导你如何安装MediaPipePython和Rerun SDK以便进行手部追踪、识别不同手势并可视化数据。因此你将学习如何安装 MediaPipe Python 和 Rerun如何使用 MediaPipe 手势识别 进行手部追踪与手势识别如何在 Rerun Viewer 中可视化手部追踪和手势识别的结果如果你迫不及待想尝试这个示例可以直接使用提供的代码# Clone the rerun GitHub repository to your local machine.git clone https://github.com/rerun-io/rerun# Navigate to the rerun repository directory.cd rerun# Install the required Python packages specified in the requirements filepip install-r examples/python/gesture_detection/requirements.txt# Run the main Python script for the examplepython examples/python/gesture_detection/main.py# Run the main Python script for a specific imagepython examples/python/gesture_detection/main.py--image path/to/your/image.jpg# Run the main Python script for a specific videopython examples/python/gesture_detection/main.py--video path/to/your/video.mp4# Run the main Python script with camera streampython examples/python/gesture_detection/main.py--camera手部追踪和手势识别技术在我们继续之前先对使这一切成为可能的技术给予应有的认可。手部追踪和手势识别技术旨在赋予设备解读手部动作和手势作为指令或输入的能力。在这项技术的核心一种预训练的机器学习模型分析视觉输入并识别手部地标和手势。这项技术的实际应用范围广泛手部动作和手势可用于控制智能设备。人机交互、机器人学、游戏和增强现实是这项技术潜在应用最有前景的一些领域。然而我们在使用此类技术时应时刻保持警觉。因为模型可能会误解手势且假阳性或假阴性的可能性不容忽视所以在敏感和关键系统中使用它是非常具有挑战性的。利用这项技术还可能带来伦理和法律方面的问题因为用户可能不希望在公共场所被记录他们的手势。如果你打算在现实世界的场景中实施这项技术考虑任何伦理和法律问题是非常重要的。前提条件与设置首先你需要安装必要的库包括 OpenCV、MediaPipe 和 Rerun。MediaPipe Python是一个方便的工具供开发者在计算机视觉和机器学习领域集成设备端 ML 解决方案Rerun是一个用于可视化随时间变化的多模态数据的 SDK。# Install the required Python packages specified in the requirements filepip install-r examples/python/gesture_detection/requirements.txt然后你需要从此处下载预定义模型HandGestureClassifier使用 MediaPipe 进行手部追踪和手势识别https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/47ff9b3771ef5e9e98811c796da311bf.png图片来自 手势识别任务指南 由 Google 提供“MediaPipe 手势识别任务允许你实时识别手势并提供识别到的手势结果以及检测到的手的地标。你可以使用此任务识别用户的特定手势并调用与这些手势对应的应用功能。” 引自 手势识别任务指南现在让我们尝试使用 MediaPipe 预训练模型进行手势识别处理一张示例图像。总体而言以下代码为初始化和配置 MediaPipe 手势识别解决方案奠定了基础。frommediapipe.tasks.pythonimportvisionfrommediapipe.tasksimportpythonclassGestureDetectorLogger:def__init__(self,video_mode:boolFalse):self._video_modevideo_mode base_optionspython.BaseOptions(model_asset_pathgesture_recognizer.task)optionsvision.GestureRecognizerOptions(base_optionsbase_options,running_modemp.tasks.vision.RunningMode.VIDEOifself._video_modeelsemp.tasks.vision.RunningMode.IMAGE)self.recognizervision.GestureRecognizer.create_from_options(options)defdetect(self,image:npt.NDArray[np.uint8])-None:imagemp.Image(image_formatmp.ImageFormat.SRGB,dataimage)# Get results from Gesture Detection modelrecognition_resultself.recognizer.recognize(image)fori,gestureinenumerate(recognition_result.gestures):# Get the top gesture from the recognition resultprint(Top Gesture Result: ,gesture[0].category_name)ifrecognition_result.hand_landmarks:# Obtain hand landmarks from MediaPipehand_landmarksrecognition_result.hand_landmarksprint(Hand Landmarks: str(hand_landmarks))# Obtain hand connections from MediaPipemp_hands_connectionsmp.solutions.hands.HAND_CONNECTIONSprint(Hand Connections: str(mp_hands_connections))GestureDetectorLogger类中的detect函数接受一张图片作为参数并打印模型结果突出显示识别出的手势及检测到的手部地标。有关模型的更多细节请参考其模型卡片。https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/af87cc0b5c9dacee7900b4dab9433aee.png图片来源手势识别任务指南 由Google提供你可以使用以下代码亲自尝试defrun_from_sample_image(path)-None:imagecv2.imread(str(path))show_imagecv2.cvtColor(image,cv2.COLOR_BGR2RGB)loggerGestureDetectorLogger(video_modeFalse)logger.detect_and_log(show_image)# Run the gesture recognition on a sample imagerun_from_sample_image(SAMPLE_IMAGE_PATH)使用 Rerun 进行验证、调试和演示这一步骤帮助你确保解决方案的可靠性和有效性。现在模型已经准备好接下来可视化结果以验证准确性调试潜在问题并展示其功能。使用 Rerun SDK可以简单快速地实现结果的可视化。我们如何使用 Rerunhttps://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/dd9474d4f31555cc7fc2c9f655597e18.png图片来源Rerun 文档 由Rerun提供通过使用 Rerun SDK 记录数据将多模态数据从代码流式传输可视化并与实时或录制的流进行交互无论是本地的还是远程的互动式构建布局并自定义可视化在需要时扩展 Rerun在进入代码之前你应该访问页面安装 Rerun 查看器来安装查看器。然后我强烈建议通过阅读以下指南来熟悉 Rerun SDKPython 快速入门和在 Python 中记录数据。这些初始步骤将确保顺利设置并帮助你开始接下来的代码实现。从视频或实时运行对于视频流使用了 OpenCV。你可以选择特定视频的文件路径或者通过提供参数 0 或 1 来访问你自己的摄像头使用 0 为默认摄像头在 Mac 上你可以使用 1。值得注意的是要强调时间轴的介绍。Rerun 时间轴的功能使得可以将数据与一个或多个时间轴关联。因此视频的每一帧都与其对应的时间戳相关联。defrun_from_video_capture(vid:int|str,max_frame_count:int|None)-None: Run the detector on a video stream. Parameters ---------- vid: The video stream to run the detector on. Use 0/1 for the default camera or a path to a video file. max_frame_count: The maximum number of frames to process. If None, process all frames. capcv2.VideoCapture(vid)fpscap.get(cv2.CAP_PROP_FPS)detectorGestureDetectorLogger(video_modeTrue)try:it:Iterable[int]itertools.count()ifmax_frame_countisNoneelserange(max_frame_count)forframe_idxintqdm.tqdm(it,descProcessing frames):ret,framecap.read()ifnotret:breakifnp.all(frame0):continueframe_time_nanoint(cap.get(cv2.CAP_PROP_POS_MSEC)*1e6)ifframe_time_nano0:frame_time_nanoint(frame_idx*1000/fps*1e6)framecv2.cvtColor(frame,cv2.COLOR_BGR2RGB)rr.set_time_sequence(frame_nr,frame_idx)rr.set_time_nanos(frame_time,frame_time_nano)detector.detect_and_log(frame,frame_time_nano)rr.log(Media/Video,rr.Image(frame))exceptKeyboardInterrupt:passcap.release()cv2.destroyAllWindows()为可视化记录数据https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/669757c874516e02624cf43b52a69a60.png使用 Rerun SDK 记录 2D 数据 | 图片来源作者要在 Rerun 查看器中可视化数据必须使用 Rerun SDK 记录数据。前面提到的指南提供了关于这一过程的深入见解。在这个上下文中我们提取手部地标点作为归一化值然后利用图像的宽度和高度将其转换为图像坐标。这些坐标随后作为2D 点记录到 Rerun SDK 中。此外我们识别地标之间的连接并将其作为2D 线段记录。对于手势识别结果会打印到控制台。然而在源代码中你可以探索一种方法通过TextDocument和表情符号将这些结果呈现给查看器。classGestureDetectorLogger:defdetect_and_log(self,image:npt.NDArray[np.uint8],frame_time_nano:int|None)-None:# Recognize gestures in the imageheight,width,_image.shape imagemp.Image(image_formatmp.ImageFormat.SRGB,dataimage)recognition_result(self.recognizer.recognize_for_video(image,int(frame_time_nano/1e6))ifself._video_modeelseself.recognizer.recognize(image))# Clear the valuesforlog_keyin[Media/Points,Media/Connections]:rr.log(log_key,rr.Clear(recursiveTrue))fori,gestureinenumerate(recognition_result.gestures):# Get the top gesture from the recognition resultgesture_categorygesture[0].category_nameifrecognition_result.gestureselseNoneprint(Gesture Category: ,gesture_category)# Log the detected gestureifrecognition_result.hand_landmarks:hand_landmarksrecognition_result.hand_landmarks# Convert normalized coordinates to image coordinatespointsself.convert_landmarks_to_image_coordinates(hand_landmarks,width,height)# Log points to the image and Hand Entityrr.log(Media/Points,rr.Points2D(points,radii10,colors[255,0,0]))# Obtain hand connections from MediaPipemp_hands_connectionsmp.solutions.hands.HAND_CONNECTIONS points1[points[connection[0]]forconnectioninmp_hands_connections]points2[points[connection[1]]forconnectioninmp_hands_connections]# Log connections to the image and Hand Entityrr.log(Media/Connections,rr.LineStrips2D(np.stack((points1,points2),axis1),colors[255,165,0]))defconvert_landmarks_to_image_coordinates(hand_landmarks,width,height):return[(int(lm.x*width),int(lm.y*height))forhand_landmarkinhand_landmarksforlminhand_landmark]3D 点最后我们研究如何将手部地标呈现为 3D 点。我们首先在初始化函数中使用来自注释上下文的关键点定义点之间的连接然后将它们作为3D 点进行记录。https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/140447578f2915dba04718f2d11f1588.png使用 Rerun SDK 记录 3D 数据 | 图片来自作者classGestureDetectorLogger:–def__init__(self,video_mode:boolFalse):# ... existing code ...rr.log(/,rr.AnnotationContext(rr.ClassDescription(inforr.AnnotationInfo(id0,labelHand3D),keypoint_connectionsmp.solutions.hands.HAND_CONNECTIONS)),timelessTrue,)rr.log(Hand3D,rr.ViewCoordinates.RIGHT_HAND_X_DOWN,timelessTrue)defdetect_and_log(self,image:npt.NDArray[np.uint8],frame_time_nano:int|None)-None:# ... existing code ...ifrecognition_result.hand_landmarks:hand_landmarksrecognition_result.hand_landmarks landmark_positions_3dself.convert_landmarks_to_3d(hand_landmarks)iflandmark_positions_3disnotNone:rr.log(Hand3D/Points,rr.Points3D(landmark_positions_3d,radii20,class_ids0,keypoint_ids[iforiinrange(len(landmark_positions_3d))]),)# ... existing code ...你准备好了让魔法开始吧# For imagerun_from_sample_image(IMAGE_PATH)# For saved videorun_from_video_capture(VIDEO_PATH)# For Real-Timerun_from_video_capture(0)# mac may need 1这个示例的完整源代码可以在GitHub上找到。欢迎随意探索、修改并理解实现的内部工作原理。超越手部跟踪与手势识别https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/e3e98cf7eca2c494781c91cf7e150a09.pngRerun 示例 | 图片来自 Rerun最后如果你对可视化跨多种应用场景的多模态数据流有浓厚兴趣我鼓励你探索Rerun 示例。这些示例展示了潜在的现实世界案例并提供了有关这些可视化技术实际应用的宝贵见解。如果你觉得这篇文章有用且富有启发性更多内容即将发布我定期分享关于机器人技术和计算机视觉可视化的深度内容绝对不容错过。为了获取未来的更新和令人兴奋的项目记得关注我此外你还可以在LinkedIn上找到我。类似文章[## 使用 MediaPipe 进行实时人脸和人脸地标检测Rerun 展示如何轻松地在 2D 和 3D 中可视化 MediaPipe 的人脸和人脸地标检测使用 Rerunai.gopubby.com](https://ai.gopubby.com/real-time-face-and-face-landmark-detection-with-mediapipe-rerun-showcase-40481baa1763?sourcepost_page-----9ec57cb0c831--------------------------------) ## 使用 MediaPipe 进行 2D 和 3D 人体姿态跟踪Rerun 展示如何轻松地通过 Rerun 可视化 MediaPipe 的人体姿态跟踪towardsdatascience.com本页面的部分内容转载自Google创建并分享的作品并根据创意共享 4.0 署名许可协议中的条款使用。