Captura de Movimiento en Blender
Resumen
Importa, procesa y retargetiza datos de captura de movimiento en Blender usando Python. Trabaja con archivos de mocap BVH/FBX, rastrea movimiento de cámara y objetos desde metraje de video, resuelve trayectorias de cámara 3D y limpia datos de animación, todo desde el terminal.
Instrucciones
1. Importar archivos de captura de movimiento 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"Importado: {armature.name}, Huesos: {len(armature.data.bones)}, Fotogramas: {action.frame_range}")
2. Importar FBX con animación
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. Retargetizar movimiento entre armaduras
from mathutils import Matrix
def retarget_motion(source_armature, target_armature, bone_mapping):
"""Retargetizar animación usando un mapeo de nombres de huesos: {hueso_destino: hueso_origen}"""
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)
# Copiar ubicación solo para el hueso raíz
if src_name == list(bone_mapping.values())[0]:
tgt.location = src.location
tgt.keyframe_insert(data_path="location", frame=frame)
# Ejemplo de mapeo 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. Limpiar datos de captura de movimiento
def decimate_fcurve(fcurve, factor=0.5):
"""Eliminar fotogramas clave para reducir datos manteniendo la forma."""
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. Seguimiento de movimiento por video y resolución de cámara
# Cargar metraje
clip = bpy.data.movieclips.load("/path/to/footage.mp4")
scene = bpy.context.scene
scene.active_clip = clip
# Configurar seguimiento
tracking = clip.tracking
settings = tracking.settings
settings.default_pattern_size = 21
settings.default_search_size = 71
settings.default_motion_model = 'AFFINE'
# Configuración de cámara para resolver
camera = tracking.camera
camera.sensor_width = 36.0
camera.focal_length = 50.0
# Resolver movimiento de cámara
bpy.ops.clip.solve_camera()
solve_error = tracking.reconstruction.average_error
print(f"Error de resolución: {solve_error:.4f} px ({'Bueno' if solve_error < 0.5 else 'Necesita refinamiento'})")
# Configurar escena a partir de datos resueltos
bpy.ops.clip.setup_tracking_scene()
6. Aplicar movimiento rastreado a objetos
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
# Hornear restricción a fotogramas clave
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 datos de animación
# Exportar como 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'
)
# Exportar como FBX con animación horneada
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
)
Ejemplos
Ejemplo 1: Escanear biblioteca de mocap por lotes
Solicitud del usuario: "Importar todos los archivos BVH de una carpeta, listar recuentos de huesos y rangos de fotogramas"
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)} huesos, {duration:.1f}s")
Ejecutar: blender --background --python scan_mocap.py
Ejemplo 2: Aplicar mocap a personaje y renderizar
Solicitud del usuario: "Importar un archivo BVH, aplicarlo a mi personaje riggeado y renderizar una vista previa"
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
# Transferir acción (funciona cuando los nombres de huesos coinciden)
if not char_armature.animation_data:
char_armature.animation_data_create()
char_armature.animation_data.action = mocap_action
# Eliminar armadura temporal, establecer rango de fotogramas, agregar cámara, renderizar
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)
Directrices
- BVH es el más simple (texto plano con jerarquía + movimiento). FBX admite datos más ricos (blend shapes, múltiples tomas).
- La escala importa: los archivos BVH a menudo usan centímetros. Establece
global_scale=0.01para archivos basados en cm. - La coincidencia de nombres de huesos es crítica para la retargetización. Construye un diccionario de mapeo para cada formato de origen.
- Para retargetizar, copia las rotaciones para todos los huesos, pero solo la ubicación para el hueso raíz/cadera.
- Limpia el mocap importado decimando fotogramas clave: el mocap crudo tiene fotogramas clave en cada fotograma, lo que dificulta la edición.
- La calidad de la resolución de la cámara depende de la cantidad y distribución de los marcadores. Usa 8+ marcadores bien distribuidos, mantén el error por debajo de 0.5px.
- Usa
bpy.ops.nla.bake()para convertir restricciones a fotogramas clave para exportar. - Siempre exporta con
bake_anim=Trueen FBX para aplanar tiras NLA y restricciones.