Communitygithub.com

ComeOnOliver/skillshub

在 Blender 中使用 Python 导入、处理和重定向动作捕捉数据。可操作 BVH/FBX 动捕文件、从视频素材中追踪相机和物体运动、求解 3D 相机路径以及清理动画数据——全部可从终端脚本化执行。

skillshub 是什么?

该技能提供了一个完整的 Python 工作流,用于在 Blender 中处理动作捕捉数据,涵盖从导入、重定向、清理到导出动画数据的全流程。它支持 BVH 和 FBX 格式的动捕文件,并提供了从视频素材中追踪相机和物体运动、求解 3D 相机路径的功能。通过内置的骨骼映射和帧简化函数,用户可以高效地将动捕数据重定向到不同骨架,并在导出前清理冗余关键帧。该技能适用于 Blender 2.8+ 版本,支持通过 `blender --background` 命令行批量处理,适合游戏开发、影视 VFX 和动画制作等场景。其核心优势在于将复杂的动捕管线脚本化,便于集成到自动化工作流或 CI/CD 流程中。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/TerminalSkills/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}_retarget")
    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} 像素 ({'良好' 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.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相关技能