Python numpy.rad2deg() Examples

The following are 30 code examples of numpy.rad2deg(). 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 numpy , or try the search function .
Example #1
Source File: get_points.py    From visual_foresight with MIT License 6 votes vote down vote up
def main_sawyer():
    import intera_interface
    from visual_mpc.envs.robot_envs.sawyer.sawyer_impedance import SawyerImpedanceController
    
    controller = SawyerImpedanceController('sawyer', True, gripper_attached='none')       # doesn't initial gripper object even if gripper is attached

    def print_eep(value):
        if not value:
            return
        xyz, quat = controller.get_xyz_quat()
        yaw, roll, pitch = [np.rad2deg(x) for x in controller.quat_2_euler(quat)]
        logging.getLogger('robot_logger').info("XYZ IS: {}, ROTATION IS: yaw={} roll={} pitch={}".format(xyz, yaw, roll, pitch))
    
    navigator = intera_interface.Navigator()
    navigator.register_callback(print_eep, 'right_button_show')
    rospy.spin() 
Example #2
Source File: polar.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def __call__(self, x, pos=None):
        vmin, vmax = self.axis.get_view_interval()
        d = np.rad2deg(abs(vmax - vmin))
        digits = max(-int(np.log10(d) - 1.5), 0)

        if rcParams['text.usetex'] and not rcParams['text.latex.unicode']:
            format_str = r"${value:0.{digits:d}f}^\circ$"
            return format_str.format(value=np.rad2deg(x), digits=digits)
        else:
            # we use unicode, rather than mathtext with \circ, so
            # that it will work correctly with any arbitrary font
            # (assuming it has a degree sign), whereas $5\circ$
            # will only work correctly with one of the supported
            # math fonts (Computer Modern and STIX)
            format_str = "{value:0.{digits:d}f}\N{DEGREE SIGN}"
            return format_str.format(value=np.rad2deg(x), digits=digits) 
Example #3
Source File: test3.py    From pyeo with GNU General Public License v3.0 6 votes vote down vote up
def sample_data_3d(shape):
    """Returns `lons`, `lats`, and fake `data`

    adapted from:
    http://scitools.org.uk/cartopy/docs/v0.15/examples/axes_grid_basic.html
    """

    nlons, nlats = shape
    lats = np.linspace(-np.pi / 2, np.pi / 2, nlats)
    lons = np.linspace(0, 2 * np.pi, nlons)
    lons, lats = np.meshgrid(lons, lats)
    wave = 0.75 * (np.sin(2 * lats) ** 8) * np.cos(4 * lons)
    mean = 0.5 * np.cos(2 * lats) * ((np.sin(2 * lats)) ** 2 + 2)

    lats = np.rad2deg(lats)
    lons = np.rad2deg(lons)
    data = wave + mean

    return lons, lats, data


# get data 
Example #4
Source File: registration.py    From BIRL with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_affine_components(matrix):
    """ get the main components of Affine transform

    :param ndarray matrix: affine transformation matrix for 2d
    :return dict: dictionary of float values

    >>> mtx = np.array([[ -0.95,   0.1,  65.], [  0.1,   0.95, -60.], [  0.,   0.,   1.]])
    >>> import  pandas as pd
    >>> aff = pd.Series(get_affine_components(mtx)).sort_index()
    >>> aff  # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
    rotation                           173.9...
    scale                    (0.95..., 0.95...)
    shear                              -3.14...
    translation                   (65.0, -60.0)
    dtype: object
    """
    aff = AffineTransform(matrix)
    norm_rotation = norm_angle(np.rad2deg(aff.rotation), deg=True)
    comp = {
        'rotation': float(norm_rotation),
        'translation': tuple(aff.translation.tolist()),
        'scale': aff.scale,
        'shear': aff.shear,
    }
    return comp 
Example #5
Source File: demo.py    From pytorch_mpiigaze with MIT License 6 votes vote down vote up
def _draw_gaze_vector(self, face: Face) -> None:
        length = self.config.demo.gaze_visualization_length
        if self.config.mode == GazeEstimationMethod.MPIIGaze.name:
            for key in [FacePartsName.REYE, FacePartsName.LEYE]:
                eye = getattr(face, key.name.lower())
                self.visualizer.draw_3d_line(
                    eye.center, eye.center + length * eye.gaze_vector)
                pitch, yaw = np.rad2deg(eye.vector_to_angle(eye.gaze_vector))
                logger.info(
                    f'[{key.name.lower()}] pitch: {pitch:.2f}, yaw: {yaw:.2f}')
        elif self.config.mode == GazeEstimationMethod.MPIIFaceGaze.name:
            self.visualizer.draw_3d_line(
                face.center, face.center + length * face.gaze_vector)
            pitch, yaw = np.rad2deg(face.vector_to_angle(face.gaze_vector))
            logger.info(f'[face] pitch: {pitch:.2f}, yaw: {yaw:.2f}')
        else:
            raise ValueError 
