示例#1
0
文件: pose.py 项目: ericustc/RFC
def load_bvh_file(fname, skeleton):
    with open(fname) as f:
        mocap = Bvh(f.read())

    # build bone_addr
    bone_addr = dict()
    start_ind = 0
    for bone in skeleton.bones:
        end_ind = start_ind + len(bone.channels)
        bone_addr[bone.name] = (start_ind, end_ind)
        start_ind = end_ind
    dof_num = start_ind

    poses = np.zeros((mocap.nframes, dof_num))
    for i in range(mocap.nframes):
        for bone in skeleton.bones:
            trans = np.array(
                mocap.frame_joint_channels(i, bone.name, bone.channels))
            if bone == skeleton.root:
                trans[:3] *= skeleton.len_scale
                trans[3:6] = np.deg2rad(trans[3:6])
            else:
                trans = np.deg2rad(trans)
            start_ind, end_ind = bone_addr[bone.name]
            poses[i, start_ind:end_ind] = trans

    return poses, bone_addr
示例#2
0
 def test_channels(self):
     with open('tests/test_mocapbank.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual(mocap.joint_channels('LeftElbow'), ['Zrotation', 'Xrotation', 'Yrotation'])
     self.assertEqual(mocap.joint_channels('Hips'),
                      ['Xposition', 'Yposition', 'Zposition', 'Zrotation', 'Xrotation', 'Yrotation']
                      )
示例#3
0
 def test_frame_channel(self):
     with open('tests/test_mocapbank.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual(mocap.frame_joint_channel(22, 'Hips', 'Xrotation'), -20.98)
     self.assertEqual(mocap.frame_joint_channel(22, 'Chest', 'Xrotation'), 17.65)
     self.assertEqual(mocap.frame_joint_channel(22, 'Neck', 'Xrotation'), -6.77)
     self.assertEqual(mocap.frame_joint_channel(22, 'Head', 'Yrotation'), 8.47)
示例#4
0
 def test_frame_iteration(self):
     with open('tests/test_mocapbank.bvh') as f:
         mocap = Bvh(f.read())
     x_accumulator = 0.0
     for i in range(0, mocap.nframes):
         x_accumulator += mocap.frame_joint_channel(i, 'Hips', 'Xposition')
     self.assertTrue(abs(-19735.902699999995 - x_accumulator) < 0.0001)
示例#5
0
	def Load( self, pathname, filename ):
		self.PathName = pathname
		self.FileName = filename
		tempFile = pathname + filename
		print(tempFile)
		
		with open( tempFile ) as f:
			self.mocapdata = Bvh( f.read() )
		self.Skeleton = self.GetSkeleton()
		
		return tempFile
示例#6
0
def validate_bvh_file(bvh_file):
    MAX_NUMBER_FRAMES = int(os.environ["MAX_NUMBER_FRAMES"])
    FRAME_TIME = 1.0 / float(os.environ["RENDER_FPS"])

    file_content = bvh_file.decode("utf-8")
    mocap = Bvh(file_content)
    counter = None
    for line in file_content.split("\n"):
        if counter is not None and line.strip():
            counter += 1
        if line.strip() == "MOTION":
            counter = -2

    if mocap.nframes != counter:
        raise TaskFailure(
            f"The number of rows with motion data ({counter}) does not match the Frames field ({mocap.nframes})"
        )

    if MAX_NUMBER_FRAMES != -1 and mocap.nframes > MAX_NUMBER_FRAMES:
        raise TaskFailure(
            f"The supplied number of frames ({mocap.nframes}) is bigger than {MAX_NUMBER_FRAMES}"
        )

    if mocap.frame_time != FRAME_TIME:
        raise TaskFailure(
            f"The supplied frame time ({mocap.frame_time}) differs from the required {FRAME_TIME}"
        )
示例#7
0
 def test_tree2(self):
     with open('tests/test_mocapbank.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual([str(item) for item in mocap.root], [
         'HIERARCHY', 'ROOT Hips', 'MOTION', 'Frames: 455',
         'Frame Time: 0.033333'
     ])
示例#8
0
 def test_tree(self):
     with open('tests/test_freebvh.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual([str(item) for item in mocap.root], [
         'HIERARCHY', 'ROOT mixamorig:Hips', 'MOTION', 'Frames: 69',
         'Frame Time: 0.0333333'
     ])
示例#9
0
    def __init__(self, mocap_file: str, constraints_file: str):
        with open(mocap_file) as f:
            self.mocap = Bvh(f.read())
        with open(constraints_file) as f:
            content = f.readlines()

        content = [x.strip() for x in content]
        content = [x.split() for x in content]

        channel_mapping = ['Xrotation', 'Yrotation', 'Zrotation']
        self.mapping = {}
        for joint in content:
            self.mapping[joint[0]] = []
            for i in range(1, 4):
                if (joint[i] != '0'):
                    self.mapping[joint[0]].append(
                        (channel_mapping[i - 1], joint[i].lower()))
