Python scipy.spatial.transform.Rotation.from_rotvec() Examples

The following are 5 code examples of scipy.spatial.transform.Rotation.from_rotvec(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module scipy.spatial.transform.Rotation , or try the search function .
Example #1
Source File: face_model.py    From pytorch_mpiigaze with MIT License 6 votes vote down vote up
def estimate_head_pose(self, face: Face, camera: Camera) -> None:
        """Estimate the head pose by fitting 3D template model."""
        # If the number of the template points is small, cv2.solvePnP
        # becomes unstable, so set the default value for rvec and tvec
        # and set useExtrinsicGuess to True.
        # The default values of rvec and tvec below mean that the
        # initial estimate of the head pose is not rotated and the
        # face is in front of the camera.
        rvec = np.zeros(3, dtype=np.float)
        tvec = np.array([0, 0, 1], dtype=np.float)
        _, rvec, tvec = cv2.solvePnP(self.LANDMARKS,
                                     face.landmarks,
                                     camera.camera_matrix,
                                     camera.dist_coefficients,
                                     rvec,
                                     tvec,
                                     useExtrinsicGuess=True,
                                     flags=cv2.SOLVEPNP_ITERATIVE)
        rot = Rotation.from_rotvec(rvec)
        face.head_pose_rot = rot
        face.head_position = tvec
        face.reye.head_pose_rot = rot
        face.leye.head_pose_rot = rot 
Example #2
Source File: dcm.py    From pyins with MIT License 6 votes vote down vote up
def from_rv(rv):
    """Create a direction cosine matrix from a rotation vector.

    The direction of a rotation vector determines the axis of rotation and its
    magnitude determines the angle of rotation.

    The returned DCM projects a vector from the rotated frame to the original
    frame.

    Parameters
    ----------
    rv : array_like, shape (3,) or (n, 3)
        Rotation vectors.

    Returns
    -------
    dcm : ndarray, shape (3, 3) or (n, 3, 3)
        Direction cosine matrices.
    """
    return Rotation.from_rotvec(rv).as_matrix() 
Example #3
Source File: pointcloud.py    From AlignNet-3D with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_mat_angle(translation=None, rotation=None, rotation_center=np.array([0., 0, 0])):
    mat1 = np.eye(4)
    mat2 = np.eye(4)
    mat3 = np.eye(4)
    mat1[:3, 3] = -rotation_center
    mat3[:3, 3] = rotation_center
    if translation is not None:
        mat3[:3, 3] += translation
    if rotation is not None:
        mat2[:3, :3] = Rotation.from_rotvec(np.array([0, 0, 1.]) * rotation).as_dcm()
    return np.matmul(np.matmul(mat3, mat2), mat1) 
Example #4
Source File: snap.py    From plonk with MIT License 4 votes vote down vote up
def rotate(self, rotation: Union[ndarray, Rotation]) -> Snap:
        """Rotate snapshot.

        Parameters
        ----------
        rotation
            The rotation as a scipy.spatial.transform.Rotation object
            or ndarray that can be converted to a Rotation object via
            Rotation.from_rotvec.

        Returns
        -------
        Snap
            The rotated Snap. Note that the rotation operation is
            in-place.

        Examples
        --------
        Rotate a Snap by π/3 around [1, 1, 0].

        >>> rot = np.array([1, 1, 0])
        >>> rot = rot * np.pi / 3 * np.linalg.norm(rot)
        >>> snap.rotate(rot)
        """
        logger.debug(f'Rotating snapshot: {self.file_path.name}')
        if isinstance(rotation, (list, tuple, ndarray)):
            rotation = Rotation.from_rotvec(rotation)
        for arr in self._vector_arrays:
            if arr in self.loaded_arrays():
                self._arrays[arr] = rotation.apply(self._arrays[arr])
            if arr in self.loaded_arrays(sinks=True):
                self._sinks[arr] = rotation.apply(self._sinks[arr])
        for arr in self._vector_component_arrays:
            if arr in self.loaded_arrays():
                del self._arrays[arr]
            if arr in self.loaded_arrays(sinks=True):
                del self._sinks[arr]

        if self.rotation is None:
            self.rotation = rotation
        else:
            rot = rotation * self.rotation
            self.rotation = rot

        return self 
Example #5
Source File: anvil_correction.py    From dials with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def goniometer_rotation(experiment, reflections):
    # type: (Experiment, flex.reflection_table) -> Rotation
    """
    Calculate the goniometer rotation operator for each reflection.

    Following the DXTBX model of a goniometer, whereby a scan is only possible
    around one physical axis at a time, the rotation operation (conventionally
    denoted R, here denoted R' to avoid confusion with the notation of
    dxtbx/model/goniometer.h) can be calculated as R' = S · R · F.
    Here:
        * S is the 'setting rotation', the operator denoting the position of all parent
        axes of the scan axis, which hence defines the orientation of the scan axis;
        * R is the the operator denoting the scan rotation as if it were performed with
        all parent axes at zero datum, it has a different value for each reflection,
        according to the reflection centroid positions.
        * F is the 'fixed rotation', denoting the orientation of all child axes of the
        scan axis as if they were performed with all parent axes at zero datum.

    Args:
        experiment:  The DXTBX experiment object corresponding to the scan.
        reflections:  A table of reflections at which to calculate the rotations.

    Returns:
        An array of rotation operators, one per reflection in the reflection table.
    """
    # Get the axis of the scan rotation.
    rotation_axis = experiment.goniometer.get_rotation_axis_datum()
    # For each reflection, get the angle of the scan rotation.
    angles = reflections["xyzobs.mm.value"].parts()[2]
    # Construct a rotation vector (parallel with the rotation axis and with
    # magnitude equal to the rotation angle) for each reflection.
    # The shape of this array is (N, 3), where N is the number of reflections.
    rotvecs = np.outer(angles, rotation_axis)
    # Create a rotation operator for each scan rotation (i.e. one per reflection).
    # In the notation of dxtbx/model/goniometer.h, this is R.
    scan_rotation = Rotation.from_rotvec(rotvecs)

    # Get the setting rotation.
    # In the notation of dxtbx/model/goniometer.h, this is S.
    set_rotation = np.array(experiment.goniometer.get_setting_rotation()).reshape(3, 3)
    if hasattr(Rotation, "from_matrix"):
        set_rotation = Rotation.from_matrix(set_rotation)
    else:
        # SciPy < 1.4.0. Can be removed after 15th of September 2020
        set_rotation = Rotation.from_dcm(set_rotation)

    # Create a rotation operator for those axes that are fixed throughout the scan.
    # In the notation of dxtbx/model/goniometer.h, this is F.
    fixed_rotation = np.array(experiment.goniometer.get_fixed_rotation()).reshape(3, 3)
    if hasattr(Rotation, "from_matrix"):
        fixed_rotation = Rotation.from_matrix(fixed_rotation)
    else:
        # SciPy < 1.4.0. Can be removed after 15th of September 2020
        fixed_rotation = Rotation.from_dcm(fixed_rotation)

    # Calculate the rotation operator representing the goniometer orientation for each
    # reflection.  In the notation of dxtbx/model/goniometer.h this is S × R × F.
    return set_rotation * scan_rotation * fixed_rotation