Example #6
Source File: polar.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def __call__(self, x, pos=None):
        vmin, vmax = self.axis.get_view_interval()
        d = np.rad2deg(abs(vmax - vmin))
        digits = max(-int(np.log10(d) - 1.5), 0)

        if rcParams['text.usetex'] and not rcParams['text.latex.unicode']:
            format_str = r"${value:0.{digits:d}f}^\circ$"
            return format_str.format(value=np.rad2deg(x), digits=digits)
        else:
            # we use unicode, rather than mathtext with \circ, so
            # that it will work correctly with any arbitrary font
            # (assuming it has a degree sign), whereas $5\circ$
            # will only work correctly with one of the supported
            # math fonts (Computer Modern and STIX)
            format_str = "{value:0.{digits:d}f}\N{DEGREE SIGN}"
            return format_str.format(value=np.rad2deg(x), digits=digits) 
Example #7
Source File: spa.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def heliocentric_latitude(jme):
    b0 = 0.0
    b1 = 0.0
    for row in range(HELIO_LAT_TABLE.shape[1]):
        b0 += (HELIO_LAT_TABLE[0, row, 0]
               * np.cos(HELIO_LAT_TABLE[0, row, 1]
                        + HELIO_LAT_TABLE[0, row, 2] * jme)
               )
        b1 += (HELIO_LAT_TABLE[1, row, 0]
               * np.cos(HELIO_LAT_TABLE[1, row, 1]
                        + HELIO_LAT_TABLE[1, row, 2] * jme)
               )

    b_rad = (b0 + b1 * jme)/10**8
    b = np.rad2deg(b_rad)
    return b 
Example #8
Source File: base.py    From kite with GNU General Public License v3.0 6 votes vote down vote up
def orientArrow(self):
        phi = num.nanmedian(self.model.scene.phi)
        theta = num.nanmedian(self.model.scene.theta)

        angle = 180. - num.rad2deg(phi)

        theta_f = theta / (num.pi/2)

        tipAngle = 30. + theta_f * 20.
        tailLen = 15 + theta_f * 15.

        self.arrow.setStyle(
            angle=0.,
            tipAngle=tipAngle,
            tailLen=tailLen,
            tailWidth=6,
            headLen=25)
        self.arrow.setRotation(angle)

        rect_label = self.label.boundingRect()
        rect_arr = self.arrow.boundingRect()

        self.label.setPos(-rect_label.width()/2., rect_label.height()*1.33) 
Example #9
Source File: test_camera.py    From ratcave with MIT License 6 votes vote down vote up
def test_look_at_updates_for_children():
    dist = 2.
    cam = StereoCameraGroup(distance=dist)
    point = np.array([0, 0, 0, 1]).reshape(-1, 1)
    point[2] = -1 #np.random.randint(1, 6)

    angle = np.arctan(point[2]/(cam.distance/2))[0]
    cam.right.rotation.y = -np.rad2deg(angle)
    cam.left.rotation.y = np.rad2deg(angle)
    point_view_mat_left = np.dot(cam.left.view_matrix, point)
    point_view_mat_right = np.dot(cam.right.view_matrix, point)
    assert (point_view_mat_left == point_view_mat_right).all()

    cam2 = StereoCameraGroup(distance=dist)
    cam2.look_at(*point[:3])
    point_view_mat_left2 = np.dot(cam2.left.view_matrix, point)
    point_view_mat_right2 = np.dot(cam2.right.view_matrix, point)
    assert (point_view_mat_left == point_view_mat_left2).all() and (point_view_mat_right == point_view_mat_right2).all() 
Example #10
Source File: polar.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_thetamax(self):
        return np.rad2deg(self.viewLim.xmax) 
