Communitygithub.com

Blender 动捕与跟踪工具

在Blender中通过Python实现运动捕捉与跟踪流程自动化。适用于用户需要导入BVH或FBX动捕数据、将运动重定向至骨架、从视频中跟踪相机或物体运动、求解相机运动、清理动捕数据,或在Blender中编写任何跟踪管线脚本的场景。

Blender 动捕与跟踪工具 是什么?

该技能提供了一套完整的Python脚本,用于在Blender中自动化运动捕捉和摄像机/物体跟踪工作流程。它支持导入BVH和FBX格式的动捕文件,并包含一个重定向函数,可以利用骨骼名称映射将动画从一个骨架转移到另一个骨架。用户还可以清理动捕数据,通过关键帧抽取来减少数据量。对于基于视频的跟踪,该技能提供了设置视频片段、配置跟踪参数、求解摄像机运动以及创建跟踪场景的脚本。跟踪结果可以应用于物体,并烘焙成关键帧,然后导出为BVH或FBX格式。该技能包含两个实际示例:批量扫描一个文件夹中的所有BVH文件,以及将动捕数据应用于角色并渲染预览。它支持所有平台(Windows、macOS、Linux),并通过Blender的Python API (`bpy`) 和命令行操作。文档包含了关于尺度(厘米与全局缩放)、骨骼名称匹配、重定向期间仅复制根骨骼的位置、使用关键帧抽取进行数据清理、需要至少8个标记以获得良好求解质量的摄像机跟踪最佳实践,以及导出时使用 `bake_anim=True` 以展平NLA条和约束的重要指南。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/TerminalSkills/skills/tree/HEAD/skills/blender-motion-capture

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Blender 运动捕捉

概述

使用Python在Blender中导入、处理和重定向运动捕捉数据。可处理BVH/FBX动捕文件,从视频素材中跟踪摄像机和物体运动,求解3D摄像机路径,以及清理动画数据——这一切均可通过终端编写脚本实现。

指令

1. 导入BVH运动捕捉文件

import bpy

bpy.ops.import_anim.bvh(
    filepath="/path/to/mocap.bvh",
    target='ARMATURE',
    global_scale=1.0,
    frame_start=1,
    use_fps_scale=False,
    rotate_mode='NATIVE',
    axis_forward='-Z', axis_up='Y'
)

armature = bpy.context.active_object
action = armature.animation_data.action
print(f"已导入: {armature.name}, 骨骼数: {len(armature.data.bones)}, 帧数: {action.frame_range}")

2. 导入带动画的FBX文件

bpy.ops.import_scene.fbx(
    filepath="/path/to/mocap.fbx",
    use_anim=True,
    ignore_leaf_bones=True,
    automatic_bone_orientation=True,
    primary_bone_axis='Y', secondary_bone_axis='X'
)

3. 在骨架之间重定向运动

from mathutils import Matrix

def retarget_motion(source_armature, target_armature, bone_mapping):
    """使用骨骼名称映射进行动画重定向: {目标骨骼: 源骨骼}"""
    source_action = source_armature.animation_data.action
    frame_start, frame_end = int(source_action.frame_range[0]), int(source_action.frame_range[1])

    if not target_armature.animation_data:
        target_armature.animation_data_create()
    new_action = bpy.data.actions.new(f"{source_action.name}_重定向")
    target_armature.animation_data.action = new_action

    for frame in range(frame_start, frame_end + 1):
        bpy.context.scene.frame_set(frame)
        for tgt_name, src_name in bone_mapping.items():
            src = source_armature.pose.bones.get(src_name)
            tgt = target_armature.pose.bones.get(tgt_name)
            if not src or not tgt:
                continue
            tgt.rotation_quaternion = src.rotation_quaternion
            tgt.keyframe_insert(data_path="rotation_quaternion", frame=frame)
            # 仅复制根骨骼的位置
            if src_name == list(bone_mapping.values())[0]:
                tgt.location = src.location
                tgt.keyframe_insert(data_path="location", frame=frame)

