当前位置: 首页>>代码示例>>Python>>正文


Python transformations.quaternion_matrix函数代码示例

本文整理汇总了Python中transformations.quaternion_matrix函数的典型用法代码示例。如果您正苦于以下问题:Python quaternion_matrix函数的具体用法?Python quaternion_matrix怎么用?Python quaternion_matrix使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了quaternion_matrix函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getBlendedPose

    def getBlendedPose(self, poses, weights, additiveBlending=True):
        import transformations as tm

        REST_QUAT = np.asarray([1,0,0,0], dtype=np.float32)

        if isinstance(poses[0], basestring):
            f_idxs = [self.getPoseNames().index(pname) for pname in poses]
        else:
            f_idxs = poses

        if not additiveBlending:
            # normalize weights
            if not isinstance(weights, np.ndarray):
                weights = np.asarray(weights, dtype=np.float32)
            t = sum(weights)
            if t < 1:
                # Fill up rest with neutral pose (neutral pose is assumed to be first frame)
                weights = np.asarray(weights + [1.0-t], dtype=np.float32)
                f_idxs.append(0)
            weights /= t

        #print zip([self.getPoseNames()[_f] for _f in f_idxs],weights)

        result = emptyPose(self.nBones)
        m = np.identity(4, dtype=np.float32)
        m1 = np.identity(4, dtype=np.float32)
        m2 = np.identity(4, dtype=np.float32)

        if len(f_idxs) == 1:
            for b_idx in xrange(self.nBones):
                m[:3, :4] = self.getAtFramePos(f_idxs[0], True)[b_idx]
                q = tm.quaternion_slerp(REST_QUAT, tm.quaternion_from_matrix(m, True), float(weights[0]))
                result[b_idx] = tm.quaternion_matrix( q )[:3,:4]
        else:
            for b_idx in xrange(self.nBones):
                m1[:3, :4] = self.getAtFramePos(f_idxs[0], True)[b_idx]
                m2[:3, :4] = self.getAtFramePos(f_idxs[1], True)[b_idx]
                q1 = tm.quaternion_slerp(REST_QUAT, tm.quaternion_from_matrix(m1, True), float(weights[0]))
                q2 = tm.quaternion_slerp(REST_QUAT, tm.quaternion_from_matrix(m2, True), float(weights[1]))
                quat = tm.quaternion_multiply(q2, q1)

                for i,f_idx in enumerate(f_idxs[2:]):
                    i += 2
                    m[:3, :4] = self.getAtFramePos(f_idx, True)[b_idx]
                    q = tm.quaternion_slerp(REST_QUAT, tm.quaternion_from_matrix(m, True), float(weights[i]))
                    quat = tm.quaternion_multiply(q, quat)

                result[b_idx] = tm.quaternion_matrix( quat )[:3,:4]

        return Pose(self.name+'-blended', result)
开发者ID:TeoTwawki,项目名称:makehuman,代码行数:50,代码来源:animation.py

示例2: setRotationIndex

 def setRotationIndex(self, index, angle, useQuat):
     """
     Set the rotation for one of the three rotation channels, either as
     quaternion or euler matrix. index should be 1,2 or 3 and represents
     x, y and z axis accordingly
     """
     if useQuat:
         quat = tm.quaternion_from_matrix(self.matPose)
         log.debug("%s", str(quat))
         quat[index] = angle/1000
         log.debug("%s", str(quat))
         _normalizeQuaternion(quat)
         log.debug("%s", str(quat))
         self.matPose = tm.quaternion_matrix(quat)
         return quat[0]*1000
     else:
         angle = angle*D
         ax,ay,az = tm.euler_from_matrix(self.matPose, axes='sxyz')
         if index == 1:
             ax = angle
         elif index == 2:
             ay = angle
         elif index == 3:
             az = angle
         mat = tm.euler_matrix(ax, ay, az, axes='sxyz')
         self.matPose[:3,:3] = mat[:3,:3]
         return 1000.0
开发者ID:TeoTwawki,项目名称:makehuman,代码行数:27,代码来源:skeleton.py

