Python matplotlib.pyplot.figaspect() Examples

The following are code examples for showing how to use matplotlib.pyplot.figaspect(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: ller   Author: all-umass   File: demo.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def demo(k):
    X, t = make_swiss_roll(noise=1)

    lle = LocallyLinearEmbedding(n_components=2, n_neighbors=k)
    lle_X = lle.fit_transform(X)

    ller = LLER(n_components=2, n_neighbors=k)
    ller_X = ller.fit_transform(X, t)

    _, axes = plt.subplots(nrows=1, ncols=3, figsize=plt.figaspect(0.33))
    axes[0].set_axis_off()
    axes[0] = plt.subplot(131, projection='3d')
    axes[0].scatter(*X.T, c=t, s=50)
    axes[0].set_title('Swiss Roll')
    axes[1].scatter(*lle_X.T, c=t, s=50)
    axes[1].set_title('LLE Embedding')
    axes[2].scatter(*ller_X.T, c=t, s=50)
    axes[2].set_title('LLER Embedding')
    plt.show() 
Example 2
Project: rel_3d_pose   Author: matteorr   File: pose_plotter.py    MIT License 6 votes vote down vote up
def plot_2d_3d(self, pose_2d_x, pose_2d_y,
                         pose_3d_x, pose_3d_y, pose_3d_z, kpts_v, BLOCK=True):

        fig = plt.figure(figsize=plt.figaspect(.5))
        plt.clf()
        ax_2d = fig.add_subplot(1, 2, 1)
        self.plot_2d(pose_2d_x, pose_2d_y, kpts_v, BLOCK, ax_2d)

        ax_3d = fig.add_subplot(1, 2, 2, projection='3d')
        self.plot_3d(pose_3d_x, pose_3d_y, pose_3d_z, kpts_v, BLOCK, ax_3d)

        if BLOCK:
            plt.show()
            #plt.close()
        else:
            plt.draw()
            plt.pause(0.01) 
Example 3
Project: RiboCode   Author: xryanglab   File: metaplots.py    MIT License 5 votes vote down vote up
def lengthDistribution(length_counter,outname):
	w,h = plt.figaspect(0.4)
	plt.figure(figsize=(w,h))
	x = sorted(length_counter.keys())
	y = [length_counter[i] for i in x]
	plt.bar(x,y,width=0.95,edgecolor="white",align="center",color="#297FFF")
	plt.savefig(outname + "_readlength_distribution.pdf")
	plt.close() 
Example 4
Project: ble5-nrf52-mac   Author: tomasero   File: test_figure.py    MIT License 5 votes vote down vote up
def test_figaspect():
    w, h = plt.figaspect(np.float64(2) / np.float64(1))
    assert h / w == 2
    w, h = plt.figaspect(2)
    assert h / w == 2
    w, h = plt.figaspect(np.zeros((1, 2)))
    assert h / w == 0.5
    w, h = plt.figaspect(np.zeros((2, 2)))
    assert h / w == 1 
Example 5
Project: python3_ios   Author: holzschu   File: test_figure.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_figaspect():
    w, h = plt.figaspect(np.float64(2) / np.float64(1))
    assert h / w == 2
    w, h = plt.figaspect(2)
    assert h / w == 2
    w, h = plt.figaspect(np.zeros((1, 2)))
    assert h / w == 0.5
    w, h = plt.figaspect(np.zeros((2, 2)))
    assert h / w == 1 
Example 6
Project: pytrax   Author: PMEAL   File: __RandomWalk__.py    MIT License 5 votes vote down vote up
def _save_fig(self, figname='test.png', dpi=600):
        r'''
        Wrapper for saving figure in journal format
        '''
        plt.figaspect(1)
        plt.savefig(fname=figname, dpi=dpi, facecolor='w', edgecolor='w',
                    format='png', bbox_inches='tight', pad_inches=0.0) 
Example 7
Project: logan   Author: shashank879   File: visual_models.py    MIT License 5 votes vote down vote up
def _setup_config(self, config):
        self.ext = config['ext']
        self.lvls = config['lvls']
        self.x_len = config['x_len']
        self.z_len = config['z_len']
        self.gf_dim = config['gf_dim']
        self.df_dim = config['df_dim']
        self.sampler_batch_size = config['sampler_batch_size']
        self.activation_fn = config['activation_fn']
        self.out_activation_fn = config['out_activation_fn']
        d_bn = config['d_bn']
        g_bn = config['g_bn']
        self.lr = config['lr']
        self.optimizer = config['optimizer']
        self.loss = config['loss']
        self.grad_pen = config['grad_pen']
        self.ae_pen = config['ae_pen']
        self.gp_lambda = config['gp_lambda']
        self.ae_lambda = config['ae_lambda']

        if self.optimizer is 'adam':
            self.opt = tf.train.AdamOptimizer(learning_rate=self.lr, beta1=0.5, beta2=0.9)
        elif self.optimizer is 'rms':
            self.opt = tf.train.RMSPropOptimizer(learning_rate=self.lr)

        self.d_bn_fn = layers.batch_norm if d_bn else None
        self.g_bn_fn = layers.batch_norm if g_bn else None

        # Seaborn style
        # sns.set(style="white")
        sns.set(style="darkgrid")
        sns.set_context('paper')
        self.fig = plt.figure(figsize=plt.figaspect(1 / self.z_len))
        # ax.set_aspect('equal')
        self.sample_imgs = [] 
Example 8
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_figure.py    MIT License 5 votes vote down vote up
def test_figaspect():
    w, h = plt.figaspect(np.float64(2) / np.float64(1))
    assert h / w == 2
    w, h = plt.figaspect(2)
    assert h / w == 2
    w, h = plt.figaspect(np.zeros((1, 2)))
    assert h / w == 0.5
    w, h = plt.figaspect(np.zeros((2, 2)))
    assert h / w == 1 
Example 9
Project: SHN-based-2D-face-alignment   Author: face-alignment-group-of-ahucs   File: utils.py    MIT License 5 votes vote down vote up
def show_image(image, landmarks, box=None):
    fig = plt.figure(figsize=plt.figaspect(.5))
    ax = fig.add_subplot(1, 1, 1)
    ax.imshow(image)
    num_points = landmarks.shape[0]
    if num_points == 68:
        ax.plot(landmarks[0:17,0],landmarks[0:17,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[17:22,0],landmarks[17:22,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[22:27,0],landmarks[22:27,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[27:31,0],landmarks[27:31,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[31:36,0],landmarks[31:36,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[36:42,0],landmarks[36:42,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[42:48,0],landmarks[42:48,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[48:60,0],landmarks[48:60,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[60:68,0],landmarks[60:68,1],marker='o',markersize=4,linestyle='-',color='w',lw=2) 
    elif num_points == 98:
        ax.plot(landmarks[0:33,0],landmarks[0:33,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[33:38,0],landmarks[33:38,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[37:42,0],landmarks[37:42,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[42:46,0],landmarks[42:46,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[45:51,0],landmarks[45:51,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[51:55,0],landmarks[51:55,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[55:60,0],landmarks[55:60,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[60:65,0],landmarks[60:65,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[64:68,0],landmarks[64:68,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[68:73,0],landmarks[68:73,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[72:76,0],landmarks[72:76,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[76:83,0],landmarks[76:83,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[82:88,0],landmarks[82:88,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[88:93,0],landmarks[88:93,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[92:96,0],landmarks[92:96,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[96,0],landmarks[96,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
        ax.plot(landmarks[97,0],landmarks[97,1],marker='o',markersize=4,linestyle='-',color='w',lw=2)
    if box is not None:
        currentAxis=plt.gca()
        box = enlarge_box(box,0.05)
        xmin, ymin, xmax, ymax = box
        rect=patches.Rectangle((xmin, ymin),xmax-xmin,ymax-ymin,linewidth=2,edgecolor='r',facecolor='none')
        currentAxis.add_patch(rect)
    ax.axis('off')
    plt.show() 
Example 10
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_figure.py    MIT License 5 votes vote down vote up
def test_figaspect():
    w, h = plt.figaspect(np.float64(2) / np.float64(1))
    assert h / w == 2
    w, h = plt.figaspect(2)
    assert h / w == 2
    w, h = plt.figaspect(np.zeros((1, 2)))
    assert h / w == 0.5
    w, h = plt.figaspect(np.zeros((2, 2)))
    assert h / w == 1 
Example 11
Project: Blackjack-Tracker   Author: martinabeleda   File: test_figure.py    MIT License 5 votes vote down vote up
def test_figaspect():
    w, h = plt.figaspect(np.float64(2) / np.float64(1))
    assert h / w == 2
    w, h = plt.figaspect(2)
    assert h / w == 2
    w, h = plt.figaspect(np.zeros((1, 2)))
    assert h / w == 0.5
    w, h = plt.figaspect(np.zeros((2, 2)))
    assert h / w == 1 
Example 12
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_figure.py    GNU General Public License v3.0 5 votes vote down vote up
def test_figaspect():
    w, h = plt.figaspect(np.float64(2) / np.float64(1))
    assert h / w == 2
    w, h = plt.figaspect(2)
    assert h / w == 2
    w, h = plt.figaspect(np.zeros((1, 2)))
    assert h / w == 0.5
    w, h = plt.figaspect(np.zeros((2, 2)))
    assert h / w == 1 
Example 13
Project: scqubits   Author: scqubits   File: plotting.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def contours(x_vals, y_vals, func, contour_vals=None, aspect_ratio=None, show_colorbar=True, filename=None,
             fig_ax=None):
    """Contour plot of a 2d function `func(x,y)`.

    Parameters
    ----------
    x_vals: (ordered) list
        x values for the x-y evaluation grid
    y_vals: (ordered) list
        y values for the x-y evaluation grid
    func: function f(x,y)
        function for which contours are to be plotted
    contour_vals: list
        contour values can be specified if so desired
    aspect_ratio: float
    show_colorbar: bool
    filename: str or None
        file path and name (not including suffix)
    fig_ax: None or tuple(Figure, Axes)
        fig and ax objects for matplotlib figure addition

    Returns
    -------
    tuple(Figure, Axes)
        matplotlib objects for further editing
    """

    x_grid, y_grid = np.meshgrid(x_vals, y_vals)
    z_array = func(x_grid, y_grid)

    if fig_ax is None:
        if aspect_ratio is None:
            aspect_ratio = (y_vals[-1] - y_vals[0])/(x_vals[-1] - x_vals[0])
        w, h = plt.figaspect(aspect_ratio)
        fig, axes = plt.subplots(figsize=(w, h))
    else:
        fig, axes = fig_ax

    im = axes.contourf(x_grid, y_grid, z_array, levels=contour_vals, cmap=plt.cm.viridis, origin="lower")

    if show_colorbar:
        fig.colorbar(im, ax=axes)

    if filename:
        out_file = mplpdf.PdfPages(filename)
        out_file.savefig()
        out_file.close()

    return fig, axes 
Example 14
Project: lie_learn   Author: AMLab-Amsterdam   File: S2.py    MIT License 4 votes vote down vote up
def plot_sphere_func2(f, grid='Clenshaw-Curtis', beta=None, alpha=None, colormap='jet', fignum=0,  normalize=True):
    # TODO: update this  function now that we have changed the order of axes in f
    import matplotlib.pyplot as plt
    from matplotlib import cm, colors
    from mpl_toolkits.mplot3d import Axes3D
    import numpy as np
    from scipy.special import sph_harm

    if normalize:
        f = (f - np.min(f)) / (np.max(f) - np.min(f))

    if grid == 'Driscoll-Healy':
        b = f.shape[0] // 2
    elif grid == 'Clenshaw-Curtis':
        b = (f.shape[0] - 2) // 2
    elif grid == 'SOFT':
        b = f.shape[0] // 2
    elif grid == 'Gauss-Legendre':
        b = (f.shape[0] - 2) // 2

    if beta is None or alpha is None:
        beta, alpha = meshgrid(b=b, grid_type=grid)

    alpha = np.r_[alpha, alpha[0, :][None, :]]
    beta = np.r_[beta, beta[0, :][None, :]]
    f = np.r_[f, f[0, :][None, :]]

    x = np.sin(beta) * np.cos(alpha)
    y = np.sin(beta) * np.sin(alpha)
    z = np.cos(beta)

    # m, l = 2, 3
    # Calculate the spherical harmonic Y(l,m) and normalize to [0,1]
    # fcolors = sph_harm(m, l, beta, alpha).real
    # fmax, fmin = fcolors.max(), fcolors.min()
    # fcolors = (fcolors - fmin) / (fmax - fmin)
    print(x.shape, f.shape)

    if f.ndim == 2:
        f = cm.gray(f)
        print('2')

    # Set the aspect ratio to 1 so our sphere looks spherical
    fig = plt.figure(figsize=plt.figaspect(1.))
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=f ) # cm.gray(f))
    # Turn off the axis planes
    ax.set_axis_off()
    plt.show() 
Example 15
Project: DCASE2019_task3   Author: andresperezlopez   File: visualize_output.py    MIT License 4 votes vote down vote up
def visualize_output(pred_path, ref_dir, aud_dir, params):

    title = params['preset_string']

    # fixed hoplength of 0.02 seconds for evaluation
    hop_s = 0.02

    pred_files = [f for f in os.listdir(pred_path) if not f.startswith('.')]
    for pred_file in pred_files:
        print(pred_file)

        # check that gt file exists

        # load the predicted output format
        pred = os.path.join(pred_path, pred_file)
        pred_dict = evaluation_metrics.load_output_format_file(pred)

        # load the reference output format
        feat_cls = cls_feature_class.FeatureClass()
        ref_filename = os.path.basename(pred)
        ref_path = os.path.join(ref_dir, ref_filename)

        if not os.path.exists(ref_path):
            print('Metadata file not found: ' + ref_path)
        else:
            ref_desc_dict = feat_cls.read_desc_file(ref_path, in_sec=True)
            ref_dict = evaluation_metrics.description_file_to_output_format(ref_desc_dict, feat_cls.get_classes(), hop_s)

            pred_data = collect_classwise_data(pred_dict)
            ref_data = collect_classwise_data(ref_dict)

            nb_classes = len(feat_cls.get_classes())

            # load the audio and extract spectrogram
            # ref_filename = os.path.basename(pred).replace('.csv', '.wav')
            # audio, fs = feat_cls._load_audio(os.path.join(aud_dir, ref_filename))
            # stft = np.abs(np.squeeze(feat_cls._spectrogram(audio[:, :1])))
            # stft = librosa.amplitude_to_db(stft, ref=np.max)

            if params['quick_test']:
                xmax = params['quick_test_file_duration']
            else:
                xmax = 60

            plot.figure(figsize=plot.figaspect(1 / 2.))
            plot.suptitle(title + ' ' + ref_filename)
            gs = gridspec.GridSpec(2, 2)
            # ax0 = plot.subplot(gs[0, :]), librosa.display.specshow(stft.T, sr=fs, x_axis='time', y_axis='linear')
            # ax1 = plot.subplot(gs[1, :2]), plot_func(ref_data, hop_s, ind=1), plot.ylim([-1, nb_classes + 1]), plot.title('SED reference')
            # ax2 = plot.subplot(gs[1, 2:]), plot_func(pred_data, hop_s, ind=1), plot.ylim([-1, nb_classes + 1]), plot.title('SED predicted')
            ax3 = plot.subplot(gs[0, 0]), plot_func(ref_data, hop_s, ind=2), plot.ylim([-190, 190]), plot.title('Azimuth DOA reference'), plot.xlim(0, xmax)
            ax4 = plot.subplot(gs[0, 1]), plot_func(pred_data, hop_s, ind=2), plot.ylim([-190, 190]), plot.title('Azimuth DOA predicted'), plot.xlim(0, xmax)
            ax5 = plot.subplot(gs[1, 0]), plot_func(ref_data, hop_s, ind=3, plot_x_ax=True), plot.ylim([-50, 50]), plot.title('Elevation DOA reference'), plot.xlim(0, xmax)
            ax6 = plot.subplot(gs[1, 1]), plot_func(pred_data, hop_s, ind=3, plot_x_ax=True), plot.ylim([-50, 50]), plot.title('Elevation DOA predicted'), plot.xlim(0, xmax)
            # ax_lst = [ax0, ax1, ax2, ax3, ax4, ax5, ax6]
            ax_lst = [ax3, ax4, ax5, ax6]
            # if params['quick_test']: plot.xlim(0,params['quick_test_file_duration'])
            plot.show() 
Example 16
Project: work-in-horizon   Author: dafuny   File: visualize.py    MIT License 4 votes vote down vote up
def draw_landmarks():
    filelists = 'test.data/AFLW2000-3D_crop.list'
    root = 'AFLW-2000-3D/'
    fns = open(filelists).read().strip().split('\n')
    params = _load('res/params_aflw2000.npy')

    for i in range(2000):
        plt.close()
        img_fp = osp.join(root, fns[i])
        img = io.imread(img_fp)
        lms = reconstruct_vertex(params[i], dense=False)
        lms = convert_to_ori(lms, i)

        # print(lms.shape)
        fig = plt.figure(figsize=plt.figaspect(.5))
        # fig = plt.figure(figsize=(8, 4))
        ax = fig.add_subplot(1, 2, 1)
        ax.imshow(img)

        alpha = 0.8
        markersize = 4
        lw = 1.5
        color = 'w'
        markeredgecolor = 'black'

        nums = [0, 17, 22, 27, 31, 36, 42, 48, 60, 68]
        for ind in range(len(nums) - 1):
            l, r = nums[ind], nums[ind + 1]
            ax.plot(lms[0, l:r], lms[1, l:r], color=color, lw=lw, alpha=alpha - 0.1)

            ax.plot(lms[0, l:r], lms[1, l:r], marker='o', linestyle='None', markersize=markersize, color=color,
                    markeredgecolor=markeredgecolor, alpha=alpha)

        ax.axis('off')

        # 3D
        ax = fig.add_subplot(1, 2, 2, projection='3d')
        lms[1] = img.shape[1] - lms[1]
        lms[2] = -lms[2]

        # print(lms)
        ax.scatter(lms[0], lms[2], lms[1], c="cyan", alpha=1.0, edgecolor='b')

        for ind in range(len(nums) - 1):
            l, r = nums[ind], nums[ind + 1]
            ax.plot3D(lms[0, l:r], lms[2, l:r], lms[1, l:r], color='blue')

        ax.view_init(elev=5., azim=-95)
        # ax.set_xlabel('x')
        # ax.set_ylabel('y')
        # ax.set_zlabel('z')

        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.set_zticklabels([])

        plt.tight_layout()
        # plt.show()

        wfp = f'res/AFLW-2000-3D/{osp.basename(img_fp)}'
        plt.savefig(wfp, dpi=200) 
Example 17
Project: semantic-segmentation   Author: singnet   File: common.py    MIT License 4 votes vote down vote up
def segment_image(img, visualize=False):
    import tensorflow as tf
    from keras import backend as K
    tf_config = tf.ConfigProto()
    tf_config.gpu_options.allow_growth = True
    sess = tf.Session(config=tf_config)
    K.set_session(sess)

    init()

    model = load_model()

    # Run detection
    results = model.detect([img], verbose=1)
    r = results[0]

    print("Model inference completed")

    # We need to copy/serialise some of this data otherwise
    # it will be lost when this spawned process finishes
    if visualize:
        print("Visualisation requested")
        from mrcnn import visualize
        # Visualize results
        fig, ax = plt.subplots(1, figsize=plt.figaspect(img))
        ax.set_axis_off()
        fig.subplots_adjust(0, 0, 1, 1)

        visualize.display_instances(img, r['rois'], r['masks'], r['class_ids'],
                                    class_names, r['scores'], ax=ax)
        print("Saving visualise result")
        viz_img_buff = fig2png_buffer(fig)

        r["resultImage"] = viz_img_buff.getvalue()

    r['rois'] = r['rois'].tolist()
    r['class_ids'] = r['class_ids'].tolist()
    r['class_names'] = [class_names[i] for i in r['class_ids']]
    r['known_classes'] = class_names
    r['scores'] = r['scores'].tolist()
    masks = r['masks']
    r['masks'] = []
    for i in range(masks.shape[2]):
        # convert mask arrays into gray-scale pngs, then base64 encode them
        buff = io.BytesIO()
        # skimage annoying spams warnings when the mask is below a certain pixel area
        # proportional to the image size.
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            skimage.io.imsave(buff, img_as_uint(masks[:, :, i]))
        r['masks'].append(buff.getvalue())
    
    del model
    sess.close()
    return r 
Example 18
Project: 3DDFA   Author: cleardusk   File: visualize.py    MIT License 4 votes vote down vote up
def draw_landmarks():
    filelists = 'test.data/AFLW2000-3D_crop.list'
    root = 'AFLW-2000-3D/'
    fns = open(filelists).read().strip().split('\n')
    params = _load('res/params_aflw2000.npy')

    for i in range(2000):
        plt.close()
        img_fp = osp.join(root, fns[i])
        img = io.imread(img_fp)
        lms = reconstruct_vertex(params[i], dense=False)
        lms = convert_to_ori(lms, i)

        # print(lms.shape)
        fig = plt.figure(figsize=plt.figaspect(.5))
        # fig = plt.figure(figsize=(8, 4))
        ax = fig.add_subplot(1, 2, 1)
        ax.imshow(img)

        alpha = 0.8
        markersize = 4
        lw = 1.5
        color = 'w'
        markeredgecolor = 'black'

        nums = [0, 17, 22, 27, 31, 36, 42, 48, 60, 68]
        for ind in range(len(nums) - 1):
            l, r = nums[ind], nums[ind + 1]
            ax.plot(lms[0, l:r], lms[1, l:r], color=color, lw=lw, alpha=alpha - 0.1)

            ax.plot(lms[0, l:r], lms[1, l:r], marker='o', linestyle='None', markersize=markersize, color=color,
                    markeredgecolor=markeredgecolor, alpha=alpha)

        ax.axis('off')

        # 3D
        ax = fig.add_subplot(1, 2, 2, projection='3d')
        lms[1] = img.shape[1] - lms[1]
        lms[2] = -lms[2]

        # print(lms)
        ax.scatter(lms[0], lms[2], lms[1], c="cyan", alpha=1.0, edgecolor='b')

        for ind in range(len(nums) - 1):
            l, r = nums[ind], nums[ind + 1]
            ax.plot3D(lms[0, l:r], lms[2, l:r], lms[1, l:r], color='blue')

        ax.view_init(elev=5., azim=-95)
        # ax.set_xlabel('x')
        # ax.set_ylabel('y')
        # ax.set_zlabel('z')

        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.set_zticklabels([])

        plt.tight_layout()
        # plt.show()

        wfp = f'res/AFLW-2000-3D/{osp.basename(img_fp)}'
        plt.savefig(wfp, dpi=200) 
Example 19
Project: vehicle_dynamics_Blender   Author: physycom   File: plot_utils.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def plot_vectors(vectors_list, label_list=None, title=None, tri_dim=True, horiz=None):
    """ Plot 3xn numpy array in 2d and 3d

    plt.show() blocking call must be called to show all plot created whit this function

    :param vectors_list: list of 3xn numpy array
    :param label_list: optional list of custom 3d plot label (matching 1-1 with vectors-list)
    :param title: string figure title
    :param tri_dim: boolean toggle 3d plot
    :param horiz: units for x axis in 2d plot
    :return figure
    """

    axis_labels = ['x', 'y', 'z']
    label_list = label_list if (label_list is not None) else [" "] * len(vectors_list)
    if (tri_dim):
        fig = plt.figure(figsize=plt.figaspect(0.5))
        axes_2d = fig.add_subplot(1, 2, 1)
        axes_3d = fig.add_subplot(1, 2, 2, projection='3d')
    else:
        fig = plt.figure()
        axes_2d = fig.add_subplot(1, 1, 1)
    if (title):
        fig.suptitle(title)
    for vectors, label in zip(vectors_list, label_list):
        # if vector is multidimensional
        if (vectors.ndim > 1):
            if (horiz is not None):
                [axes_2d.plot(horiz, ri, label=axis_labels[i] + " " + label) for i, ri in enumerate(vectors)]
            else:
                [axes_2d.plot(ri, label=axis_labels[i] + " " + label) for i, ri in enumerate(vectors)]
            if (tri_dim):
                axes_3d.plot(*vectors, label=label)
                axes_3d.set_xlabel('x')
                axes_3d.set_ylabel('y')
                axes_3d.set_zlabel('z')
        else:
            if (horiz is not None):
                axes_2d.plot(horiz, vectors, label=label)
            else:
                axes_2d.plot(vectors, label=label)
    axes_2d.legend()
    if (tri_dim):
        axes_3d.legend()

    return fig 
Example 20
Project: rel_3d_pose   Author: matteorr   File: pose_plotter.py    MIT License 4 votes vote down vote up
def plot_2d(self, pose_2d_x, pose_2d_y, kpts_v, BLOCK=True, ax=None):
        if ax is None:
            fig = plt.figure(figsize=plt.figaspect(1.))
            plt.clf()
            self.ax = fig.add_subplot(1, 1, 1)
        else:
            self.ax = ax
        self._plot_skeleton(kpts_v, pose_2d_x, pose_2d_y)

        if self.ax_2d_lims:
            self.ax.set_xlim(self.x_start_2d, self.x_end_2d)
            self.ax.set_ylim(self.y_start_2d, self.y_end_2d)
        else:
            # uses the keypoint visibility flags to select the max and min
            # across the x and y dimensions for setting the plot axis limits
            max_x = np.max(pose_2d_x[kpts_v.astype(np.bool)])
            min_x = np.min(pose_2d_x[kpts_v.astype(np.bool)])
            max_y = np.max(pose_2d_y[kpts_v.astype(np.bool)])
            min_y = np.min(pose_2d_y[kpts_v.astype(np.bool)])

            w  = max_x - min_x
            h  = max_y - min_y

            cx = int(min_x + w/2.)
            cy = int(min_y + h/2.)

            ENLARGE = 0.
            bbox = [cx - (w*(1+ENLARGE))/2.,
                    cy - (h*(1+ENLARGE))/2., w*(1+ENLARGE), h*(1+ENLARGE)]
            slack = int(bbox[2]/2.) if w > h else int(bbox[3]/2.)

            x_start = cx - slack
            x_end   = cx + slack
            y_start = cy - slack
            y_end   = cy + slack
            self.ax.set_xlim(x_start, x_end)
            self.ax.set_ylim(y_start, y_end)

        self.ax.invert_yaxis()
        # self.ax.set_xlabel("x")
        # self.ax.set_ylabel("y")

        if ax is None:
            if BLOCK:
                plt.show()
                #plt.close()
            else:
                plt.draw()
                plt.pause(0.01) 
Example 21
Project: rel_3d_pose   Author: matteorr   File: pose_plotter.py    MIT License 4 votes vote down vote up
def plot_3d(self, pose_3d_x, pose_3d_y, pose_3d_z, kpts_v, BLOCK=True, ax=None):
        if ax is None:
            fig = plt.figure(figsize=plt.figaspect(1.))
            plt.clf()
            self.ax = fig.add_subplot(1, 1, 1, projection='3d')
        else:
            self.ax = ax

        self._plot_skeleton(kpts_v, pose_3d_x, pose_3d_y, pose_3d_z)

        if self.ax_3d_lims:
            self.ax.set_xlim(self.x_start_3d, self.x_end_3d)
            self.ax.set_ylim(self.z_start_3d, self.z_end_3d)
            self.ax.set_zlim(self.y_start_3d, self.y_end_3d)
        else:
            max_range = np.array([pose_3d_x.max()-pose_3d_x.min(),
                          pose_3d_y.max()-pose_3d_y.min(),
                          pose_3d_z.max()-pose_3d_z.min()]).max() / 2.0
            mid_x = (pose_3d_x.max()+pose_3d_x.min()) * 0.5
            mid_y = (pose_3d_y.max()+pose_3d_y.min()) * 0.5
            mid_z = (pose_3d_z.max()+pose_3d_z.min()) * 0.5

            x_start = mid_x - max_range
            x_end   = mid_x + max_range
            y_start = mid_y - max_range
            y_end   = mid_y + max_range
            z_start = mid_z - max_range
            z_end   = mid_z + max_range
            self.ax.set_xlim(x_start, x_end)
            self.ax.set_ylim(z_start, z_end)
            self.ax.set_zlim(y_start, y_end)

        self.ax.invert_zaxis()
        # self.ax.set_xlabel("x")
        # self.ax.set_ylabel("z")
        # self.ax.set_zlabel("y")

        if ax is None:
            if BLOCK:
                plt.show()
                #plt.close()
            else:
                plt.draw()
                plt.pause(0.01) 
Example 22
Project: spaudiopy   Author: chris-hld   File: plots.py    MIT License 4 votes vote down vote up
def subplot_sph_coeffs(F_l, SH_type=None, azi_steps=5, el_steps=3, title=None):
    """Plot spherical harmonics coefficients as function on the sphere."""
    N_plots = len(F_l)
    azi_steps = np.deg2rad(azi_steps)
    el_steps = np.deg2rad(el_steps)
    phi_plot, theta_plot = np.meshgrid(np.arange(0., 2 * np.pi + azi_steps,
                                                 azi_steps),
                                       np.arange(10e-3, np.pi + el_steps,
                                                 el_steps))

    fig = plt.figure(figsize=plt.figaspect(1 / N_plots))
    ax_l = []
    for i_p, ff in enumerate(F_l):
        F_nm = utils.asarray_1d(ff)
        F_nm = F_nm[:, np.newaxis]
        if SH_type is None:
            SH_type = 'complex' if np.iscomplexobj(F_nm) else 'real'

        f_plot = sph.inverse_sht(F_nm, phi_plot.ravel(), theta_plot.ravel(),
                                 SH_type)
        f_r = np.abs(f_plot)
        f_ang = np.angle(f_plot)

        x_plot, y_plot, z_plot = utils.sph2cart(phi_plot.ravel(),
                                                theta_plot.ravel(),
                                                f_r.ravel())

        ax = fig.add_subplot(1, N_plots, i_p + 1, projection='3d')

        m = cm.ScalarMappable(cmap=cm.hsv,
                              norm=colors.Normalize(vmin=-np.pi, vmax=np.pi))
        m.set_array(f_ang)
        c = m.to_rgba(f_ang.reshape(phi_plot.shape))

        ax.plot_surface(x_plot.reshape(phi_plot.shape),
                        y_plot.reshape(phi_plot.shape),
                        z_plot.reshape(phi_plot.shape),
                        facecolors=c,
                        edgecolor='none', linewidth=0.06, alpha=0.68,
                        shade=True)
        ax.set_xlim(-1, 1)
        ax.set_ylim(-1, 1)
        ax.set_zlim(-1, 1)

        if i_p == 0:
            ax.set_xlabel('x')
            ax.set_ylabel('y')
            ax.set_zlabel('z')

        plt.grid(True)
        ax.view_init(25, 230)
        if title is not None:
            ax.set_title(title[i_p])
        ax.set_aspect('equal')
        ax_l.append(ax)

    cbar = plt.colorbar(m, shrink=0.3, aspect=8,
                        ax=ax_l)
    cbar.set_ticks([-np.pi, 0, np.pi])
    cbar.set_ticklabels([r'$-\pi$', r'$0$', r'$\pi$'])