1 安装blender的py包bpy

bpy全称Blender Python API,是blender使用python与系统执行数据交换和功能调用的接口模块。

先使用conda创建虚拟环境,blender的py包只支持python3.7

conda create -n fbx2bvh python=3.7
pip install bpy=2.82.1
bpy_post_install

按照顺序依次执行上述命令即可完成blender python包的安装。

另外还需要numpy,继续执行以下命令安装numpy

pip install numpy

2 将fbx转换为bvh

使用github的python脚本,脚本内容如下,

import bpy
import numpy as np
from os import listdir, path

def fbx2bvh(data_path, file):
    sourcepath = data_path+"/"+file
    bvh_path = data_path+"/"+file.split(".fbx")[0]+".bvh"

    bpy.ops.import_scene.fbx(filepath=sourcepath)

    frame_start = 9999
    frame_end = -9999
    action = bpy.data.actions[-1]
    if  action.frame_range[1] > frame_end:
      frame_end = action.frame_range[1]
    if action.frame_range[0] < frame_start:
      frame_start = action.frame_range[0]

    frame_end = np.max([60, frame_end])
    bpy.ops.export_anim.bvh(filepath=bvh_path,
                            frame_start=frame_start,
                            frame_end=frame_end, root_transform_only=True)
    bpy.data.actions.remove(bpy.data.actions[-1])
    print(data_path+"/"+file+" processed.")

if __name__ == '__main__':
    data_path = "./fbx/"
    directories = sorted([f for f in listdir(data_path) if not f.startswith(".")])
    for d in directories:
      files = sorted([f for f in listdir(data_path+d) if f.endswith(".fbx")])
      for file in files:
          fbx2bvh(path.join(data_path,d), file)

将需要转换的fbx文件放在与该脚本同级的fbx目录下,然后直接运行该脚本,转换之后的bvh文件保存在fbx文件夹下。

或者使用以下命令运行,

blender -b -P fbx2bvh.py

如果待转换的fbx文件没有动作信息而只有静态初始骨架,则需要将上述脚本修改为

import bpy
import numpy as np
from os import listdir, path

def fbx2bvh(data_path, file):
    sourcepath = data_path+"/"+file
    bvh_path = data_path+"/"+file.split(".fbx")[0]+".bvh"

    bpy.ops.import_scene.fbx(filepath=sourcepath)

    frame_start = 9999
    frame_end = -9999
    action = bpy.data.actions[-1]
    if  action.frame_range[1] > frame_end:
      frame_end = int(action.frame_range[1])
    if action.frame_range[0] < frame_start:
      frame_start = int(action.frame_range[0])

    frame_end = np.max([60, frame_end])
    bpy.ops.export_anim.bvh(filepath=bvh_path,
                            frame_start=frame_start,
                            frame_end=frame_end, root_transform_only=True)
    bpy.data.actions.remove(bpy.data.actions[-1])
    print(data_path+"/"+file+" processed.")

if __name__ == '__main__':
    data_path = "./fbx/"
    directories = sorted([f for f in listdir(data_path) if not f.startswith(".")])
    for d in directories:
      files = sorted([f for f in listdir(data_path+d) if f.endswith(".fbx")])
      for file in files:
          fbx2bvh(path.join(data_path,d), file)

不然会出现错误,因为在导出bvh的时候起始帧和终止帧应为整数,所以将frame_startframe_end转换为int强制转为int即可。

参考