示例3: writeAnimation

def writeAnimation(fp, bone, action, config):
    aname = "Action%s" % bone.name
    points = action[bone.name]

    for channel,default in [
            ("T", 0),
            ("R", 0),
            ("S", 1)
        ]:
        writeAnimationCurveNode(fp, bone, channel, default)

    relmat = bone.getRelativeMatrix(config.meshOrientation, config.localBoneAxis, config.offset)
    translations = []
    eulers = []
    R = 180/math.pi
    for quat in points:
        mat = tm.quaternion_matrix(quat)
        mat = np.dot(relmat, mat)
        translations.append(mat[:3,3])
        eul = tm.euler_from_matrix(mat, axes='sxyz')
        eulers.append((eul[0]*R, eul[1]*R, eul[2]*R))
    scales = len(points)*[(1,1,1)]

    for channel,data in [
            ("T", translations),
            ("R", eulers),
            ("S", scales)
        ]:
        for idx,coord in enumerate(["X","Y","Z"]):
            writeAnimationCurve(fp, idx, coord, bone, channel, data)
开发者ID:TeoTwawki,项目名称:makehuman,代码行数:30,代码来源:fbx_anim.py

示例4: apply_to_matrix

def apply_to_matrix(x, A):
    """Applies the change of basis given by the SO3 quantity
    x to the 3by3 matrix M.

    To be clear, this performs:
    R * A * transpose(R)
    where R is the rotation matrix form of x.

    >>> A = np.random.rand(3, 3)
    >>> q = trns.random_quaternion()
    >>> R = trns.quaternion_matrix(q)
    >>> B1 = R[:3, :3].dot(A).dot(R[:3, :3].T)
    >>> B2 = apply_to_matrix(q, A)
    >>> print(np.allclose(B1, B2))
    True

    """
    A = np.array(A)
    if A.shape != (3, 3):
        raise ValueError("A must be 3 by 3.")
    xrep = rep(x)
    # Get rotation matrix if not rotmat:
    if xrep == 'rotvec':
        x = matrix_from_rotvec(x)
    elif xrep == 'quaternion':
        x = trns.quaternion_matrix(x)[:3, :3]
    elif xrep == 'tfmat':
        x = x[:3, :3]
    elif xrep != 'rotmat':
        raise ValueError("Quantity to apply is not on SO3.")
    # Apply change of basis to A:
    return x.dot(A).dot(x.T)
开发者ID:jnez71,项目名称:orientation_library,代码行数:32,代码来源:so3tools.py

示例5: loadPoseFromMhpFile

    def loadPoseFromMhpFile(self, filepath):
        """
        Load a MHP pose file that contains a static pose. Posing data is defined
        with quaternions to indicate rotation angles.
        Sets current pose to
        """
        log.message("Mhp %s", filepath)
        fp = open(filepath, "rU", encoding="utf-8")

        boneMap = self.getBoneToIdxMapping()
        nBones = len(boneMap.keys())
        poseMats = np.zeros((nBones,4,4),dtype=np.float32)
        poseMats[:] = np.identity(4, dtype=np.float32)

        for line in fp:
            words = line.split()
            if len(words) < 5:
                continue
            elif words[1] in ["quat", "gquat"]:
                boneIdx = boneMap[words[0]]
                quat = float(words[2]),float(words[3]),float(words[4]),float(words[5])
                mat = tm.quaternion_matrix(quat)
                if words[1] == "gquat":
                    bone = self.bones[boneIdx]
                    mat = np.dot(la.inv(bone.matRestRelative), mat)
                poseMats[boneIdx] = mat[:3,:3]

        fp.close()
        self.setPose(poseMats)
开发者ID:nitish116,项目名称:mhx_os,代码行数:29,代码来源:skeleton.py