# Mixamo → Rigify 映射示例
mapping = {
    "spine": "mixamorig:Hips", "spine.001": "mixamorig:Spine",
    "spine.004": "mixamorig:Neck", "spine.006": "mixamorig:Head",
    "upper_arm.L": "mixamorig:LeftArm", "forearm.L": "mixamorig:LeftForeArm",
    "upper_arm.R": "mixamorig:RightArm", "forearm.R": "mixamorig:RightForeArm",
    "thigh.L": "mixamorig:LeftUpLeg", "shin.L": "mixamorig:LeftLeg",
    "thigh.R": "mixamorig:RightUpLeg", "shin.R": "mixamorig:RightLeg",
}

4. 清理运动捕捉数据

def decimate_fcurve(fcurve, factor=0.5):
    """移除关键帧以减少数据量,同时保持形状。"""
    points = fcurve.keyframe_points
    total = len(points)
    keep_every = max(1, int(1.0 / factor))
    remove_indices = [i for i in range(total) if i % keep_every != 0 and i != 0 and i != total - 1]
    for i in reversed(remove_indices):
        points.remove(points[i])

armature = bpy.context.active_object
action = armature.animation_data.action
for fcurve in action.fcurves:
    decimate_fcurve(fcurve, factor=0.5)
    fcurve.update()

5. 视频运动跟踪与摄像机求解

# 加载素材
clip = bpy.data.movieclips.load("/path/to/footage.mp4")
scene = bpy.context.scene
scene.active_clip = clip

# 配置跟踪
tracking = clip.tracking
settings = tracking.settings
settings.default_pattern_size = 21
settings.default_search_size = 71
settings.default_motion_model = 'AFFINE'

# 摄像机求解设置
camera = tracking.camera
camera.sensor_width = 36.0
camera.focal_length = 50.0

# 求解摄像机运动
bpy.ops.clip.solve_camera()
solve_error = tracking.reconstruction.average_error
print(f"求解误差: {solve_error:.4f} px ({'良好' if solve_error < 0.5 else '需要优化'})")

# 根据求解数据设置场景
bpy.ops.clip.setup_tracking_scene()

6. 将跟踪运动应用于物体

obj = bpy.data.objects["MyObject"]
constraint = obj.constraints.new(type='FOLLOW_TRACK')
constraint.clip = clip
constraint.track = tracking.tracks["Marker_01"]
constraint.use_3d_position = True
constraint.camera = scene.camera

# 将约束烘焙为关键帧
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
bpy.ops.nla.bake(
    frame_start=1, frame_end=clip.frame_duration,
    only_selected=True, visual_keying=True,
    clear_constraints=True, bake_types={'OBJECT'}
)

7. 导出动画数据

# 导出为BVH
bpy.ops.export_anim.bvh(
    filepath="/tmp/output_mocap.bvh",
    frame_start=int(action.frame_range[0]),
    frame_end=int(action.frame_range[1]),
    rotate_mode='NATIVE'
)

# 导出为带烘焙动画的FBX
bpy.ops.export_scene.fbx(
    filepath="/tmp/output_anim.fbx",
    use_selection=True, bake_anim=True,
    bake_anim_use_all_bones=True, add_leaf_bones=False
)

示例

示例1: 批量扫描动捕库

用户请求: “导入文件夹中的所有BVH文件,列出骨骼数量和帧范围”

import bpy, glob, os

for filepath in sorted(glob.glob("/path/to/mocap_library/*.bvh")):
    bpy.ops.object.select_all(action='SELECT')
    bpy.ops.object.delete()
    bpy.ops.import_anim.bvh(filepath=filepath, target='ARMATURE', global_scale=0.01, frame_start=1)
    arm = bpy.context.active_object
    if arm and arm.animation_data:
        action = arm.animation_data.action
        duration = (action.frame_range[1] - action.frame_range[0]) / bpy.context.scene.render.fps
        print(f"{os.path.basename(filepath)}: {len(arm.data.bones)} 个骨骼, {duration:.1f} 秒")

