Communitygithub.com

Captura de Movimento no Blender

Importe, processe e retarget dados de captura de movimento no Blender usando Python. Trabalhe com arquivos mocap BVH/FBX, rastreie movimento de câmera e objetos a partir de vídeos, resolva trajetórias 3D de câmera e limpe dados de animação — tudo com script via terminal.

O que é Captura de Movimento no Blender?

Esta skill capacita o usuário a manipular dados de captura de movimento (mocap) no Blender, utilizando scripts Python que podem ser executados diretamente do terminal. Ela oferece funcionalidades para importar arquivos nos formatos BVH e FBX, retarget (redirecionar) animações entre diferentes armaduras (armatures) através de mapeamento de nomes de ossos, limpar dados brutos com decimação de keyframes, realizar rastreamento de movimento de vídeo e resolver câmeras 3D, além de exportar animações limpas. A skill é ideal para desenvolvedores e artistas técnicos que precisam automatizar pipelines de animação, integrando-se perfeitamente ao ecossistema Blender/Python. Suporta todos os principais sistemas operacionais e é compatível com qualquer versão recente do Blender.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/TerminalSkills/skills/blender-motion-capture

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

O que Captura de Movimento no Blender faz?

Visão Geral

Importe, processe e retarget dados de captura de movimento no Blender usando Python. Trabalhe com arquivos mocap BVH/FBX, rastreie movimento de câmera e objetos a partir de vídeos, resolva trajetórias 3D de câmera e limpe dados de animação — tudo com script via terminal.

Instruções

1. Importar arquivos BVH de captura de movimento

import bpy