Example #11
Source File: test_uvbase.py    From pyuvdata with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_location_degree():
    test_obj = UVTest()
    test_obj2 = test_obj.copy()
    test_obj2.location_lat_lon_alt_degrees = (
        np.rad2deg(ref_latlonalt[0]),
        np.rad2deg(ref_latlonalt[1]),
        ref_latlonalt[2],
    )
    assert test_obj == test_obj2 
Example #12
Source File: polar.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_thetamin(self):
        return np.rad2deg(self.viewLim.xmin) 
Example #13
Source File: model.py    From deep-photometric-stereo-network with MIT License 5 votes vote down vote up
def eval(self, dataset, num, step):
        o_path = os.path.join(self.output_path, "eval")
        if not os.path.exists(o_path):
            os.makedirs(o_path)

        m, n = dataset.img_size
        for i in range(num):
            M, N_, mask = dataset.load_data(dataset.data_list[i])
            M /= np.max(M)
            N = self.test(M, m, n, 10000)

            obj_name, brdf_name = dataset.data_path2name(dataset.data_list[i])

            MAE = np.zeros(shape=(m * n))
            for j in range(m * n):
                if mask[j] == 0:
                    continue
                error = np.dot(N_[:, j], N[:, j]) / (np.linalg.norm(N_[:, j]) * np.linalg.norm(N[:, j]))
                error = np.arccos(np.clip(error, -1., 1.))
                error = np.rad2deg(error)
                MAE[j] = error

            N[:, mask == 0] = 0
            n_img = (N.T.reshape(m, n, 3) + 1.) / 2. * 255.
            plt.figure()
            plt.imshow(n_img.astype(np.uint8))
            plt.title("MAE: {}".format(np.average(MAE[mask != 0])))
            plt.savefig(os.path.join(o_path, "{}_{}-{}.png").format(step, obj_name, brdf_name))
            plt.close() 
Example #14
Source File: scene_io.py    From kite with GNU General Public License v3.0 5 votes vote down vote up
def read(self, filename, **kwargs):
        header = self.parseHeaderFile(filename)

        def load_data(filename):
            self._log.debug('Loading %s' % filename)
            return num.flipud(
                num.fromfile(filename, dtype=num.float32)
                .reshape((header.lines, header.samples)))

        displacement = load_data(filename)
        theta_file, phi_file = self.getLOSFiles(filename)

        if not theta_file:
            theta = num.full_like(displacement, 0.)
        else:
            theta = load_data(theta_file)
            theta = num.deg2rad(theta)

        if not phi_file:
            phi = num.full_like(displacement, num.pi/2)
        else:
            phi = load_data(phi_file)
            phi = num.pi/2 - num.rad2deg(phi)

        c = self.container
        c.displacement = displacement
        c.phi = phi
        c.theta = theta

        map_info = header.map_info
        c.frame.dE = float(map_info[5])
        c.frame.dN = dN = float(map_info[6])
        c.frame.spacing = 'meter'

        c.frame.llLat, c.frame.llLon = utm.to_latlon(
            float(map_info[3]) - header.lines * dN,
            float(map_info[4]),
            zone_number=int(map_info[7]),
            northern=True if map_info[8] == 'Northern' else False)

        return c 
Example #15
Source File: scene.py    From kite with GNU General Public License v3.0 5 votes vote down vote up
def phiDeg(self):
        """ LOS horizontal orientation angle in degree,
            counter-clockwise from East,``NxM`` matrix like
            :class:`kite.Scene.phi`

        :type: :class:`numpy.ndarray`
        """
        return num.rad2deg(self.phi) 
Example #16
Source File: scene.py    From kite with GNU General Public License v3.0 5 votes vote down vote up
def thetaDeg(self):
        """ LOS elevation angle in degree, ``NxM`` matrix like
            :class:`kite.Scene.theta`

        :type: :class:`numpy.ndarray`
        """
        return num.rad2deg(self.theta) 
Example #17
Source File: Numpy.py    From NodeEditor with MIT License 5 votes vote down vote up
def rad2deg(radians=('FloatPin', [0],{PinSpecifires.ENABLED_OPTIONS: PinOptions.ArraySupported})) :
        """radians to degree"""
        
        return list(np.rad2deg(np.array(radians))) 
Example #18
Source File: plot.py    From deskew with MIT License 5 votes vote down vote up
def display_hough(h: float, a: List[float], d: List[float]) -> None:  # pylint: disable=invalid-name
    plt.imshow(
        np.log(1 + h),
        extent=[np.rad2deg(a[-1]), np.rad2deg(a[0]), d[-1], d[0]],
        cmap=plt.gray,
        aspect=1.0 / 90
    )
    plt.show() 