示例6: readMhpFile

 def readMhpFile(self, filepath):
     log.message("Loading MHP file %s", filepath)
     amt = self.armature
     fp = open(filepath, "rU")
     bname = None
     mat = np.identity(4, float)
     for line in fp:
         words = line.split()
         if len(words) < 4:
             continue
         if words[0] != bname:
             self.setMatrixPose(bname, mat)
             bname = words[0]
             mat = np.identity(4, float)
         if words[1] in ["quat", "gquat"]:
             quat = float(words[2]),float(words[3]),float(words[4]),float(words[5])
             mat = tm.quaternion_matrix(quat)
             if words[1] == "gquat":
                 pb = self.posebones[words[0]]
                 mat = np.dot(la.inv(pb.bone.matrixRelative), mat)
         elif words[1] == "scale":
             scale = 1+float(words[2]), 1+float(words[3]), 1+float(words[4])
             smat = tm.compose_matrix(scale=scale)
             mat = np.dot(smat, mat)
         elif words[1] == "matrix":
             rows = []
             n = 2
             for i in range(4):
                 rows.append((float(words[n]), float(words[n+1]), float(words[n+2]), float(words[n+3])))
                 n += 4
             mat = np.array(rows)
     self.setMatrixPose(bname, mat)
     fp.close()
     self.update()
开发者ID:nitish116,项目名称:mhx_os,代码行数:34,代码来源:pose.py