运行: blender --background --python scan_mocap.py

示例2: 将动捕应用于角色并渲染

用户请求: “导入一个BVH文件,将其应用到我的角色骨骼上,并渲染预览”

import bpy

bpy.ops.wm.open_mainfile(filepath="/path/to/character.blend")
char_armature = bpy.data.objects["Armature"]

bpy.ops.import_anim.bvh(filepath="/path/to/walk_cycle.bvh", target='ARMATURE', global_scale=0.01)
mocap_armature = bpy.context.active_object
mocap_action = mocap_armature.animation_data.action

# 传输动作(骨骼名称匹配时有效)
if not char_armature.animation_data:
    char_armature.animation_data_create()
char_armature.animation_data.action = mocap_action

# 移除临时骨架,设置帧范围,添加摄像机,渲染
bpy.data.objects.remove(mocap_armature)
scene = bpy.context.scene
scene.frame_start, scene.frame_end = int(mocap_action.frame_range[0]), int(mocap_action.frame_range[1])
scene.render.filepath = "/tmp/mocap_preview/frame_"
bpy.ops.render.render(animation=True)

指南

  • BVH最简单(纯文本,包含层级结构和运动)。FBX支持更丰富的数据(混合形状、多个镜头)。
  • 尺度很重要:BVH文件通常使用厘米单位。对于基于厘米的文件,设置 global_scale=0.01。
  • 骨骼名称匹配对于重定向至关重要。为每种源格式构建一个映射字典。
  • 重定向时,复制所有骨骼的旋转,但仅复制根/髋骨骼的位置。
  • 通过关键帧抽取清理导入的动捕数据——原始动捕数据每帧都有关键帧,使得编辑变得困难。
  • 摄像机求解质量取决于标记数量和分布。使用8个以上分布良好的标记,保持误差低于0.5像素。
  • 使用 bpy.ops.nla.bake() 将约束转换为关键帧以便导出。
  • 导出FBX时始终使用 bake_anim=True,以展平NLA条和约束。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

TerminalSkills/skills

>- Run GitHub Actions locally with act. Use when a user asks to test GitHub Actions workflows locally, debug CI pipelines without pushing, or run workflows offline.

TerminalSkills/skills

>- You are an expert in AG2 (formerly AutoGen), the open-source multi-agent conversation framework. You help developers build systems where multiple AI agents collaborate through structured conversations — with tool use, human-in-the-loop, code execution, group chat orchestration, and nested conversations — for complex tasks like software development, research, and data analysis.

TerminalSkills/skills

>- Generate short-form videos with AI — script writing, text-to-speech narration, stock footage selection, subtitle generation, and video assembly. Use when: creating TikTok/YouTube Shorts/Reels content, automating video production, building content pipelines.

TerminalSkills/skills

>- Animate 3D objects and characters in Blender with Python. Use when the user wants to keyframe properties, create armatures and rigs, set up IK/FK chains, animate shape keys for facial animation, edit F-Curves, use the NLA editor to blend actions, add drivers for expression-based animation, or script any animation workflow in Blender.

TerminalSkills/skills

>- You are an expert in Bolt.new by StackBlitz, the AI-powered full-stack development environment that runs entirely in the browser. You help developers go from idea to deployed app in minutes using natural language prompts — Bolt generates complete applications with frontend, backend, database, and deployment, all running in a WebContainer without local setup.

TerminalSkills/skills

>- Assists with using Bun as an all-in-one JavaScript/TypeScript runtime, package manager, bundler, and test runner. Use when building HTTP servers, managing packages, running tests, or migrating from Node.js. Trigger words: bun, bun serve, bun install, bun test, bun build, javascript runtime, bun runtime.

TerminalSkills/skills

>- Self-host customer support with Chatwoot. Use when a user asks to set up open-source customer support, add live chat without SaaS costs, build a multi-channel inbox, or deploy a free Intercom alternative.