示例#10
0
 def parse(self):
     with open(self.bvh_path) as f:
         mocap = Bvh(f.read())
     self.frames_num = mocap.nframes
     joints = get_order_joints(mocap)
     self.joints_num = len(joints)
     self.joints_lst = []
     for frame_idx in range(self.frames_num):
         motions, root_pos = get_motions(mocap, frame_idx)
         compute_pos(joints, motions, root_pos)
         self.joints_lst.append(copy.deepcopy(joints))
示例#11
0
    def __init__(self, bvh_filename):
        with open(bvh_filename) as f:
            mocap = Bvh(f.read())

        MOCAP_TO_OSIM_HEIGHT = 0.94 / 17.6356
        MOCAP_TO_OSIM_TRANSLATION = 1.27441  # the relative position of the left toes in the first frame of mocap data

        self.nframes = mocap.nframes
        self.frame_time = mocap.frame_time

        self.joints = {}
        self.joints['hip_l'] = np.array([
            self.align_mocap_to_osim(eul_mocap, [0, 0, 21])
            for eul_mocap in mocap.frames_joint_channels(
                'LeftUpLeg', ['Xrotation', 'Yrotation', 'Zrotation'])
        ])
        self.joints['hip_r'] = np.array([
            self.align_mocap_to_osim(eul_mocap, [0, 0, -21])
            for eul_mocap in mocap.frames_joint_channels(
                'RightUpLeg', ['Xrotation', 'Yrotation', 'Zrotation'])
        ])
        self.joints['knee_l'] = np.array([
            self.align_mocap_to_osim(eul_mocap, [0, 0, 21])
            for eul_mocap in mocap.frames_joint_channels(
                'LeftLeg', ['Xrotation', 'Yrotation', 'Zrotation'])
        ])[:, :1]
        self.joints['knee_r'] = np.array([
            self.align_mocap_to_osim(eul_mocap, [0, 0, -21])
            for eul_mocap in mocap.frames_joint_channels(
                'RightLeg', ['Xrotation', 'Yrotation', 'Zrotation'])
        ])[:, :1]
        self.joints['ankle_l'] = np.array([
            self.align_mocap_to_osim(eul_mocap, [0, 0, 21])
            for eul_mocap in mocap.frames_joint_channels(
                'LeftFoot', ['Xrotation', 'Yrotation', 'Zrotation'])
        ])[:, :1]
        self.joints['ground_pelvis'] = np.array([
            mocap.frames_joint_channels('Pelvis', [
                'Xrotation', 'Yrotation', 'Zrotation', 'Xposition',
                'Yposition', 'Zposition'
            ])
        ]).squeeze()

        # now make a few tweaks to the reference motion to zero out some joints
        self.joints[
            'ground_pelvis'][:, 3:] = self.joints['ground_pelvis'][:, 3:].dot(
                matrix_from_euler(0, -90, 0)) * MOCAP_TO_OSIM_HEIGHT
        self.joints['ground_pelvis'][:, 3] += MOCAP_TO_OSIM_TRANSLATION
        self.joints['ground_pelvis'][:, :3] = self.joints[
            'hip_l'][:, 1:] = self.joints['hip_r'][:, 1:] = 0
示例#12
0
def get_bvh_offsets_and_animation(file_name, frame_number):
    with open(file_name) as f:
        mocap = Bvh(f.read())

    mocap_joint_names = mocap.get_joints_names()
    mocap_joint_prefix = mocap_joint_names[0].split('Hips')[0]

    rotation_matrices = np.empty((1, 3, 3), dtype=float)
    offsets = np.empty((1, 3), dtype=float)
    root_position = mocap.frame_joint_channels(
        frame_number, mocap_joint_names[0],
        ['Xposition', 'Yposition', 'Zposition'])
    for name in joint_names:  # predefined joint_names
        mocap_joint_name = mocap_joint_prefix + name
        euler = mocap.frame_joint_channels(
            frame_number, mocap_joint_name,
            ['Xrotation', 'Yrotation', 'Zrotation'])
        #     print(name, euler)
        # rot = R.from_euler('xyz', euler, degrees=False)  # Previous models are trained for wrong rotations
        rot = R.from_euler('XYZ', euler,
                           degrees=True)  # should we use 'XYZ', degrees=True?
        rot = np.array(rot.as_matrix())
        rot = rot.reshape(1, 3, 3)
        rotation_matrices = np.append(rotation_matrices, rot, axis=0)

        offset = np.array(mocap.joint_offset(mocap_joint_name))
        offsets = np.append(offsets, offset.reshape(1, 3), axis=0)

        # print('{}:\nRotationMatrix:\n'.format(name), rot[0], '\nOffset: ', offset.reshape(3, ))

    offsets = np.delete(offsets, [0, 0], axis=0)
    rotation_matrices = np.delete(rotation_matrices, [0, 0, 0], axis=0)
    return offsets, rotation_matrices, root_position  #[3], [J, 3], [J, 3]