示例7: draw_trajectory

    def draw_trajectory(self, pose_array, angles, ns="default_ns"):
        decimation = max(len(pose_array.poses)//6, 1)
        ps = gm.PoseStamped()
        ps.header.frame_id = pose_array.header.frame_id        
        ps.header.stamp = rospy.Time.now()
        handles = []
 
        multiplier = 5.79 
        
        for (pose,angle) in zip(pose_array.poses,angles)[::decimation]:

            ps.pose = deepcopy(pose)
            pointing_axis = transformations.quaternion_matrix([pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w])[:3,0]
            ps.pose.position.x -= .18*pointing_axis[0]
            ps.pose.position.y -= .18*pointing_axis[1]
            ps.pose.position.z -= .18*pointing_axis[2]
            
            
            root_link = "r_wrist_roll_link"
            valuedict = {"r_gripper_l_finger_joint":angle*multiplier,
                         "r_gripper_r_finger_joint":angle*multiplier,
                         "r_gripper_l_finger_tip_joint":angle*multiplier,
                         "r_gripper_r_finger_tip_joint":angle*multiplier,
                         "r_gripper_joint":angle}
            handles.extend(self.place_kin_tree_from_link(ps, root_link, valuedict, ns=ns))
        return handles
开发者ID:ttblue,项目名称:rapprentice,代码行数:26,代码来源:ros_utils.py

示例8: writeAnimation

def writeAnimation(fp, bone, action, config):
    aname = "Action_%s" % goodBoneName(bone.name)
    points = action[bone.name]
    npoints = len(points)

    fp.write(
        '    <animation id="%s_pose_matrix">\n' % aname +
        '      <source id="%s_pose_matrix-input">\n' % aname +
        '        <float_array id="%s_pose_matrix-input-array" count="%d">' % (aname, npoints))

    fp.write(''.join([" %g" % (0.04*(t+1)) for t in range(npoints)]))

    fp.write(
        '</float_array>\n' +
        '        <technique_common>\n' +
        '          <accessor source="#%s_pose_matrix-input-array" count="%d" stride="1">\n' % (aname, npoints) +
        '            <param name="TIME" type="float"/>\n' +
        '          </accessor>\n' +
        '        </technique_common>\n' +
        '      </source>\n' +
        '      <source id="%s_pose_matrix-output">\n' % aname +
        '        <float_array id="%s_pose_matrix-output-array" count="%d">\n' % (aname, 16*npoints))

    string = '          '
    relmat = bone.getRelativeMatrix(config.meshOrientation, config.localBoneAxis, config.offset)
    for quat in points:
        mat0 = tm.quaternion_matrix(quat)
        mat = np.dot(relmat, mat0)
        string += ''.join(['%g %g %g %g  ' % tuple(mat[i,:]) for i in range(4)])
        string += '\n          '
    fp.write(string)

    fp.write(
        '</float_array>\n' +
        '        <technique_common>\n' +
        '          <accessor source="#%s_pose_matrix-output-array" count="%d" stride="16">\n' % (aname, npoints) +
        '            <param name="TRANSFORM" type="float4x4"/>\n' +
        '          </accessor>\n' +
        '        </technique_common>\n' +
        '      </source>\n' +
        '      <source id="%s_pose_matrix-interpolation">\n' % aname +
        '        <Name_array id="%s_pose_matrix-interpolation-array" count="%d">' % (aname, npoints))

    fp.write(npoints * 'LINEAR ')

    fp.write(
        '</Name_array>\n' +
        '        <technique_common>\n' +
        '          <accessor source="#%s_pose_matrix-interpolation-array" count="%d" stride="1">\n' % (aname, npoints) +
        '            <param name="INTERPOLATION" type="name"/>\n' +
        '          </accessor>\n' +
        '        </technique_common>\n' +
        '      </source>\n' +
        '      <sampler id="%s_pose_matrix-sampler">\n' % aname +
        '        <input semantic="INPUT" source="#%s_pose_matrix-input"/>\n' % aname +
        '        <input semantic="OUTPUT" source="#%s_pose_matrix-output"/>\n' % aname +
        '        <input semantic="INTERPOLATION" source="#%s_pose_matrix-interpolation"/>\n' % aname +
        '      </sampler>\n' +
        '      <channel source="#%s_pose_matrix-sampler" target="%s/transform"/>\n' % (aname, goodBoneName(bone.name)) +
        '    </animation>\n')
开发者ID:orezpraw,项目名称:unnaturalcode,代码行数:60,代码来源:dae_animation.py

示例9: __modify_quaternion

	def __modify_quaternion( self , q , d ) :
		glPushMatrix()
		glLoadMatrixf( tr.quaternion_matrix( q ) )
		glRotatef( d[0] , 0 , 1 , 0 )
		glRotatef( d[1] , 1 , 0 , 0 )
		q = tr.quaternion_from_matrix( glGetDoublev(GL_MODELVIEW_MATRIX) )
		glPopMatrix()
		return q
开发者ID:jkotur,项目名称:queuler,代码行数:8,代码来源:quaternions.py

示例10: step

	def step( self , dt ) :
		if not self.R.successful() : return
		self.Q = self.R.integrate(self.R.t+dt)
		if len(self.trace) > self.trace_len :
			self.trace.pop(0)
		if len(self.trace) < self.trace_len+1 :
			qm = tr.quaternion_matrix( self.Q[3:] )
			self.trace.append( np.dot( qm , self.x[-1] ) )
开发者ID:jkotur,项目名称:spinning_top,代码行数:8,代码来源:top.py

示例11: toMatrix

 def toMatrix(self):
     q0 = self.even
     mat = tm.quaternion_matrix(q0)
     q1 = self.odd        
     mat[0,3] = 2.0*(-q1[0]*q0[1] + q1[1]*q0[0] - q1[2]*q0[3] + q1[3]*q0[2])
     mat[1,3] = 2.0*(-q1[0]*q0[2] + q1[1]*q0[3] + q1[2]*q0[0] - q1[3]*q0[1])
     mat[2,3] = 2.0*(-q1[0]*q0[3] - q1[1]*q0[2] + q1[2]*q0[1] + q1[3]*q0[0])
     return mat
开发者ID:RuliLG,项目名称:makehuman,代码行数:8,代码来源:dual_quaternions.py

示例12: interp_transforms

def interp_transforms(T1, T2, alpha):
    assert alpha <= 1
    T_avg = alpha * T1 + (1 - alpha) * T2
    q1 = quaternion_from_matrix(T1)
    q2 = quaternion_from_matrix(T2)
    q3 = quaternion_slerp(q1, q2, alpha)
    R = quaternion_matrix(q3)
    T_avg[0:3, 0:3] = R[0:3, 0:3]
    return T_avg
开发者ID:yinggo,项目名称:caffe,代码行数:9,代码来源:LidarTransforms.py

示例13: _draw_scene

	def _draw_scene( self ) :
		glPushMatrix()
		glTranslatef( *self.b )
		glPushMatrix()
		glMultMatrixd( tr.quaternion_matrix( self.qb ) )
		self.frame.draw()
		glPopMatrix()

		glTranslatef( *self.c )
		glMultMatrixd( tr.quaternion_matrix( self.qc ) )
		self.frame.draw()
		glPopMatrix()

		glPushMatrix()
		glTranslatef( *self.e )
		glMultMatrixd( tr.quaternion_matrix( self.qe ) )
		self.frame.draw()
		glPopMatrix()
开发者ID:jkotur,项目名称:queuler,代码行数:18,代码来源:quaternions.py

示例14: compute_ref_accuracy

def compute_ref_accuracy(fid_path, original_corrs_path,
                         geo_tform):

    #Load fiducial .ply
    fid = open(fid_path, 'r')
    fid_points = np.genfromtxt(fid, dtype=float, delimiter=' ',
                                skip_header=9)
    fid.close()
    #Load original corrs .ply
    fid = open(original_corrs_path, 'r')
    original_corrs = np.genfromtxt(fid, dtype=float,
                                    delimiter=' ', skip_header=9)
    fid.close()

    #Load transformation
    #************GEO**************"
    Tfis = open(geo_tform, 'r')
    lines = []
    lines = Tfis.readlines()
    scale_geo = float(lines[0])
    Ss_geo = tf.scale_matrix(scale_geo)
    quat_line = lines[1].split(" ")
    quat_geo = np.array([float(quat_line[3]), float(quat_line[0]),
                         float(quat_line[1]), float(quat_line[2])])
    Rs_geo = tf.quaternion_matrix(quat_geo)
    trans_line = lines[2].split(" ")
    trans_geo = np.array([float(trans_line[0]), float(trans_line[1]),
                          float(trans_line[2])])
    Tfis.close()
    Hs_geo = Rs_geo.copy()
    Hs_geo[:3, 3] = trans_geo[:3]
    Hs_geo = Ss_geo.dot(Hs_geo)

    LOG.debug("\n******Geo***** \n Scale: \n%s \nR:\n%s \nT:\n%s \nH:\n%s",
        Ss_geo, Rs_geo, trans_geo, Hs_geo)

    #Compute the "reference error"
    #i.e. fiducial points - geo registered correspondances
    npoints, c = fid_points.shape
    if npoints != 30:
        LOG.warn("Number of fiducial point is NOT 30")
    if c != 3:
        LOG.error("Fiducial points has the wrong number of dimensions")
    # import code; code.interact(local=locals())

    fid_points_hom = np.hstack((fid_points, np.ones([npoints, 1]))).T
    original_corrs_hom = np.hstack((original_corrs, np.ones([npoints, 1]))).T
    geo_corrs_hom = Hs_geo.dot(original_corrs_hom)
    geo_ref_diff = geo_corrs_hom - fid_points_hom

    # import pdb; pdb.set_trace()

    delta_z = np.sqrt(geo_ref_diff[2, :] * geo_ref_diff[2, :])
    delta_r = np.sqrt(geo_ref_diff[0, :] * geo_ref_diff[0, :] +
                      geo_ref_diff[1, :] * geo_ref_diff[1, :])

    return delta_z, delta_r
开发者ID:mirestrepo,项目名称:voxels-at-lems,代码行数:57,代码来源:compute_trans_geo_accuracy.py

示例15: newPose

	def newPose(self, poseMsg):
		self.publish()
		q = [poseMsg.orientation.x, poseMsg.orientation.y, poseMsg.orientation.z, poseMsg.orientation.w]
		rq = transformations.quaternion_matrix(q)
		al, be, ga = transformations.euler_from_matrix(rq, 'rxyz')
		self.ga = ga
		x = poseMsg.position.x
		y = poseMsg.position.y
		z = poseMsg.position.z
		self.dist = math.sqrt(x*x + y*y + z*z)
		print al, be, ga
开发者ID:lianqiang,项目名称:InteractWithAurora,代码行数:11,代码来源:controller.py


注:本文中的transformations.quaternion_matrix函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。