目录
pygame
pygame保存mp4
mayavi
pygame
import pygame
from pygame.locals import *
import numpy as np
import sys
# 初始化Pygame
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
# 生成示例数据
n_frames = 20
n_joints = 17
keypoints_3d = np.random.rand(n_frames, n_joints, 3) * 2 - 1
# 投影3D到2D(简化版)
def project_3d_to_2d(x, y, z, scale=200):
return int(width / 2 + x * scale), int(height / 2 - y * scale)
frame = 0
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
screen.fill((255, 255, 255))
# 获取当前帧
current_frame = keypoints_3d[frame % n_frames]
# 绘制关键点
for x, y, z in current_frame:
px, py = project_3d_to_2d(x, y, z)
pygame.draw.circle(screen, (255, 0, 0), (px, py), 5)
# 绘制骨骼连线
for i in range(n_joints - 1):
x1, y1, z1 = current_frame[i]
x2, y2, z2 = current_frame[i + 1]
p1 = project_3d_to_2d(x1, y1, z1)
p2 = project_3d_to_2d(x2, y2, z2)
pygame.draw.line(screen, (0, 0, 255), p1, p2, 2)
pygame.display.flip()
frame += 1
n=1
clock.tick(n) # n帧/秒
pygame.quit()
sys.exit()
pygame保存mp4
import pygame
import imageio
import numpy as np
# 初始化 Pygame
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
# 视频帧列表
frames = []
running = True
frame_count = 0
max_frames = 300 # 保存300帧,大概10秒@30fps
while running and frame_count < max_frames:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 清屏和绘制内容
screen.fill((0, 0, 0))
pygame.draw.circle(screen, (255, 0, 0), (frame_count % width, height // 2), 30)
pygame.display.flip()
# 截图保存为 numpy 数组
buffer = pygame.surfarray.array3d(screen)
frame = np.transpose(buffer, (1, 0, 2)) # 转换为 HWC 格式
frames.append(frame)
frame_count += 1
clock.tick(30) # 控制帧率为30FPS
pygame.quit()
# 保存为MP4
imageio.mimsave("output.mp4", frames, fps=30)
print("视频保存为 output.mp4")
mayavi
import numpy as np
from mayavi import mlab
# 生成示例数据
n_frames = 20
n_joints = 17
keypoints_3d = np.random.rand(n_frames, n_joints, 3)
# 创建动画
@mlab.animate(delay=100) # 每帧100ms
def animate():
for i in range(n_frames):
mlab.clf() # 清空当前帧
current_frame = keypoints_3d[i]
# 绘制关键点
pts = mlab.points3d(
current_frame[:, 0], current_frame[:, 1], current_frame[:, 2],
color=(1, 0, 0), scale_factor=0.05
)
# 绘制骨骼连线
for j in range(n_joints - 1):
mlab.plot3d(
[current_frame[j, 0], current_frame[j+1, 0]],
[current_frame[j, 1], current_frame[j+1, 1]],
[current_frame[j, 2], current_frame[j+1, 2]],
tube_radius=0.01, color=(0, 0, 1)
)
yield # 切换到下一帧
animate()
mlab.show()