Mediapipe-姿態估計實例

Mediapipe簡介

Mediapipe 是由 Google Research 開發的一款開源框架,旨在幫助開發者輕松地構建、測試和部署復雜的多模態、多任務的機器學習模型。它特別擅長于實時處理和分析音頻、視頻等多媒體數據。以下是 Mediapipe 的一些關鍵特點和組件:

關鍵特點

  1. 多平臺支持:Mediapipe 支持在多個平臺上運行,包括桌面、移動設備和網頁。這使得開發者可以輕松地將模型部署到不同的平臺上。

  2. 高效的實時處理:Mediapipe 具有高度優化的性能,能夠在資源受限的設備上進行實時處理。這使其特別適合于移動設備和嵌入式系統。

  3. 模塊化設計:Mediapipe 使用圖表(graph)來組織和連接不同的處理模塊。這種設計使得開發者可以靈活地組合和復用不同的處理組件。

  4. 豐富的預構建解決方案:Mediapipe 提供了許多預構建的解決方案,如人臉檢測、手部追蹤、姿態估計等,開發者可以直接使用這些解決方案來快速構建應用。

主要組件

  1. 圖表(Graph):Mediapipe 的核心是其圖表結構,圖表定義了數據流和處理模塊的連接方式。每個圖表由一系列節點(nodes)和邊(edges)組成,節點表示具體的處理模塊,邊表示數據在節點之間的流動。

  2. 節點(Nodes):節點是圖表的基本單元,表示具體的處理操作。Mediapipe 提供了許多內置的節點,如數據輸入輸出節點、圖像處理節點、機器學習推理節點等。

  3. 數據包(Packets):數據包是圖表中傳輸的數據單元,節點之間通過發送和接收數據包來通信。數據包可以包含各種類型的數據,如圖像幀、音頻信號、檢測結果等。

  4. 計算機視覺解決方案:Mediapipe 提供了許多預構建的計算機視覺解決方案,這些解決方案已經高度優化,能夠在實時應用中使用。常見的解決方案包括人臉檢測、手部追蹤、姿態估計、對象檢測等。

常見使用場景

  1. 姿態估計(Pose Estimation):Mediapipe 可以實時檢測和追蹤人體的關鍵點(如肩膀、肘部、膝蓋等),并估計人體的姿態。這對于體育訓練、動作捕捉、增強現實等應用非常有用。

  2. 手部追蹤(Hand Tracking):Mediapipe 能夠檢測和追蹤手部的關鍵點,提供手勢識別和手部動作分析的能力。這在手勢控制、虛擬現實、手寫輸入等應用中有廣泛的應用。

  3. 人臉檢測(Face Detection):Mediapipe 提供了高效的人臉檢測和關鍵點追蹤功能,可以用于面部識別、表情分析、虛擬化妝等場景。

  4. 對象檢測(Object Detection):Mediapipe 還提供了實時的對象檢測解決方案,可以用于監控、無人駕駛、智能家居等領域。

示例代碼

以下是一個使用 Mediapipe 進行姿態估計的簡單示例:

import cv2
import mediapipe as mp# Initialize mediapipe pose class.
mp_pose = mp.solutions.pose
pose = mp_pose.Pose()# Initialize mediapipe drawing class, useful for annotation.
mp_drawing = mp.solutions.drawing_utils# Load the video file or start webcam capture.
cap = cv2.VideoCapture(0)  # Use 0 for webcam, or provide video file pathwhile cap.isOpened():ret, frame = cap.read()if not ret:break# Convert the BGR image to RGB.image_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)# Process the image and detect the pose.result = pose.process(image_rgb)# Draw the pose annotation on the image.if result.pose_landmarks:mp_drawing.draw_landmarks(frame, result.pose_landmarks, mp_pose.POSE_CONNECTIONS)# Display the frame with pose landmarks.cv2.imshow('Pose Estimation', frame)# Break the loop if 'q' is pressed.if cv2.waitKey(10) & 0xFF == ord('q'):break# Release the video capture object and close display window.
cap.release()
cv2.destroyAllWindows()

這段代碼使用 Mediapipe 的姿態估計功能,讀取視頻流并實時繪制人體的關鍵點。你可以使用攝像頭實時捕捉人體姿態,也可以處理預錄制的視頻文件。

實例1-讀取視頻流并進行骨骼點繪制:

import cv2
import mediapipe as mp# Initialize mediapipe pose class.
mp_pose = mp.solutions.pose
pose = mp_pose.Pose()# Initialize mediapipe drawing class, useful for annotation.
mp_drawing = mp.solutions.drawing_utils# Load the video file.
cap = cv2.VideoCapture('D:/basketball.mp4')# Check if the video is opened successfully.
if not cap.isOpened():print("Error: Could not open video.")exit()while cap.isOpened():ret, frame = cap.read()if not ret:print("Reached the end of the video.")break# Convert the BGR image to RGB.image_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)# Process the image and detect the pose.result = pose.process(image_rgb)# Draw the pose annotation on the image.if result.pose_landmarks:mp_drawing.draw_landmarks(frame, result.pose_landmarks, mp_pose.POSE_CONNECTIONS)# Display the frame with pose landmarks.cv2.imshow('Pose Estimation', frame)# Break the loop if 'q' is pressed.if cv2.waitKey(10) & 0xFF == ord('q'):break# Release the video capture object and close display window.
cap.release()
cv2.destroyAllWindows()

效果如下:
在這里插入圖片描述

實例2-讀取視頻流中姿態估計與3D繪制:

代碼如下:

import cv2
import mediapipe as mp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from matplotlib.animation import FuncAnimation# Initialize mediapipe pose class.
mp_pose = mp.solutions.pose
pose = mp_pose.Pose()# Initialize mediapipe drawing class, useful for annotation.
mp_drawing = mp.solutions.drawing_utils# Load the video file.
cap = cv2.VideoCapture('D:/basketball.mp4')# Check if the video is opened successfully.
if not cap.isOpened():print("Error: Could not open video.")exit()fig = plt.figure(figsize=(10, 5))
ax2d = fig.add_subplot(121)
ax3d = fig.add_subplot(122, projection='3d')def update(frame_number):ret, frame = cap.read()if not ret:print("Reached the end of the video.")return# Convert the BGR image to RGB.image_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)# Process the image and detect the pose.result = pose.process(image_rgb)# Clear the previous plotsax2d.clear()ax3d.clear()# Draw the pose annotation on the image.if result.pose_landmarks:mp_drawing.draw_landmarks(frame, result.pose_landmarks, mp_pose.POSE_CONNECTIONS)# Extract the landmark points.landmarks = result.pose_landmarks.landmarkxs = [landmark.x for landmark in landmarks]ys = [landmark.y for landmark in landmarks]zs = [landmark.z for landmark in landmarks]# Plot 2D imageax2d.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))ax2d.set_title('Pose Estimation')ax2d.axis('off')# Plot 3D landmarksax3d.scatter(xs, ys, zs, c='blue', marker='o')ax3d.set_xlim([0, 1])ax3d.set_ylim([0, 1])ax3d.set_zlim([-1, 1])ax3d.set_xlabel('X')ax3d.set_ylabel('Y')ax3d.set_zlabel('Z')ax3d.set_title('3D Pose Landmarks')ani = FuncAnimation(fig, update, interval=10)plt.show()cap.release()
cv2.destroyAllWindows()

效果如下:
在這里插入圖片描述
為了將三維骨骼點連接起來,可以使用 mpl_toolkits.mplot3d.art3d.Line3DCollection 來繪制骨骼連接。你需要定義這些連接的點對,并在三維圖中使用它們來繪制線條。以下是更新后的代碼:

import cv2
import mediapipe as mp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Line3DCollection
import numpy as np
from matplotlib.animation import FuncAnimation# Initialize mediapipe pose class.
mp_pose = mp.solutions.pose
pose = mp_pose.Pose()# Initialize mediapipe drawing class, useful for annotation.
mp_drawing = mp.solutions.drawing_utils# Load the video file.
cap = cv2.VideoCapture('D:/basketball.mp4')# Check if the video is opened successfully.
if not cap.isOpened():print("Error: Could not open video.")exit()fig = plt.figure(figsize=(10, 5))
ax2d = fig.add_subplot(121)
ax3d = fig.add_subplot(122, projection='3d')def update(frame_number):ret, frame = cap.read()if not ret:print("Reached the end of the video.")return# Convert the BGR image to RGB.image_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)# Process the image and detect the pose.result = pose.process(image_rgb)# Clear the previous plotsax2d.clear()ax3d.clear()# Draw the pose annotation on the image.if result.pose_landmarks:mp_drawing.draw_landmarks(frame, result.pose_landmarks, mp_pose.POSE_CONNECTIONS)# Extract the landmark points.landmarks = result.pose_landmarks.landmarkxs = [landmark.x for landmark in landmarks]ys = [landmark.y for landmark in landmarks]zs = [landmark.z for landmark in landmarks]# Define the connections between landmarksconnections = [(0, 1), (1, 2), (2, 3), (3, 7), (0, 4), (4, 5), (5, 6), (6, 8),(9, 10), (11, 12), (11, 13), (13, 15), (15, 17), (15, 19), (15, 21),(17, 19), (12, 14), (14, 16), (16, 18), (16, 20), (16, 22), (18, 20),(11, 23), (12, 24), (23, 24), (23, 25), (24, 26), (25, 27), (26, 28),(27, 29), (28, 30), (29, 31), (30, 32)]# Create a list of 3D lineslines = [[(xs[start], ys[start], zs[start]), (xs[end], ys[end], zs[end])] for start, end in connections]# Plot 2D imageax2d.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))ax2d.set_title('Pose Estimation')ax2d.axis('off')# Plot 3D landmarks and connectionsax3d.scatter(xs, ys, zs, c='blue', marker='o')ax3d.add_collection3d(Line3DCollection(lines, colors='blue', linewidths=2))ax3d.set_xlim([0, 1])ax3d.set_ylim([0, 1])ax3d.set_zlim([-1, 1])ax3d.set_xlabel('X')ax3d.set_ylabel('Y')ax3d.set_zlabel('Z')ax3d.set_title('3D Pose Landmarks')ani = FuncAnimation(fig, update, interval=10)plt.show()cap.release()
cv2.destroyAllWindows()

在這個代碼中,我們定義了 connections 列表,它包含了骨骼點之間的連接對。然后我們創建了一個 lines 列表,用于存儲這些連接的三維線段,并使用 ax3d.add_collection3d(Line3DCollection(lines, colors='blue', linewidths=2)) 方法將這些線段添加到三維圖中。

運行這個腳本后,三維圖中不僅會顯示骨骼點,還會將這些點連起來,形成完整的骨骼結構。
效果如下:
在這里插入圖片描述
上面的代碼看似三維圖的骨骼是倒立的,你可以調整三維圖的坐標顯示,以使得骨骼結構顯示為正常的人體姿態。可以通過設置三維圖的坐標軸范圍和方向來調整顯示效果。以下是修改后的代碼,調整了坐標軸的范圍和方向,以使骨骼結構正常顯示:

import cv2
import mediapipe as mp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Line3DCollection
import numpy as np
from matplotlib.animation import FuncAnimation# Initialize mediapipe pose class.
mp_pose = mp.solutions.pose
pose = mp_pose.Pose()# Initialize mediapipe drawing class, useful for annotation.
mp_drawing = mp.solutions.drawing_utils# Load the video file.
cap = cv2.VideoCapture('D:/basketball.mp4')# Check if the video is opened successfully.
if not cap.isOpened():print("Error: Could not open video.")exit()fig = plt.figure(figsize=(10, 5))
ax2d = fig.add_subplot(121)
ax3d = fig.add_subplot(122, projection='3d')def update(frame_number):ret, frame = cap.read()if not ret:print("Reached the end of the video.")return# Convert the BGR image to RGB.image_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)# Process the image and detect the pose.result = pose.process(image_rgb)# Clear the previous plotsax2d.clear()ax3d.clear()# Draw the pose annotation on the image.if result.pose_landmarks:mp_drawing.draw_landmarks(frame, result.pose_landmarks, mp_pose.POSE_CONNECTIONS)# Extract the landmark points.landmarks = result.pose_landmarks.landmarkxs = [landmark.x for landmark in landmarks]ys = [landmark.y for landmark in landmarks]zs = [-landmark.z for landmark in landmarks]  # Negate the z-axis for better visualization# Define the connections between landmarksconnections = [(0, 1), (1, 2), (2, 3), (3, 7), (0, 4), (4, 5), (5, 6), (6, 8),(9, 10), (11, 12), (11, 13), (13, 15), (15, 17), (15, 19), (15, 21),(17, 19), (12, 14), (14, 16), (16, 18), (16, 20), (16, 22), (18, 20),(11, 23), (12, 24), (23, 24), (23, 25), (24, 26), (25, 27), (26, 28),(27, 29), (28, 30), (29, 31), (30, 32)]# Create a list of 3D lineslines = [[(xs[start], ys[start], zs[start]), (xs[end], ys[end], zs[end])] for start, end in connections]# Plot 2D imageax2d.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))ax2d.set_title('Pose Estimation')ax2d.axis('off')# Plot 3D landmarks and connectionsax3d.scatter(xs, ys, zs, c='blue', marker='o')ax3d.add_collection3d(Line3DCollection(lines, colors='blue', linewidths=2))ax3d.set_xlim([0, 1])ax3d.set_ylim([1, 0])  # Flip the y-axis for better visualizationax3d.set_zlim([1, -1])ax3d.set_xlabel('X')ax3d.set_ylabel('Y')ax3d.set_zlabel('Z')ax3d.set_title('3D Pose Landmarks')ani = FuncAnimation(fig, update, interval=10)plt.show()cap.release()
cv2.destroyAllWindows()