示例#13
0
 def test_joint_children(self):
     with open('tests/test_mocapbank.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual(
         mocap.joint_direct_children('Chest')[0].name, 'Chest2')
     self.assertEqual(mocap.joint_direct_children('Hips')[0].name, 'Chest')
     self.assertEqual(
         mocap.joint_direct_children('Hips')[1].name, 'LeftHip')
     self.assertEqual(
         mocap.joint_direct_children('Hips')[2].name, 'RightHip')
     self.assertEqual(mocap.joint_direct_children('RightWrist'), [])
示例#14
0
    def load_from_bvh(self, fname, exclude_bones=None, spec_channels=None):
        if exclude_bones is None:
            exclude_bones = {}
        if spec_channels is None:
            spec_channels = dict()
        with open(fname) as f:
            mocap = Bvh(f.read())

        joint_names = list(
            filter(lambda x: all([t not in x for t in exclude_bones]),
                   mocap.get_joints_names()))
        dof_ind = {'x': 0, 'y': 1, 'z': 2}
        self.len_scale = 0.0254
        self.root = Bone()
        self.root.id = 0
        self.root.name = joint_names[0]
        self.root.channels = mocap.joint_channels(self.root.name)
        self.name2bone[self.root.name] = self.root
        self.bones.append(self.root)
        for i, joint in enumerate(joint_names[1:]):
            bone = Bone()
            bone.id = i + 1
            bone.name = joint
            bone.channels = spec_channels[joint] if joint in spec_channels.keys(
            ) else mocap.joint_channels(joint)
            bone.dof_index = [dof_ind[x[0].lower()] for x in bone.channels]
            bone.offset = np.array(mocap.joint_offset(joint)) * self.len_scale
            bone.lb = [-180.0] * 3
            bone.ub = [180.0] * 3
            self.bones.append(bone)
            self.name2bone[joint] = bone

        for bone in self.bones[1:]:
            parent_name = mocap.joint_parent(bone.name).name
            if parent_name in self.name2bone.keys():
                bone_p = self.name2bone[parent_name]
                bone_p.child.append(bone)
                bone.parent = bone_p

        self.forward_bvh(self.root)
        for bone in self.bones:
            if len(bone.child) == 0:
                bone.end = bone.pos + np.array([
                    float(x)
                    for x in mocap.get_joint(bone.name).children[-1]['OFFSET']
                ]) * self.len_scale
            else:
                bone.end = sum([bone_c.pos
                                for bone_c in bone.child]) / len(bone.child)
示例#15
0
    def test_bones(self):
        bones = []
        with open('tests/test_freebvh.bvh') as f:
            mocap = Bvh(f.read())

        def iterate_joints(joint):
            bones.append(str(joint))
            for child in joint.filter('JOINT'):
                iterate_joints(child)
        iterate_joints(next(mocap.root.filter('ROOT')))
        self.assertEqual(bones[0], 'ROOT mixamorig:Hips')
        self.assertEqual(bones[17], 'JOINT mixamorig:LeftHandThumb2')
        self.assertEqual(bones[22], 'JOINT mixamorig:LeftHandRing1')
        self.assertEqual(bones[30], 'JOINT mixamorig:RightForeArm')
示例#16
0
def Import_Bvh(file_path):
    try:
        if not os.path.exists(file_path):
            print('File .BVH is not available.')
        bpy.ops.import_anim.bvh(filepath=file_path,
                                axis_forward='Y',
                                axis_up='Z',
                                rotate_mode='NATIVE')
        with open(file_path) as f:
            global frame_end
            mocap = Bvh(f.read())
            frame_end = mocap.nframes
        print("Importing is successful !!!")
    except:
        print("Couln't open file: {}".format(file_path))