TerminalSkills/skills

>- You are an expert in Chi, the lightweight, idiomatic Go HTTP router built on `net/http`. You help developers build composable HTTP services using Chi's middleware stack, route groups, URL parameters, sub-routers, and context-based request scoping — providing Express-like ergonomics while staying 100% compatible with Go's standard library.

TerminalSkills/skills

When the user wants to edit, review, or improve existing marketing copy. Also use when the user mentions 'edit this copy,' 'review my copy,' 'copy feedback,' 'proofread,' 'polish this,' 'make this better,' or 'copy sweep.' This skill provides a systematic approach to editing marketing copy through multiple focused passes.

TerminalSkills/skills

>- Add live chat and customer support with Crisp. Use when a user asks to add a chat widget, implement live customer support, set up a help desk, create a knowledge base, or add a chatbot to a website.

TerminalSkills/skills

>- Assists with building custom interactive data visualizations using D3.js. Use when creating charts, graphs, maps, force layouts, or hierarchical diagrams that require fine-grained control beyond what charting libraries provide. Trigger words: d3, data visualization, chart, svg, scales, force graph, treemap, choropleth.

TerminalSkills/skills

dbt (data build tool) transforms data in your warehouse using SQL SELECT statements. Learn project setup, models, tests, documentation, incremental materializations, and integration with data warehouses like PostgreSQL, BigQuery, and Snowflake.

TerminalSkills/skills

>- You are an expert in dlt, the open-source Python library for building data pipelines. You help developers load data from any API, file, or database into warehouses and lakes using simple Python decorators — with automatic schema inference, incremental loading, and built-in data contracts. dlt is the "requests library for data pipelines.

TerminalSkills/skills

Data Version Control for ML projects. Track large datasets and models alongside Git, build reproducible ML pipelines, and run experiments with metric comparison. Works with any storage backend including S3, GCS, Azure, and local filesystems.

TerminalSkills/skills

>- You are an expert in E2B, the cloud platform for running AI-generated code in secure sandboxes. You help developers give AI agents the ability to execute code, install packages, read/write files, and run long processes in isolated cloud environments — each sandbox is a lightweight VM that boots in ~150ms with full Linux, filesystem, and networking.

TerminalSkills/skills

>- Transcode, convert, edit, and process audio and video with FFmpeg. Use when a user asks to convert video formats (webm to mp4, mkv to mp4), extract audio from video, compress video files, trim or cut clips, concatenate videos, add subtitles, create thumbnails, apply filters, change resolution or bitrate, re-encode media, create GIFs from video, add watermarks, normalize audio, stream media, or build automated media processing pipelines.

TerminalSkills/skills

>- Create advanced animations with GSAP. Use when building complex timelines, scroll-driven animations, SVG morphing, text animations, or high-performance web animations beyond CSS capabilities.

TerminalSkills/skills

>- Generate deterministic MP4 videos from HTML, CSS, media, and seekable animations using HeyGen's HyperFrames framework. Use when someone asks to "render HTML to video", "make a video with HyperFrames", "create a programmatic video", "turn an animation into MP4", "build a launch/product video from HTML", "render GSAP/Lottie/Three.js to video", or set up an agent-driven video pipeline. Covers init/preview/render/add/lint/inspect commands, data-* timing attributes, animation adapters, and the component catalog.

TerminalSkills/skills

When the user wants to perform load testing, stress testing, or performance testing of APIs and websites using k6. Also use when the user mentions "k6," "load test," "performance test," "stress test," "spike test," "soak test," "thresholds," "virtual users," or "VUs." For browser-based testing, see selenium.

TerminalSkills/skills

>- Lovable (formerly GPT Engineer) is a browser-based AI app builder that turns a natural-language description into a working full-stack web app with a built-in backend, authentication, database and one-click publishing. Use when the user wants to prototype or ship a web app with Lovable, write effective Lovable prompts, connect Supabase or GitHub, review generated security rules, or move a Lovable project into their own editor.

相关技能