如何将 Mediapipe识别到的骨骼关节运动数据读取并保存
时间: 2023-06-26 18:07:10 浏览: 190
python实时读取串口数据并自动保存至excel
要将Mediapipe识别到的骨骼关节运动数据读取并保存,可以使用Python的OpenCV库和Numpy库。具体步骤如下:
1.导入所需库:
```python
import cv2
import mediapipe as mp
import numpy as np
```
2.创建一个Mediapipe的骨骼关节模型对象:
```python
mp_drawing = mp.solutions.drawing_utils
mp_pose = mp.solutions.pose
```
3.读取视频或摄像头图像,创建一个视频流:
```python
cap = cv2.VideoCapture(0) #打开摄像头
```
4.循环读取视频流中的每一帧图像:
```python
while True:
ret, frame = cap.read() # 读取一帧图像
if not ret:
break
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # 将图像从BGR模式转换为RGB模式,以在Mediapipe中使用
```
5.调用Mediapipe的骨骼关节模型,对当前帧图像进行关节识别:
```python
with mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose:
results = pose.process(frame)
```
6.从results中获取关节位置信息,并将其保存到一个Numpy数组中:
```python
if results.pose_landmarks:
landmarks = np.zeros((33, 3)) # 创建一个33行3列的数组,用于保存关节信息
for i, landmark in enumerate(results.pose_landmarks.landmark):
landmarks[i] = [landmark.x, landmark.y, landmark.z] # 将每个关节的位置信息保存到数组中
```
7.在窗口中绘制出骨骼关节信息:
```python
mp_drawing.draw_landmarks(
frame, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)
cv2.imshow('MediaPipe Pose', frame) # 显示窗口
```
8.将关节信息保存到文件中:
```python
np.savetxt('landmarks.txt', landmarks) # 将关节信息保存到文件中
```
9.释放资源,关闭窗口:
```python
cap.release() # 释放资源
cv2.destroyAllWindows() # 关闭窗口
```
完整代码如下:
```python
import cv2
import mediapipe as mp
import numpy as np
mp_drawing = mp.solutions.drawing_utils
mp_pose = mp.solutions.pose
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
with mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose:
results = pose.process(frame)
if results.pose_landmarks:
landmarks = np.zeros((33, 3))
for i, landmark in enumerate(results.pose_landmarks.landmark):
landmarks[i] = [landmark.x, landmark.y, landmark.z]
mp_drawing.draw_landmarks(
frame, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)
cv2.imshow('MediaPipe Pose', frame)
np.savetxt('landmarks.txt', landmarks)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
阅读全文