示例#17
0
def Get_Data_Rotation_BVH_File(pathMotion, divideMotion):
    ROTATION_KEY_DATA = []
    dataRotationMoverment = []
    bpy.ops.object.mode_set(mode='OBJECT')
    bpy.ops.object.delete(use_global=False)
    bpy.ops.import_anim.bvh(filepath=pathMotion,
                            axis_forward="Y",
                            axis_up="Z",
                            rotate_mode="NATIVE")
    with open(pathMotion) as f:
        global frame_end
        mocap = Bvh(f.read())
        frame_end = mocap.nframes
        #frame_end = numberFrame
        sce = bpy.context.scene
        ob = bpy.context.object
        if divideMotion == 0:
            for f in range(frame_start, frame_end):
                sce.frame_set(f)
                rotation_bone = []
                for pbone in ob.pose.bones:
                    if pbone.name in Setting.List_Bone_Upper_Body:
                        rotation_bone.extend([
                            pbone.rotation_euler.x, pbone.rotation_euler.y,
                            pbone.rotation_euler.z
                        ])
                ROTATION_KEY_DATA.append(rotation_bone)
        elif divideMotion == 1:
            for f in range(frame_start, frame_end):
                sce.frame_set(f)
                rotation_bone = []
                for pbone in ob.pose.bones:
                    if pbone.name in Setting.List_Bone_Lower_Body:
                        rotation_bone.extend([
                            pbone.rotation_euler.x, pbone.rotation_euler.y,
                            pbone.rotation_euler.z
                        ])
                ROTATION_KEY_DATA.append(rotation_bone)
        else:
            print("Wrong data divideMotion.")

        dataRotationMoverment = np.asarray(ROTATION_KEY_DATA)
        print("Get data rotation from BVH file done.")
    return dataRotationMoverment
示例#18
0
 def test_nframes_red_light(self):
     mocap = Bvh('')
     with self.assertRaises(LookupError):
         mocap.nframes
示例#19
0
 def test_nframes(self):
     with open('tests/test_freebvh.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual(mocap.nframes, 69)
示例#20
0
 def test_unknown_joint(self):
     with open('tests/test_mocapbank.bvh') as f:
         mocap = Bvh(f.read())
     with self.assertRaises(LookupError):
         mocap.joint_offset('FooBar')
示例#21
0
 def test_unknown_attribute(self):
     with open('tests/test_freebvh.bvh') as f:
         mocap = Bvh(f.read())
     with self.assertRaises(IndexError):
         mocap.root['Broken']
示例#22
0
 def test_file_read(self):
     with open('tests/test_freebvh.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual(len(mocap.data), 98838)
示例#23
0
 def test_joint_offset(self):
     with open('tests/test_mocapbank.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual(mocap.joint_offset('RightElbow'), (-2.6865, -25.0857, 1.2959))
示例#24
0
 def test_search_single_item_joints(self):
     with open('tests/test_mocapbank.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual(len(mocap.search('JOINT')), 18)
示例#25
0
 def test_search_single_item(self):
     with open('tests/test_mocapbank.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual([str(node) for node in mocap.search('ROOT')], ['ROOT Hips'])
示例#26
0
 def test_search(self):
     with open('tests/test_mocapbank.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual([str(node) for node in mocap.search('JOINT', 'LeftShoulder')], ['JOINT LeftShoulder'])
示例#27
0
 def test_filter(self):
     with open('tests/test_freebvh.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual([str(item) for item in mocap.root.filter('ROOT')], ['ROOT mixamorig:Hips'])
示例#28
0
 def test_frame_time(self):
     with open('tests/test_freebvh.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual(mocap.frame_time, 0.0333333)
示例#29
0
    return R
"""
def get_position(item,frame):

    if(item=="Hips"):
        px = mocap.frame_joint_channel(frame, mocap.joint_parent(item).name, 'Xposition')
        py = mocap.frame_joint_channel(frame, mocap.joint_parent(item).name, 'Yposition')
        pz = mocap.frame_joint_channel(frame, mocap.joint_parent(item).name, 'Zposition')
        return [px,py,pz]
    x = mocap.frame_joint_channel(frame, item, 'Xrotation')
    y = mocap.frame_joint_channel(frame, item, 'Yrotation')
    z = mocap.frame_joint_channel(frame, item, 'Zrotation')
    return get_position(mocap.joint_parent(item).name)+rotM([x,y,z]).dot(list(mocap.joint_offset(item)))
"""
with open('lock6.bvh','r') as f:
    mocap = Bvh(f.read())

    def get_position(item,frame,mocap):
    
        if(item=="Hips"):
            px = mocap.frame_joint_channel(frame, item, 'Xposition')
            py = mocap.frame_joint_channel(frame, item, 'Yposition')
            pz = mocap.frame_joint_channel(frame, item, 'Zposition')
            return [px,py,pz]
        x = mocap.frame_joint_channel(frame, item, 'Xrotation')
        y = mocap.frame_joint_channel(frame, item, 'Yrotation')
        z = mocap.frame_joint_channel(frame, item, 'Zrotation')
        return get_position(mocap.joint_parent(item).name,frame,mocap)+rotM([x,y,z]).dot(list(mocap.joint_offset(item)))

    frame_num = list(range(mocap.nframes-1))
示例#30
0
 def test_offset(self):
     with open('tests/test_mocapbank.bvh') as f:
         mocap = Bvh(f.read())
     self.assertEqual(next(mocap.root.filter('ROOT'))['OFFSET'], ['0.0000', '0.0000', '0.0000'])