Example #19
Source File: LM_opt.py    From ILCC with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def convert2_ang_cm(ls):
    ret = []
    for i in xrange(3):
        ret.append(np.rad2deg(ls[i]))
    for i in xrange(3):
        ret.append(ls[3 + i] * 100)
    return ret 
Example #20
Source File: panda3d_util.py    From citysim3d with MIT License 5 votes vote down vote up
def scale_crop_camera_parameters(orig_size, orig_hfov, scale_size=None, crop_size=None):
    """
    Returns the parameters (size, hfov) of the camera that renders an image
    which is equivalent to an image that is first rendered from the original
    camera and then scaled by scale_size and center-cropped by crop_size.
    """
    scale_size = scale_size if scale_size is not None else 1.0
    crop_size = crop_size if crop_size is not None else orig_size
    size = crop_size
    hfov = np.rad2deg(2 * np.arctan(np.tan(np.deg2rad(orig_hfov) / 2.) * crop_size[0] / orig_size[0] / scale_size))
    return size, hfov


# python implementation of the VirtualFileSystem method from here:
# https://github.com/panda3d/panda3d/blob/master/panda/src/express/virtualFileSystem.cxx 
Example #21
Source File: pyTarget.py    From pyMHT with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plotCovarianceEllipse(self, eta2):
        from matplotlib.patches import Ellipse
        lambda_, _ = np.linalg.eig(self.kalmanFilter.S)
        ell = Ellipse(xy=(self.kalmanFilter.x_bar[0], self.kalmanFilter.x_bar[1]),
                      width=np.sqrt(lambda_[0]) * np.sqrt(eta2) * 2,
                      height=np.sqrt(lambda_[1]) * np.sqrt(eta2) * 2,
                      angle=np.rad2deg(np.arctan2(lambda_[1], lambda_[0])),
                      linewidth=2,
                      )
        ell.set_facecolor('none')
        ell.set_linestyle("dotted")
        ell.set_alpha(0.5)
        ax = plt.subplot(111)
        ax.add_artist(ell) 
Example #22
Source File: polar.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def view_limits(self, vmin, vmax):
        vmin, vmax = np.rad2deg((vmin, vmax))
        return np.deg2rad(self.base.view_limits(vmin, vmax)) 
Example #23
Source File: polar.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_minpos(self):
        return np.rad2deg(self._axis.get_minpos()) 
Example #24
Source File: polar.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_view_interval(self):
        return np.rad2deg(self._axis.get_view_interval()) 
Example #25
Source File: spa.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def heliocentric_longitude(jme):
    l0 = 0.0
    l1 = 0.0
    l2 = 0.0
    l3 = 0.0
    l4 = 0.0
    l5 = 0.0

    for row in range(HELIO_LONG_TABLE.shape[1]):
        l0 += (HELIO_LONG_TABLE[0, row, 0]
               * np.cos(HELIO_LONG_TABLE[0, row, 1]
                        + HELIO_LONG_TABLE[0, row, 2] * jme)
               )
        l1 += (HELIO_LONG_TABLE[1, row, 0]
               * np.cos(HELIO_LONG_TABLE[1, row, 1]
                        + HELIO_LONG_TABLE[1, row, 2] * jme)
               )
        l2 += (HELIO_LONG_TABLE[2, row, 0]
               * np.cos(HELIO_LONG_TABLE[2, row, 1]
                        + HELIO_LONG_TABLE[2, row, 2] * jme)
               )
        l3 += (HELIO_LONG_TABLE[3, row, 0]
               * np.cos(HELIO_LONG_TABLE[3, row, 1]
                        + HELIO_LONG_TABLE[3, row, 2] * jme)
               )
        l4 += (HELIO_LONG_TABLE[4, row, 0]
               * np.cos(HELIO_LONG_TABLE[4, row, 1]
                        + HELIO_LONG_TABLE[4, row, 2] * jme)
               )
        l5 += (HELIO_LONG_TABLE[5, row, 0]
               * np.cos(HELIO_LONG_TABLE[5, row, 1]
                        + HELIO_LONG_TABLE[5, row, 2] * jme)
               )

    l_rad = (l0 + l1 * jme + l2 * jme**2 + l3 * jme**3 + l4 * jme**4 +
             l5 * jme**5)/10**8
    l = np.rad2deg(l_rad)
    return l % 360 