在這個代碼中:

  1. 通過取反 zs 坐標 (zs = [-landmark.z for landmark in landmarks]),使得骨骼點的 Z 軸方向與預期一致。
  2. 通過設置 ax3d.set_ylim([1, 0]) 來翻轉 Y 軸的方向,以便更符合常見的視覺習慣。

運行這個腳本后,三維圖中的骨骼結構應會顯示為正常的人體姿態。
顯示效果如下:
在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/44871.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/44871.shtml
英文地址,請注明出處:http://en.pswp.cn/web/44871.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

基于微信小程序的音樂播放平臺

基于微信小程序的音樂播放平臺 音樂播放小程序項目簡介技術棧功能模塊項目流程系統E-R圖項目頁面 音樂播放小程序 項目簡介 微信音樂小程序旨在提供一個簡潔高效的音樂播放平臺,用戶可以方便地搜索、播放和收藏自己喜歡的音樂。整個項目采用前后端分離的架構&…

WIN10開機突然,過一會就自動重啟藍屏DRIVER_IRQL_NOT_LESS_OR_EQUAL

環境: Win10 專業版 DELL7080 問題描述: WIN10開機突然,過一會就自動重啟藍屏DRIVER_IRQL_NOT_LESS_OR_EQUAL 事件日志 解決方案: 1.找到MEMORY.DMP文件內容,分析一下 Microsoft (R) Windows Debugger Version 10…

主機安全-開源HIDS字節跳動Elkeid安裝使用

