【代码】3d->video

mesh->video

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
from pywavefront import Wavefront
import os

name='dog'
# 读取OBJ文件并将其转换为numpy数组
obj_folder =f'path/{name}/'
obj_files = os.listdir(obj_folder)

# 使用列表推导式筛选出以 'e300.obj' 结尾的文件
e300_obj_files = [file for file in obj_files if file.endswith('e300.obj')]

# 定义一个函数用来从文件名中提取frame后的数字
def extract_frame_number(filename):
    # 从文件名中找到"frame_"和第一个"_"之后的位置
    start = filename.find('frame_') + 6
    end = filename.find('_', start)
    # 提取并返回数字部分
    return int(filename[start:end])

# 使用自定义函数对文件列表进行排序
sorted_e300_obj_files = sorted(e300_obj_files, key=extract_frame_number)

meshes = []
for obj_file in sorted_e300_obj_files:
    obj = Wavefront(obj_folder + obj_file, collect_faces=True)
    vertices = np.array(obj.vertices)
    faces = np.array(obj.mesh_list[0].faces)
    meshes.append((vertices, faces))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# 初始化绘图函数
def init():
    ax.clear()
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')

# 动画更新函数
def update(frame):
    ax.clear()
    vertices, faces = meshes[frame]
    x, y, z = vertices[:, 0], vertices[:, 1], vertices[:, 2]
    ax.plot_trisurf(x, y, z, triangles=faces, shade=True, color='gray')
    ax.set_title(f'{name} Frame {frame}')
    ax.set_xlim(x.min(), x.max())
    ax.set_ylim(y.min(), y.max())
    ax.set_zlim(z.min(), z.max())
    # ax.view_init(elev=20, azim=45)  # 设置视角

# 创建动画
ani = FuncAnimation(fig, update, frames=len(meshes), init_func=init, blit=False)

# 使用FFmpeg写入视频文件
writervideo = animation.FFMpegWriter(fps=10) 
ani.save(f'n_{name}.mp4', writer=writervideo)

joints->video

import os
from os.path import join as pjoin
from tqdm import tqdm
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation, PillowWriter
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import mpl_toolkits.mplot3d.axes3d as p3
def plot_3d_motion(save_path, kinematic_tree, joints, title, figsize=(10, 10), fps=120, radius=4):
    title_sp = title.split(' ')
    if len(title_sp) > 10:
        title = '\n'.join([' '.join(title_sp[:10]), ' '.join(title_sp[10:])])

    def init():
        ax.set_xlim3d([-radius / 2, radius / 2])
        ax.set_ylim3d([0, radius])
        ax.set_zlim3d([0, radius])
        fig.suptitle(title, fontsize=20)
        ax.grid(False)

    def plot_xzPlane(minx, maxx, miny, minz, maxz):
        verts = [
            [minx, miny, minz],
            [minx, miny, maxz],
            [maxx, miny, maxz],
            [maxx, miny, minz]
        ]
        xz_plane = Poly3DCollection([verts])
        xz_plane.set_facecolor((0.5, 0.5, 0.5, 0.5))
        ax.add_collection3d(xz_plane)

    data = joints.copy().reshape(len(joints), -1, 3)
    fig = plt.figure(figsize=figsize)
    ax = fig.add_subplot(111, projection='3d')
    init()
    MINS = data.min(axis=0).min(axis=0)
    MAXS = data.max(axis=0).max(axis=0)
    colors = ['red', 'blue', 'black', 'red', 'blue',  
              'darkblue', 'darkblue', 'darkblue', 'darkblue', 'darkblue',
              'darkred', 'darkred', 'darkred', 'darkred', 'darkred']
    frame_number = data.shape[0]

    height_offset = MINS[1]
    data[:, :, 1] -= height_offset
    trajec = data[:, 0, [0, 2]]
    
    data[..., 0] -= data[:, 0:1, 0]
    data[..., 2] -= data[:, 0:1, 2]

    def update(index):
        ax.cla()  # 清除当前轴
        init()  # 重新初始化轴
        
        ax.view_init(elev=120, azim=-90)
        ax.dist = 7.5
        plot_xzPlane(MINS[0]-trajec[index, 0], MAXS[0]-trajec[index, 0], 0, MINS[2]-trajec[index, 1], MAXS[2]-trajec[index, 1])
        
        if index > 1:
            ax.plot3D(trajec[:index, 0]-trajec[index, 0], np.zeros_like(trajec[:index, 0]), trajec[:index, 1]-trajec[index, 1], linewidth=1.0, color='blue')
        
        for i, (chain, color) in enumerate(zip(kinematic_tree, colors)):
            linewidth = 4.0 if i < 5 else 2.0
            ax.plot3D(data[index, chain, 0], data[index, chain, 1], data[index, chain, 2], linewidth=linewidth, color=color)

        plt.axis('off')
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.set_zticklabels([])

    ani = FuncAnimation(fig, update, frames=frame_number, interval=1000/fps, repeat=False)

    ani.save(save_path, fps=fps)
    plt.close()
    

相关推荐

  1. 代码3d->video

    2024-06-15 06:38:03       9 阅读
  2. OSDI 2023: 3D Video Loops From Asynchronous Input

    2024-06-15 06:38:03       31 阅读
  3. 3d姿态 mhformer 预测代码

    2024-06-15 06:38:03       23 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-15 06:38:03       17 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-15 06:38:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-15 06:38:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-15 06:38:03       18 阅读

热门阅读

  1. 前端常用排序算法

    2024-06-15 06:38:03       6 阅读
  2. 鸿蒙Arkts上传图片并获取接口返回信息

    2024-06-15 06:38:03       9 阅读
  3. .NETCORE 微软企业登录

    2024-06-15 06:38:03       7 阅读
  4. bash和sh区别

    2024-06-15 06:38:03       6 阅读
  5. 从零手写实现 nginx-23-directive IF 条件判断指令

    2024-06-15 06:38:03       7 阅读
  6. svm 超参数

    2024-06-15 06:38:03       6 阅读
  7. shell判断语句练习

    2024-06-15 06:38:03       6 阅读
  8. MySQL周内训参照2、DDL与DML语句

    2024-06-15 06:38:03       9 阅读
  9. Scala学习笔记12: 高阶函数

    2024-06-15 06:38:03       6 阅读
  10. 详解 Flink CDC 的介绍和入门案例

    2024-06-15 06:38:03       4 阅读
  11. Nginx之Stream(TCP/UDP)负载均衡

    2024-06-15 06:38:03       7 阅读
  12. Sklearn简介、安装教程、入门学习

    2024-06-15 06:38:03       8 阅读