用blender python api 寫一段獲取所有幀中骨架中所有骨骼的位置,旋轉,縮放的屬性的值,列印並寫入到csv檔案中

大话人生發表於2024-04-19

1.選中骨骼,進入姿態模式

2.全選所有骨骼

3.執行程式碼

程式碼:

import bpy
import csv
import os

# 獲取當前活動的骨架物件
armature = bpy.context.view_layer.objects.active

# 檢查選擇的物件是否是骨架
if armature.type != 'ARMATURE' or not armature.pose.bones:
    print("The active object is not an armature or does not have pose bones.")
else:
    # 獲取骨架的所有姿勢骨骼
    pose_bones = armature.pose.bones

    # 獲取動畫的幀範圍
    frame_start = bpy.context.scene.frame_start
    frame_end = bpy.context.scene.frame_end

    # 定義CSV檔案的名稱和路徑
    csv_filename = "bones_data.csv"
    csv_path = os.path.join(os.path.dirname(bpy.data.filepath), csv_filename)  # 使用專案路徑

    # 開啟CSV檔案進行寫入
    with open(csv_path, 'w', newline='') as csvfile:
        csvwriter = csv.writer(csvfile)
        # 寫入標題行
        csvwriter.writerow(['Frame', 'Bone Name', 'Bone Position X', 'Bone Position Y', 'Bone Position Z', 'Rotation W', 'Rotation X', 'Rotation Y', 'Rotation Z', 'Scale X', 'Scale Y', 'Scale Z'])

        # 遍歷所有幀
        for frame in range(frame_start, frame_end + 1):
            # 設定當前幀
            bpy.context.scene.frame_set(frame)

            # 遍歷骨架中的所有姿勢骨骼
            for bone in pose_bones:
                # 計算骨骼的近似位置(head和tail的中點)
                bone_position = (bone.head + bone.tail) / 2.0
                
                # 獲取骨骼的四元數
                rotation_quat = bone.rotation_quaternion
                
                # 獲取骨骼的縮放
                scale = bone.scale
                
                # 將骨骼資訊寫入CSV檔案
                csvwriter.writerow([
                    frame,
                    bone.name,
                    bone_position.x, bone_position.y, bone_position.z,
                    rotation_quat.w, rotation_quat.x, rotation_quat.y, rotation_quat.z,
                    scale.x, scale.y, scale.z
                ])

    print(f"Data has been written to {csv_path}")

相關文章