目錄 概述什么是HIDSHIDS與NIDS的區別EDR、XDR是啥? Elkeid架構Elkeid Agent && Agent centerElkeid DriverElkeid RASPElkeid HUBService DiscoveryManager安裝數據采集規則&告警 參考 概述 什么是HIDS HIDS( host-based intrusion detec…

使用Gitee倉庫鏡像管理功能實現Gitee與Github 雙向同步

進入你所需要同步的倉庫,點擊「管理」->「鏡像倉庫管理」,點擊「添加鏡像」選項; 如果你的Gitee賬號還沒有綁定過 GitHub 帳號,先根據彈窗的提示綁定 GitHub 帳號; 添加鏡像時候,在「鏡像方向」中選擇…

二次開發源碼 借貸系統uniapp/借貸認證系統/小額信貸系統/工薪貸APP/資金貸系統h5

前端:UNIAPP 后端:ThinkPHP 數據庫: Mysql 前端使用的uniapp 可以打包APP H5 小程序 系統提供了完善的網絡借貸體系,為金融中介平臺提供從獲客到貸后管理全流程服務,解決了借貸手續繁瑣、流程緩慢等問題 此源碼為運營…

ES6操作符使用總結

最近做新項目時候用到了ES6 添加的一些運算符,使用起來很方便,簡化了代碼,增強了代碼容錯性。使用感不錯,下面做了總結,本文也會持續維護。 1. !!props.useDefaultColor 這個技巧的作用是將任何 JavaScript 值轉換為…

管理Linux本地用戶和組

什么是用戶 用戶賬戶在可以運行命令的不同人員和程序之間提供安全界限。 在Linux系統中,系統通過分配唯一的標識號(用戶ID或UID)來區分不同的用戶帳戶。 在Linux系統中,用戶帳戶有以下三種主要類型: 超級用戶 負責…

分布式一致性算法:Raft學習

分布式一致性算法:Raft學習 1 什么是分布式系統? 分布式系統是由一組通過網絡進行通信、為了完成共同的任務而協調工作的計算機節點組成的系統。這些節點可能位于不同的物理位置,但它們協同工作以提供一個統一的計算平臺或服務。分布式系統…

對于復雜的數學模型,怎樣利用 MATLAB 的優化工具箱進行準確的參數估計和模型擬合?

要利用MATLAB的優化工具箱進行準確的參數估計和模型擬合,可以按照以下步驟進行: 定義模型:根據問題的需求和數學模型的形式,定義好模型的數學表達式。 收集數據:收集實際觀測數據,這些數據將用于擬合模型和…

Ubuntu linux安裝新版本go

加速網站:GOPROXY.IO - A Global Proxy for Go Modules 下載地址:All releases - The Go Programming Language Ubuntu jammy版本里面自帶的go版本較低,build ollama的時候報錯,于是升級go 升級操作 從上面下載地址找到自己需…

25秋招面試算法題 (Go版本)

文章目錄 科大訊飛 0713找01不能出現太多 科大訊飛 0713 找01 牛牛擁有一個長度為 n 的01 串,現在他想知道,對于每個字符,在它前面的最近的不同字符的下標是多少? 輸入描述 本題為多組測試數據,第一行輸入一個正整…

代碼隨想錄第五十五天打卡

42. 接雨水 接雨水這道題目是 面試中特別高頻的一道題,也是單調棧 應用的題目,大家好好做做。 建議是掌握 雙指針 和單調棧,因為在面試中 寫出單調棧可能 有點難度,但雙指針思路更直接一些。 在時間緊張的情況有,能寫出…

Unity中一鍵生成具有身體感知的虛擬人物動作

在虛擬現實(VR)和增強現實(AR)的浪潮中,如何讓虛擬人物的動作更加自然、真實,已經成為一個重要課題。AI4Animation項目,一個由 Sebastian Starke 主導的開源框架,為Unity開發者提供了強大的工具集,以實現這一目標。本文…

OrangePi AIpro在安防領域的深思和實戰(曠視科技CNN模型ShuffleNetV1開發案例測試)

一、前言 公司最近有個項目是安防領域的,主要用在邊緣結點,雖然已做成形,但是還是存在一些缺陷,例如:算力問題,開發板的成熟問題,已經各種技術的解決方案落地問題。目前我們集成了很多功能&…

Facebook 開源計算機視覺 (CV) 和 增強現實 (AR) 框架 Ocean

Ocean 是一個獨立于平臺的框架,支持所有主要操作系統,包括 iOS、Android、Quest、macOS、Windows 和 Linux。它旨在徹底改變計算機視覺和混合現實應用程序的開發。 Ocean 主要使用 C 編寫,包括計算機視覺、幾何、媒體處理、網絡和渲染&#x…

python中的pickle模塊和json模塊

目錄 pickle: Python 中的pickle 是一個內置模塊,用于序列化和反序列化 Python 對象結構。序列化是將對象轉換成字節流的過程,這樣對象就可以被存儲到文件中或者通過網絡傳輸。反序列化則是將這些字節流重新轉換成原始對象的過程。 json: json模塊是 …

實現多層感知機

目錄 多層感知機: 介紹: 代碼實現: 運行結果: 問題答疑: 線性變換與非線性變換 參數含義 為什么清除梯度? 反向傳播的作用 為什么更新權重? 多層感知機: 介紹:…

taocms 3.0.1 本地文件泄露漏洞(CVE-2021-44983)

前言 CVE-2021-44983 是一個影響 taoCMS 3.0.1 的遠程代碼執行(RCE)漏洞。該漏洞允許攻擊者通過上傳惡意文件并在服務器上執行任意代碼來利用這一安全缺陷。 漏洞描述 taoCMS 是一個內容管理系統(CMS),用于創建和管…

持續集成的自動化之旅:Gradle在CI中的配置秘籍

持續集成的自動化之旅:Gradle在CI中的配置秘籍 引言 持續集成(Continuous Integration, CI)是現代軟件開發中的一項基礎實踐,它通過自動化的構建和測試流程來提高軟件質量和開發效率。Gradle作為一個靈活的構建工具,…

【眼疾病識別】圖像識別+深度學習技術+人工智能+卷積神經網絡算法+計算機課設+Python+TensorFlow

一、項目介紹 眼疾識別系統,使用Python作為主要編程語言進行開發,基于深度學習等技術使用TensorFlow搭建ResNet50卷積神經網絡算法,通過對眼疾圖片4種數據集進行訓練(‘白內障’, ‘糖尿病性視網膜病變’, ‘青光眼’, ‘正常’&…