Example #26
Source File: geo.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def format_coord(self, lon, lat):
        'return a format string formatting the coordinate'
        lon, lat = np.rad2deg([lon, lat])
        if lat >= 0.0:
            ns = 'N'
        else:
            ns = 'S'
        if lon >= 0.0:
            ew = 'E'
        else:
            ew = 'W'
        return ('%f\N{DEGREE SIGN}%s, %f\N{DEGREE SIGN}%s'
                % (abs(lat), ns, abs(lon), ew)) 
Example #27
Source File: get_points.py    From visual_foresight with MIT License 5 votes vote down vote up
def main_franka():
    from visual_mpc.envs.robot_envs.franka.franka_impedance import FrankaImpedanceController
    controller = FrankaImpedanceController('franka', True, gripper_attached='hand')       # doesn't initial gripper object even if gripper is attached

    def print_eep(value):
        if not value:
            return
        xyz, quat = controller.get_xyz_quat()
        yaw, roll, pitch = [np.rad2deg(x) for x in controller.quat_2_euler(quat)]
        print(xyz)
        logging.getLogger('robot_logger').info("XYZ IS: {}, ROTATION IS: yaw={} roll={} pitch={}".format(xyz, yaw, roll, pitch))
    
    print_eep(1.0)
    rospy.spin() 
Example #28
Source File: get_points.py    From visual_foresight with MIT License 5 votes vote down vote up
def main_baxter(limb='right'):
    import baxter_interface
    from visual_mpc.envs.robot_envs.baxter.baxter_impedance import BaxterImpedanceController
    controller = BaxterImpedanceController('baxter', True, gripper_attached='none', limb=limb)

    def print_eep(value):
        if not value:
            return
        xyz, quat = controller.get_xyz_quat()
        yaw, roll, pitch = [np.rad2deg(x) for x in controller.quat_2_euler(quat)]
        logging.getLogger('robot_logger').info("XYZ IS: {}, ROTATION IS: yaw={} roll={} pitch={}".format(xyz, yaw, roll, pitch))
    
    navigator = baxter_interface.Navigator(limb)
    navigator.button0_changed.connect(print_eep)
    rospy.spin() 
Example #29
Source File: base_env.py    From visual_foresight with MIT License 5 votes vote down vote up
def _get_obs(self):
        obs = {}
        j_angles, j_vel, eep = self._controller.get_state()
        gripper_state, force_sensor = self._controller.get_gripper_state()

        z_angle = self._controller.quat_2_euler(eep[3:])[0]

        obs['qpos'] = j_angles
        # add support for widow_x which does not have velocity readings on ja
        if j_vel is not None:
            obs['qvel'] = j_vel

        if self._previous_target_qpos is not None:
            logging.getLogger('robot_logger').debug('xy delta: {}'.format(np.linalg.norm(eep[:2] - self._previous_target_qpos[:2])))
            logging.getLogger('robot_logger').debug('target z: {}       real z: {}'.format(self._previous_target_qpos[2], eep[2]))   
            logging.getLogger('robot_logger').debug('z dif {}'.format(abs(eep[2] - self._previous_target_qpos[2])))
            logging.getLogger('robot_logger').debug('angle dif (degrees): {}'.format(abs(z_angle - self._previous_target_qpos[3]) * 180 / np.pi))
            logging.getLogger('robot_logger').debug('angle degree target {} vs real {}'.format(np.rad2deg(z_angle),
                                                             np.rad2deg(self._previous_target_qpos[3])))

        obs['state'] = self._get_state()
        if force_sensor is not None:
            obs['finger_sensors'] = force_sensor

        self._last_obs = copy.deepcopy(obs)
        obs['images'] = self.render()
        obs['high_bound'], obs['low_bound'] = copy.deepcopy(self._high_bound), copy.deepcopy(self._low_bound)

        if self._hp.opencv_tracking:
            track_desig = np.zeros((self.ncam, 1, 2), dtype=np.int64)
            for i, c in enumerate(self._cameras):
                track_desig[i] = c.get_track()
            self._desig_pix = track_desig

        if self._desig_pix is not None:
            obs['obj_image_locations'] = copy.deepcopy(self._desig_pix)
        return obs 
Example #30
Source File: polar.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_rlabel_position(self):
        """
        Returns
        -------
        float
            The theta position of the radius labels in degrees.
        """
        return np.rad2deg(self._r_label_position.get_matrix()[0, 2])