bpy.ops.import_anim.bvh(
    filepath="/caminho/para/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"Importado: {armature.name}, Ossos: {len(armature.data.bones)}, Quadros: {action.frame_range}")

2. Importar FBX com animação

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

3. Retarget de movimento entre armaduras

from mathutils import Matrix

def retarget_motion(armadura_origem, armadura_destino, mapeamento_ossos):
    """Retarget de animação usando um mapeamento de nomes de ossos: {osso_destino: osso_origem}"""
    acao_origem = armadura_origem.animation_data.action
    quadro_inicio, quadro_fim = int(acao_origem.frame_range[0]), int(acao_origem.frame_range[1])

    if not armadura_destino.animation_data:
        armadura_destino.animation_data_create()
    nova_acao = bpy.data.actions.new(f"{acao_origem.name}_retarget")
    armadura_destino.animation_data.action = nova_acao

    for quadro in range(quadro_inicio, quadro_fim + 1):
        bpy.context.scene.frame_set(quadro)
        for nome_dest, nome_orig in mapeamento_ossos.items():
            org = armadura_origem.pose.bones.get(nome_orig)
            dst = armadura_destino.pose.bones.get(nome_dest)
            if not org or not dst:
                continue
            dst.rotation_quaternion = org.rotation_quaternion
            dst.keyframe_insert(data_path="rotation_quaternion", frame=quadro)
            # Copiar localização apenas para o osso raiz
            if nome_orig == list(mapeamento_ossos.values())[0]:
                dst.location = org.location
                dst.keyframe_insert(data_path="location", frame=quadro)

# Exemplo de mapeamento Mixamo → Rigify
mapeamento = {
    "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. Limpar dados de captura de movimento

def decimate_fcurve(curva, fator=0.5):
    """Remove keyframes para reduzir dados mantendo a forma."""
    pontos = curva.keyframe_points
    total = len(pontos)
    manter_a_cada = max(1, int(1.0 / fator))
    indices_remover = [i for i in range(total) if i % manter_a_cada != 0 and i != 0 and i != total - 1]
    for i in reversed(indices_remover):
        pontos.remove(pontos[i])

armadura = bpy.context.active_object
action = armadura.animation_data.action
for curva in action.fcurves:
    decimate_fcurve(curva, fator=0.5)
    curva.update()

5. Rastreamento de movimento de vídeo e solução de câmera

# Carregar vídeo
clip = bpy.data.movieclips.load("/caminho/para/video.mp4")
cena = bpy.context.scene
cena.active_clip = clip

# Configurar rastreamento
rastreamento = clip.tracking
config = rastreamento.settings
config.default_pattern_size = 21
config.default_search_size = 71
config.default_motion_model = 'AFFINE'

# Configurações de câmera para solução
camera = rastreamento.camera
camera.sensor_width = 36.0
camera.focal_length = 50.0

# Resolver movimento da câmera
bpy.ops.clip.solve_camera()
erro_solucao = rastreamento.reconstruction.average_error
print(f"Erro da solução: {erro_solucao:.4f} px ({'Bom' if erro_solucao < 0.5 else 'Precisa de refinamento'})")

# Configurar cena a partir dos dados resolvidos
bpy.ops.clip.setup_tracking_scene()

6. Aplicar movimento rastreado a objetos

obj = bpy.data.objects["MeuObjeto"]
restricao = obj.constraints.new(type='FOLLOW_TRACK')
restricao.clip = clip
restricao.track = rastreamento.tracks["Marcador_01"]
restricao.use_3d_position = True
restricao.camera = cena.camera

# Assar restrição em keyframes
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. Exportar dados de animação

# Exportar como BVH
bpy.ops.export_anim.bvh(
    filepath="/tmp/saida_mocap.bvh",
    frame_start=int(action.frame_range[0]),
    frame_end=int(action.frame_range[1]),
    rotate_mode='NATIVE'
)

# Exportar como FBX com animação assada
bpy.ops.export_scene.fbx(
    filepath="/tmp/saida_anim.fbx",
    use_selection=True, bake_anim=True,
    bake_anim_use_all_bones=True, add_leaf_bones=False
)

Exemplos

Exemplo 1: Escanear biblioteca mocap em lote

Solicitação do usuário: "Importar todos os arquivos BVH de uma pasta, listar contagens de ossos e intervalos de quadros"

import bpy, glob, os

para cada caminho_arquivo in sorted(glob.glob("/caminho/para/biblioteca_mocap/*.bvh")):
    bpy.ops.object.select_all(action='SELECT')
    bpy.ops.object.delete()
    bpy.ops.import_anim.bvh(filepath=caminho_arquivo, 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
        duracao = (action.frame_range[1] - action.frame_range[0]) / bpy.context.scene.render.fps
        print(f"{os.path.basename(caminho_arquivo)}: {len(arm.data.bones)} ossos, {duracao:.1f}s")

Execute: blender --background --python scan_mocap.py

Exemplo 2: Aplicar mocap a personagem e renderizar

Solicitação do usuário: "Importar um arquivo BVH, aplicar ao meu personagem rigado e renderizar uma prévia"

import bpy

bpy.ops.wm.open_mainfile(filepath="/caminho/para/personagem.blend")
armadura_personagem = bpy.data.objects["Armature"]

bpy.ops.import_anim.bvh(filepath="/caminho/para/ciclo_andar.bvh", target='ARMATURE', global_scale=0.01)
armadura_mocap = bpy.context.active_object
acao_mocap = armadura_mocap.animation_data.action

# Transferir ação (funciona quando nomes de ossos coincidem)
if not armadura_personagem.animation_data:
    armadura_personagem.animation_data_create()
armadura_personagem.animation_data.action = acao_mocap

# Remover armadura temporária, definir intervalo de quadros, adicionar câmera, renderizar
bpy.data.objects.remove(armadura_mocap)
cena = bpy.context.scene
cena.frame_start, cena.frame_end = int(acao_mocap.frame_range[0]), int(acao_mocap.frame_range[1])
cena.render.filepath = "/tmp/previa_mocap/quadro_"
bpy.ops.render.render(animation=True)

Diretrizes

  • BVH é o mais simples (texto puro com hierarquia + movimento). FBX suporta dados mais ricos (blend shapes, múltiplas takes).
  • Escala importa: arquivos BVH geralmente usam centímetros. Defina global_scale=0.01 para arquivos baseados em cm.
  • A correspondência de nomes de ossos é essencial para retargeting. Construa um dicionário de mapeamento para cada formato de origem.
  • Para retargeting, copie rotações para todos os ossos, mas apenas a localização para o osso raiz/quadril.
  • Limpe dados mocap importados decimando keyframes — o mocap bruto tem keyframes em todos os quadros, dificultando a edição.
  • A qualidade da solução de câmera depende do número e distribuição dos marcadores. Use 8+ marcadores bem distribuídos e mantenha o erro abaixo de 0,5px.
  • Use bpy.ops.nla.bake() para converter restrições em keyframes para exportação.
  • Sempre exporte com bake_anim=True no FBX para achatar tiras NLA e restrições.

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

Habilidades Relacionadas