def test_scalebar_loc(scalebar):
    assert scalebar.get_loc() is None
    assert scalebar.loc is None

    scalebar.set_location("upper right")
    assert scalebar.get_loc() == 1
    assert scalebar.loc == 1

    scalebar.location = "lower left"
    assert scalebar.get_loc() == 3
    assert scalebar.loc == 3

    scalebar.set_loc("lower right")
    assert scalebar.get_loc() == 4
    assert scalebar.loc == 4

    scalebar.location = "upper left"
    assert scalebar.get_loc() == 2
    assert scalebar.loc == 2

    with pytest.raises(ValueError):
        ScaleBar(1.0, loc="upper right", location="upper left")

    with pytest.raises(ValueError):
        ScaleBar(1.0, loc="upper right", location=2)
def get_scalebar(px, unit, sb_settings):
    if '1/' in unit:
        # px = px*10**(-9)
        scalebar = ScaleBar(px, unit, SI_LENGTH_RECIPROCAL,
                            **sb_settings)
    else:
        scalebar = ScaleBar(px, unit, **sb_settings)
    return scalebar
Beispiel #3
0
def addscale(img,
             imgdata,
             outfile,
             scale_value='auto'):  # Add Scalebar on TEM  Image

    # extract scale bar and scale unit
    scale_x = imgdata['scale'][0]
    scale_y = imgdata['scale'][1]
    scale_ratio = scale_y / scale_x
    scale_unit = imgdata['scale_unit']
    dimension = imgdata['dimension (px,px)']

    # image prepration for new image
    imga = np.array(img)
    color = sb_color(imga)  # color of scale bar
    dpi = 1000

    fig = plt.figure(figsize=(dimension[0] / dpi, dimension[1] / dpi),
                     frameon=False)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.axis('off')
    location = 'lower left'
    frameon = False

    # find optimum scale bar value
    scvs = np.array([1, 2, 5, 10, 20, 50, 100, 200,
                     500])  # scale bar candidates
    scvs_px = scvs / imgdata['scale'][0]
    rel_len = imgdata['image size (px,px)'][
        1] * 0.2  # scale bar should close to 20% of image width
    scale_value = scvs[np.argmin(abs(scvs_px - rel_len))]
    print('scale_value= {}'.format(scale_value))

    if scale_unit[0] == '1':  # reciporcal space, such as 1/nm
        scalebar = ScaleBar(scale_x,
                            scale_unit,
                            SI_LENGTH_RECIPROCAL,
                            location=location,
                            frameon=frameon,
                            color=color,
                            fixed_value=scale_value)
    else:  # real space
        scalebar = ScaleBar(scale_x,
                            scale_unit,
                            location=location,
                            frameon=frameon,
                            color=color,
                            fixed_value=scale_value)

    plt.imshow(imga)
    plt.gca().add_artist(scalebar)
    plt.savefig(outfile, dpi=dpi)

    return outfile
Beispiel #4
0
def plotRxDConcentration(speciesLabel,
                         regionLabel,
                         plane='xy',
                         figSize=(5, 10),
                         fontSize=10,
                         scalebar=False,
                         title=True,
                         showFig=True,
                         saveFig=True):

    from .. import sim

    # set font size
    plt.rcParams.update({'font.size': fontSize})

    species = sim.net.rxd['species'][speciesLabel]['hObj']
    region = sim.net.rxd['regions'][regionLabel]['hObj']
    plane2mean = {'xz': 1, 'xy': 2}

    fig = plt.figure(figsize=figSize)
    plt.imshow(species[region].states3d[:].mean(plane2mean[plane]).T,
               interpolation='nearest',
               origin='upper')  #  extent=k[extracellular].extent('xy')

    ax = plt.gca()
    if scalebar:
        ax.xaxis.set_visible(False)
        ax.yaxis.set_visible(False)
        sb = ScaleBar(1e-6)
        sb.location = 'lower left'
        ax.add_artist(sb)

    plt.colorbar(label='[' + species.name + '] (mM)')
    plt.xlabel(plane[0] + ' location (um)')
    plt.ylabel(plane[1] + ' location (um)')
    if title:
        plt.title('RxD: ' + species.name + ' concentration')
    plt.tight_layout()

    # show fig
    if showFig: _showFigure()

    # save figure
    if saveFig:
        if isinstance(saveFig, basestring):
            filename = saveFig
        else:
            filename = sim.cfg.filename + '_rxd_concentration.png'
        plt.savefig(filename)

    return fig, {'data': species[region].states3d[:].mean(plane2mean[plane])}
Beispiel #5
0
    def add_scale(self, verbose=False):
        """Add a scale to the top-right corner of the cropped image."""
        if verbose:
            print('Adding a scale bar..')

        for img in self.edited_image_list:
            scalebar = ScaleBar(img.mm_to_px)
            # Prepare a figure without axes and calculate figure sizes
            fig = plt.figure()
            ax = plt.subplot(1, 1, 1)
            plt.axis('off', frameon=False)

            # Add image and scale
            ax.imshow(img.image)
            ax.add_artist(scalebar)

            # Save the figure without borders to a temporary file
            temp_file = os.path.join(tempfile.gettempdir(), 'temp.png')
            extent = ax.get_window_extent().transformed(
                fig.dpi_scale_trans.inverted())
            fig.savefig(temp_file, bbox_inches=extent, dpi=600)
            plt.close()

            # Reload the temporary file as image object and delete it
            img.image = io.imread(temp_file)
            os.remove(temp_file)

        if verbose:
            print('Scale bar added.')
Beispiel #6
0
    def add_scalebar(self):
        """
        Display a scale bar in a matplotlib figure
        """
        
        controller = self.controller
        
        if controller.barON.get():
            
            try:
                
                if self.imgfile.dxyz is not None:
                    scalebar = ScaleBar(self.imgfile.dxyz[0], units = self.imgfile.unit,
                                        frameon='False', color='w', location='lower right', 
                                        box_color='k', box_alpha='0')  
                    # 1 pixel = metadata info
                    self.ax.add_artist(scalebar)
                    controller.canvas.draw()

                    if controller.roiON.get():
                        self.processed.roi_selector()
                    
            except AttributeError:
                pass
        else:
            
            try:
                
                if self.imgfile.dxyz is not None:
                    self.ax.artists.clear()
                    self.fig.canvas.draw()
            
            except AttributeError:
                pass
Beispiel #7
0
    def __init__(self,
                 image,
                 axis,
                 colourbar_axis=None,
                 cmap=plt.get_cmap('gray'),
                 filepath=os.getcwd(),
                 polygoncallback=None):
        '''For plotting Image as an image
		Input a 2D array to plot as an image, and an axis to plot the image on
		Optional arguments: define an axis to put a colourbar in, define the filepath to save images to'''
        self.axis = axis
        self.colourbar_axis = colourbar_axis
        self.cmap = cmap
        self.Image = image
        self.axis.set_axis_off()
        self.filepath = filepath
        self.PlottedImage = self.axis.imshow(self.Image.data,
                                             cmap=self.cmap,
                                             interpolation='none')
        if self.colourbar_axis:
            self.cbar = self.AddColourbar()
        if image.calibration != 0:
            self.scalebar = ScaleBar(self.Image.calibration)
            self.scalebar.box_alpha = 0.5
            self.axis.add_artist(self.scalebar)
        if polygoncallback:
            self.polygoncallback = polygoncallback
        else:
            self.polygoncallback = self.keyboard_press
        self.PolygonGroups = PolygonGrouper.PolygonGroupManager(self.axis)
        self.Lines = LineDraw.LineDraw(self.axis)
        self.canvas = self.axis.figure.canvas
        self.connect()
        self.creator = None
        self.mover = None
    def SaveMovieFrame(self,frame,roi_path_dict={},vmin=0,suffix='raw'):
        if suffix=='raw':
            self.raw_frame_string = os.path.join(self.save_direct,
                                    "frame%04d"%(self.ts)+"_raw.png")
            save_string = self.raw_frame_string
        elif suffix=='shifted':
            self.shifted_frame_string = os.path.join(self.save_direct,
                                        "frame%04d"%(self.ts)+"_shifted.png")
            save_string = self.shifted_frame_string
        plt.figure(figsize=(6.,6.))
        ax = plt.subplot(111)
        ax.imshow(frame,vmin=vmin)
        ax.plot(self.first_nuc_points[:,1],self.first_nuc_points[:,0],color='red',linewidth=1.25)
        i=0
        for key in roi_path_dict:
            this_roi_path = roi_path_dict[key]
            this_patch = patches.PathPatch(this_roi_path,facecolor='none',linewidth=1.0,edgecolor='white')
            i+=1
            ax.add_patch(this_patch)

        scalebar = ScaleBar(self.pix_res,'um',location=4)
        plt.gca().add_artist(scalebar)
        plt.tight_layout()
        plt.savefig(save_string,format='png',dpi=300)
        
        plt.close('all')
Beispiel #9
0
    def plot(self, save=False):
        fig, ax = plt.subplots(1, 2, figsize=(14, 6))

        ax[0].imshow(self.image)
        ax[0].set_title('Imagen original', fontsize=14)
        ax[0].add_artist(ScaleBar(self.pixel_height, 'm'))  # Barra de escala

        ax[1].imshow(self.transformed.mean(3))
        ax[1].set_title('Imagen final', fontsize=14)
        ax[1].add_artist(ScaleBar(self.pixel_height / self.magnification,
                                  'm'))  # Barra de escala

        if save:
            fig.savefig(os.path.join('outputs', self.output_name))

        plt.show(block=True)
Beispiel #10
0
 def export_data(self, event):
     if event.inaxes == self.fig_image_parameter[7].ax:
         print('export')
         #'''Save image respecting the number of pixels of the origin image'''
         #imsave('image_array.png', self.image_data)
         #'''Save image without respecting the number of pixels of the origin image'''
         plt.ioff()
         fig_export = plt.figure(figsize=(10, 7), dpi=100)
         ax_fig_export = fig_export.add_subplot(1, 1, 1)
         image_fig_export = ax_fig_export.imshow(self.image_data,
                                                 cmap=self.cmap,
                                                 vmin=self.cmin,
                                                 vmax=self.cmax)
         ax_fig_export.set_axis_off()
         if self.state_scalebar == 1:
             ax_fig_export.add_artist(ScaleBar(self.cal * 10**-9))
             fig_export.canvas.draw()
         if self.line_prof is not None:
             np.savetxt('line_profile', self.profile)
         fig_export.colorbar(image_fig_export)
         fig_export.savefig('image.png')
         print('Image saved')
         status_export_raw = 1
         if status_export_raw == 1:
             np.savetxt('image_raw', self.image_data, delimiter=',')
             print('Raw data extracted')
         plt.close(fig_export)
Beispiel #11
0
    def plotHeatGraph(self, sol, post=None, name="", vmax=None, cmap="Reds", objective=None):

        mx=int(np.max(self.data['x']))
        my=int(np.max(self.data['y']))

        color = ['black',(0,0,0,0)]
        cmapm = colors.ListedColormap(color)
        bounds=[-1,0]
        norm = colors.BoundaryNorm(bounds, cmapm.N)

        gridmap = [[0 for x in range(mx+1)] for y in range(my+1)]
        grid = [[0 for x in range(mx+1)] for y in range(my+1)]
        i=0
        for index, row in self.data.iterrows():
            if i == self.source:
                sy=int(row['y'])
                sx=int(row['x'])
            gridmap[int(row['y'])][int(row['x'])]=1

            grid[int(row['y'])][int(row['x'])]=sol[i]


            i+=1
        #np.invert(gridmap)
        gridmap = np.ma.masked_where(gridmap ==1, gridmap)
        if vmax == None:
            a = plt.imshow(np.flipud(grid), interpolation='none', cmap=cmap, extent=[0,mx+1,0,my+1])
        else:
            a = plt.imshow(np.flipud(grid), interpolation='none', cmap=cmap, extent=[0,mx+1,0,my+1], vmin=0, vmax=vmax)
        if np.min(gridmap) == 0:
            h = plt.imshow(np.flipud(gridmap), interpolation='none', cmap=cmapm, extent=[0,mx+1,0,my+1])
        #plt.set(h, 'AlphaData', gridmap)

        plt.colorbar(a)
        plt.xticks(np.arange(0,mx+1))
        plt.yticks(np.arange(0,my+1))
        plt.grid(ls='solid')
        if not post == None:
            if plot_title:
                if objective:
                    plt.title("%s: Patrol Effort, Objective: %f" %(name, objective))
                else:
                    plt.title("Patrol Effort with Post %d %s" %(post, name))

                # plt.xticks(np.arange(0,mx+1),[self.min_xval+self.resolution*i for i in range(mx+1)], rotation=60)
                # plt.xlabel("x", fontsize=12)
                # plt.yticks(np.arange(0,my+1),[self.min_yval+self.resolution*i for i in range(my+1)])
                # plt.ylabel("y", fontsize=12)

            scalebar = ScaleBar(dx=self.resolution, units='m', fixed_value=1, fixed_units='km', location='lower left') # 1 km or 200 m or 500m
            plt.gca().add_artist(scalebar)
            # plt.xticks(fontsize=6)
            # plt.yticks(fontsize=6)
            plt.plot([sx+0.5], [sy+0.5], marker='o', markersize=5, color="blue")

            plt.savefig(self.datafolder + "patrol_effort_map_post_%d_%s.png" % (post, name))
            plt.close()
            #plt.show()
        else:
            plt.show()
            def roadRight():
                x2 = []
                y2 = []
                s1 = v1.get()
                s2 = v2.get()
                s3 = v3.get()
                s4 = v4.get()
                remarks = [s1, s2, s3, s4]
                with open('csvfile1.txt', 'r') as csvfile:
                    plots = csv.reader(csvfile, delimiter=',')

                    for row in plots:
                        for i in range(0, 4):
                            if row[3] == remarks[i]:
                                x2.append(float(row[0]))
                                y2.append(float(row[1]))
                print(x2, y2)

                plt.plot(x2, y2)

                scalebar = ScaleBar(0.02)  # 1 pixel = 100 meter
                plt.gca().add_artist(scalebar)
                plt.legend(plt.plot(x2, y2), ["Road Right"], loc='lower right')
                plt.axis('off')
                plt.show()
def verifySegmentationBF(BFimage: np.ndarray, rRegion: np.ndarray,
                         sobelMasked: np.ndarray, imThresh: np.ndarray,
                         PATH: str, m: int, t: int, label: int):

    if not os.path.exists(os.path.join(PATH, str(m))):
        os.makedirs(os.path.join(PATH, str(m)))
    savePath = os.path.join(PATH, str(m))

    fname = f"{int(m):02d}t{int(t):03d}.jpeg"

    fig, ax = plt.subplots(1, 3, figsize=(10, 10))

    plt.imshow(BFimage, cmap="gray", origin="lower")

    ax[0].imshow(BFimage, cmap="gray", origin="lower")
    ax[0].axis("off")

    ax[1].imshow(imThresh, cmap="viridis", origin="lower")
    ax[1].axis("off")

    ax[2].imshow(BFimage, cmap="gray", origin="lower")
    ax[2].imshow(rRegion, alpha=0.3, origin="lower")
    ax[2].axis("off")

    scalebar = ScaleBar(0.33, units="um")
    plt.gca().add_artist(scalebar)
    plt.savefig(os.path.join(savePath, fname))
    plt.close(fig)

    return
Beispiel #14
0
def plot_image_to_file(d, title, legend=None):
    PLOT_LOCK.acquire()

    fig = plt.figure(constrained_layout=False, figsize=(15, 11.28), dpi=100)
    ax = fig.add_subplot()
    #ax.set_title(title, {'fontsize' :28})
    ax.set_axis_off()
    img = ax.imshow(d)
    scalebar = ScaleBar(35, location=3, box_color='white') 
    plt.gca().add_artist(scalebar)

    ax_img = fig.add_axes([0.15, 0.75, 0.21, 0.2], anchor='NW')
    ax_img.imshow(te_logo)
    ax_img.axis('off')

    if legend:
        ax_legend = fig.add_axes([0.63, 0.02, 0.22, 0.2], anchor='SE')
        ax_legend.imshow(legend)
        ax_legend.axis('off')

    plt.tight_layout()
    f = tempfile.NamedTemporaryFile(suffix='.png').name
    plt.savefig(f, bbox_inches='tight')

    PLOT_LOCK.release()

    return f
def go_plot(p_bbox, p_raster_data, p_raster_data_extent, family, species,
            points, p_xticks, p_jticks, p_xlabels, p_ylabels):
    f, ax = plt.subplots(figsize=(7, 7))
    ep.plot_rgb(
        p_raster_data.values,
        rgb=[0, 1, 2],
        ax=ax,
        #title="test Burundi",
        extent=p_raster_data_extent)

    p_points = geopandas.GeoDataFrame(geometry=points)
    p_points.set_crs(epsg=3857, inplace=True)
    p_points.plot(ax=ax, zorder=20, color="black")

    ax.set_xticks(p_xticks)
    ax.set_yticks(p_jticks)
    ax.set_xticklabels(p_xlabels)
    ax.set_yticklabels(p_ylabels)
    ax.set_xlim(p_bbox[0], p_bbox[1])
    ax.set_ylim(p_bbox[2], p_bbox[3])
    ax.add_artist(ScaleBar(dx=1, box_alpha=0.1, location='lower left'))
    print(family)
    print(species)
    #ax.set_title(family+ " - "+ species)
    plt.savefig(output_map + family + "_" + species + ".png", dpi=300)
    plt.close('all')
Beispiel #16
0
def show_threeview(nt, fig=None, **kwargs):
    """
    Plots all three two-dimensional projections of the neuron in nt.
    :param nt: NeuronTree, neuron to be plotted
    :param fig: (optional) pass the figure handle from outside if you want more control.
    :param kwargs: arguments that can be passed to the NeuronTree.draw_2D() function.
    """

    if not fig:
        fig = plt.figure(figsize=(16, 16))

    ax1 = plt.subplot2grid((4, 4), (0, 1), rowspan=3, colspan=3)
    ax2 = plt.subplot2grid((4, 4), (0, 0), rowspan=3, colspan=1)
    ax3 = plt.subplot2grid((4, 4), (3, 1), rowspan=1, colspan=3)
    ax4 = plt.subplot2grid((4, 4), (3, 0), rowspan=1, colspan=1)

    nt.draw_2D(fig, ax=ax2, projection='zy', **kwargs)
    nt.draw_2D(fig, ax=ax3, projection='xz', **kwargs)
    nt.draw_2D(fig, ax=ax1, projection='xy', **kwargs)

    scalebar = ScaleBar(1, units='um', location='lower left', box_alpha=0)
    ax1.add_artist(scalebar)
    ax4.axis('off')
    ax1.axis('off')

    ax2.spines['right'].set_visible(False)
    ax2.spines['top'].set_visible(False)

    ax3.spines['right'].set_visible(False)
    ax3.spines['top'].set_visible(False)
Beispiel #17
0
def plot_fancy_overlay(
        fiber,
        cell,
        field,
        path_png,
        label="field",
        dpi=300,
        cmap_cell="Greys_r",
        cmap_fiber="Greys_r",
        cmap_angle="viridis",
        alpha_ori=0.8,
        alpha_cell=0.4,
        alpha_fiber=0.4,  # example cmaps: viridis/inferno/coolwarm 
        omin=-1,
        omax=1,
        scale=None):
    fig = plt.figure()
    plt.imshow(field, cmap=cmap_angle, vmin=omin, vmax=omax, alpha=alpha_ori)
    cbar = plt.colorbar()
    plt.imshow(fiber, cmap=cmap_fiber, alpha=alpha_fiber)
    plt.imshow(cell, cmap=cmap_cell, alpha=alpha_cell)
    plt.axis('off')
    cbar.set_label(label, fontsize=12)
    if scale is not None:
        scalebar = ScaleBar(scale,
                            "um",
                            length_fraction=0.1,
                            location="lower right",
                            box_alpha=0,
                            color="k")
        plt.gca().add_artist(scalebar)
    plt.tight_layout()
    plt.savefig(path_png, dpi=dpi, bbox_inches='tight', pad_inches=0)
    return fig
Beispiel #18
0
def plot_fiber_seg(fiber_image,
                   c0,
                   c1,
                   segmention,
                   path_png,
                   dpi=200,
                   scale=None):
    fig7 = plt.figure()
    my_norm = matplotlib.colors.Normalize(vmin=0.9999, vmax=1, clip=False)
    # create a copy of matplotlib cmap
    cmap = copycmap("Greys")

    # everything under vmin gets transparent (all zeros in mask)
    cmap.set_under('k', alpha=0)
    #everything else visible
    cmap.set_over('k', alpha=1)
    # plot mask and center
    plt.imshow(fiber_image, origin="upper")
    plt.imshow(segmention, cmap=cmap, norm=my_norm, origin="upper")
    plt.scatter(c0, c1, c="w")
    plt.axis('off')
    if scale is not None:
        scalebar = ScaleBar(scale,
                            "um",
                            length_fraction=0.1,
                            location="lower right",
                            box_alpha=0,
                            color="k")
        plt.gca().add_artist(scalebar)

    plt.tight_layout()
    plt.savefig(path_png, dpi=dpi, bbox_inches='tight', pad_inches=0)
    return fig7
Beispiel #19
0
    def _save_with_scalebar(self, signal, output_size=None):
        # upstream this part to hyperspy
        from matplotlib_scalebar.scalebar import ScaleBar
        from matplotlib.figure import Figure

        data = signal.data
        dpi = 100
        axes = signal.axes_manager.signal_axes
        if output_size is None:
            output_size = [axis.size for axis in axes]
        fig = Figure(figsize=[size / dpi for size in output_size], dpi=dpi)
        ax = fig.add_axes([0, 0, 1, 1])
        ax.axis('off')
        ax.imshow(data, cmap='gray')

        if not isinstance(axes[0].units, str):
            raise ValueError(
                "Units of the signal axis needs to be of string type.")
        scalebar = ScaleBar(axes[0].scale,
                            axes[0].units,
                            box_alpha=0.75,
                            length_fraction=0.4,
                            location='lower left',
                            font_properties={'size': 40})
        ax.add_artist(scalebar)
        fig.savefig(self.fullfname, dpi=dpi)
Beispiel #20
0
    def create_preview(self):
        if self.preview_figure != None:
            plt.close(self.preview_figure)
        # ---------fig0-------------------------------------------------------------
        # first picture after the blurring and turning to binary
        default_file = 'den.png'
        src = cv.imread(self.p_file_path, cv.COLOR_BGR2HLS)
        if src is None:
            print('Error opening image!')
            return -1
        blur = cv.GaussianBlur(src, (5, 5), 0)
        p_threshold2 = self.p_threshold1 * 3 if self.p_threshold1 <= 85 else 255
        dst = cv.Canny(src, self.p_threshold1, p_threshold2, None, 3)

        (DendriteList, img_merged_lines, _lines,
         merged_lines_all) = self.get_detected_picture(dst)
        self.preview_figure = plt.figure("Preview segmentation line detection")
        ax = plt.gca()
        scalebar = ScaleBar(0.167, 'um')
        ax.add_artist(scalebar)

        textstr = "Identified lines: {} \nIdentified lines after merging : {} ".format(
            len(_lines), len(merged_lines_all))
        props = dict(facecolor='blue', alpha=0.2)
        ax.set_xlabel(textstr, bbox=props, fontsize=20)

        imshow(img_merged_lines)
        plt.xticks([]), plt.yticks([])
        plt.show()
Beispiel #21
0
def plot_image_to_file(d, title, cmap=None, legend=None):
    # find the position to place the dot
    dot_pos = len(d[0]) / 2
    fig = plt.figure(constrained_layout=False, figsize=(15, 11.28), dpi=100)
    ax = fig.add_subplot()
    ax.set_title(title, {'fontsize': 28})
    ax.set_axis_off()
    plt.plot(dot_pos, dot_pos, 'ko')
    img = ax.imshow(d)
    scalebar = ScaleBar(30, fixed_units='km', location=3,
                        box_color='none')  # 1 pixel = 0.2 meter
    plt.gca().add_artist(scalebar)

    ax_img = fig.add_axes([0.16, 0.73, 0.21, 0.2], anchor='NW')
    if cmap:
        ax_img.imshow(te_logo, cmap=cmap)
    else:
        ax_img.imshow(te_logo)
    ax_img.axis('off')

    if legend:
        ax_legend = fig.add_axes([0.63, 0.07, 0.21, 0.2], anchor='SE')
        ax_legend.imshow(legend)
        ax_legend.axis('off')

    plt.tight_layout()
    f = tempfile.NamedTemporaryFile(suffix='.png').name
    plt.savefig(f, bbox_inches='tight')

    return f
Beispiel #22
0
def shape_subplot(data, shape_names, dx, units, ax, ax_radius=None):
    # Gather all shapes and plot
    all_shapes = geopandas.GeoSeries(data[shape_names].values.flatten())
    all_shapes.plot(color=(0, 0, 0, 0),
                    edgecolor=(1, 1, 1, 0.8),
                    lw=1,
                    aspect=None,
                    ax=ax)

    # Set axes boundaries to be square; make sure size of cells are relative to one another
    if ax_radius:
        s_bound = data.bounds
        centerx = np.mean([s_bound["minx"].min(), s_bound["maxx"].max()])
        centery = np.mean([s_bound["miny"].min(), s_bound["maxy"].max()])
        ax.set_xlim(centerx - ax_radius, centerx + ax_radius)
        ax.set_ylim(centery - ax_radius, centery + ax_radius)

    for spine in ax.spines.values():
        spine.set(edgecolor="white", linewidth=1)

    # Create scale bar
    scalebar = ScaleBar(dx,
                        units,
                        location="lower right",
                        color="white",
                        box_alpha=0,
                        scale_loc="top")
    ax.add_artist(scalebar)
Beispiel #23
0
def try_add_scalebar(axes, pixel_size, units="um", fontsize=8,
    location="lower left"):
    """
    If the *matplotlib_scalebar* package is available, add a 
    scalebar. Otherwise do nothing.

    args
    ----
        axes        :   matplotlib.axes.Axes
        pixel_size  :   float
        units       :   str
        fontsize    :   int
        location    :   str, "upper left", "lower left",
                        "upper right", or "lower right"

    returns
    -------
        None

    """
    try:
        from matplotlib_scalebar.scalebar import ScaleBar 
        scalebar = ScaleBar(pixel_size, units, location=location,
            frameon=False, color="w", font_properties={'size': fontsize})
        axes.add_artist(scalebar)
    except ModuleNotFoundError:
        pass 
def plot_images(img_xy_data,
                img_add_metadata,
                img_metadata,
                channels,
                saving_on=False,
                scalebar=True):

    format.formatLH()
    for img_index, img in enumerate(img_xy_data):
        ic(img_index, img.shape)

        # print ('image:', img)
        # print ('index:', index)
        # zstacks = (img_metadata[img_index][0]['Shape_czifile'][4])

        image = img[0]

        scaling_x = handler.disp_scaling(img_add_metadata)  #[img_index])
        ic(scaling_x)

        #print(img_metadata[img_index][0]['Filename'])
        print(img_metadata[img_index]['Filename'])

        for channel_index, channel_img in enumerate(img):  #enumerates channels
            ic(channel_index)
            ic(channels[channel_index])
            ic(channel_img.shape)

            for z_index, z_img in enumerate(channel_img):
                ic(z_index)  #plt.imshow(imx) #ic(inx, imx)
                ic(z_img.shape)

                temp_filename = img_metadata[img_index]['Filename'].replace(
                    '.czi', '')
                #temp_filename = img_metadata[img_index][0]['Filename'].replace('.czi', '')
                title_filename = ''.join([
                    temp_filename, '_', channels[channel_index], '_',
                    str(z_index)
                ])
                output_filename = ''.join(
                    ['analysis/', title_filename, '.png'])

                fig = plt.figure(figsize=(5, 5), frameon=False)
                fig.tight_layout(pad=0)
                plt.imshow(z_img, cmap='gray')

                scalebar = ScaleBar(dx=scaling_x[0],
                                    location='lower right',
                                    fixed_value=30,
                                    fixed_units='µm',
                                    frameon=False,
                                    color='w')  # 1 pixel = scale [m]
                plt.gca().add_artist(scalebar)
                plt.axis('off')
                plt.title(title_filename)

                if saving_on:
                    plt.savefig(output_filename,
                                dpi=300)  # ,image[channel],cmap='gray')
Beispiel #25
0
def _plot_scalebar(ax, fig, **kwargs):
    x1, x2, y1, y2 = ax.axis()
    _y = (y1 + y2) / 2
    scale_bar = ScaleBar(1,
                         location=kwargs.get("location", "lower left"),
                         fixed_value=kwargs.get("fixed_value", None),
                         fixed_units=kwargs.get("fixed_units", None))
    fig.gca().add_artist(scale_bar)
def _plot_scale(ax, fig, **kwargs):
    x1, x2, y1, y2 = ax.axis()
    _y = (y1 + y2) / 2
    p1, p2 = (int(x1), _y), (int(x1) + 1, _y)
    meter_per_deg = gcc.distance_between_points(p1, p2)
    scale_bar = ScaleBar(meter_per_deg, units="m", location=kwargs.get("location", "lower left"),
                         fixed_value=kwargs.get("fixed_value", None), fixed_units=kwargs.get("fixed_units", None))
    fig.gca().add_artist(scale_bar)
Beispiel #27
0
    def visualize(obj,
                  data,
                  titlestr,
                  scale=1,
                  save=False,
                  file=None,
                  microns=1,
                  factor=5):
        sz = np.array([
            np.linalg.eig(obj.sigma[:3, :3, i])[0].sum()
            for i in range(obj.sigma.shape[2])
        ])
        cl = obj.mu[:, 3:6]
        cl[cl < 0] = 0
        cl = cl / cl.max()
        P = obj.mu[:, :3] * scale
        plt.cla()
        plt.imshow(factor * data[:, :, :, [0, 1, 2]].max(2) / data.max())
        plt.scatter(P[:, 1],
                    P[:, 0],
                    s=20 * sz,
                    edgecolors='w',
                    marker='o',
                    facecolors=cl)

        if obj.prior is not None:
            cl = obj.prior['mu'][:, 3:]
            cl[cl < 0] = 0
            cl = cl / cl.max()
            PR = obj.prior['mu'][:, :3] * scale
            plt.scatter(PR[:, 1],
                        PR[:, 0],
                        s=10 * sz,
                        edgecolors='w',
                        marker='x',
                        facecolors=cl)

            for i in range(len(obj.prior['names'])):
                plt.annotate(obj.prior['names'][i], (P[i, 1], P[i, 0]), c='r')

        plt.title(titlestr)
        plt.axis('off')

        scalebar = ScaleBar(microns, 'um')
        plt.gca().add_artist(scalebar)

        if save:
            plt.gcf().set_size_inches(data.shape[1] / 20, data.shape[0] / 20)

            plt.savefig(file + '-labeling.eps', format='eps')
            plt.savefig(file + '-labeling.png', format='png')
            plt.savefig(file + '-labeling.pdf', format='pdf')

            plt.close('all')
        else:
            plt.pause(.1)
            plt.show()
Beispiel #28
0
    def draw(self):
        self.ax.clear()

        self.sample_figure.draw(self.ax)

        scalebar = ScaleBar(1.0, location="lower left")
        self.ax.add_artist(scalebar)

        self.canvas.draw()
Beispiel #29
0
 def plot(self, axis=None, title="", gamma=0.5, cmap='gray'):
     if axis is None:
         _, axis = plt.subplots(1, 1, figsize=(8, 8))
     axis.imshow((self.volume.sum(axis=0)) ** gamma, cmap=cmap)
     axis.axis(False)
     scale_bar = ScaleBar(self.pitch * 1e-6)
     axis.add_artist(scale_bar)
     title = f"{title}\n{self.total_count / 1e6:0.2f} mil photons"
     axis.set_title(title)
Beispiel #30
0
    def plot_cntr(self, roi_max_distance=300, padding=50):

        soma_pos = self.soma
        dendrites = self.data_paths[self.data_paths.type == 3]

        rois_pos = np.vstack(self.data_rois.roi_pos)
        rois_dis = self.data_rois.dendritic_distance_to_soma.values

        colors = np.vstack(
            plt.cm.viridis(
                (rois_dis / roi_max_distance * 255).astype(int)))[:, :3]

        fig, ax = plt.subplots(figsize=(8, 8))

        quality = self.data_cntr['cntr_quality'].values

        for row in dendrites.iterrows():

            path = row[1]['path']
            ax.plot(path[:, 0], path[:, 1], color='gray')

        for row in self.data_cntr.iterrows():

            idx = row[0]
            idx -= 1

            if idx < 0: continue

            distance = self.data_rois.loc[idx]['dendritic_distance_to_soma']

            if row[1]['cntr_quality']:

                cntr = row[1]['RF_cntr_upsampled'][0]
                ax.plot(cntr[:, 0], cntr[:, 1], color=colors[idx])
                ax.scatter(rois_pos[idx, 0],
                           rois_pos[idx, 1],
                           color=colors[idx],
                           zorder=10)

        stack_pixel_size = self.data_stack['pixel_size']
        stack_shape = self.data_stack['shape']
        max_lim = (stack_shape * stack_pixel_size)[0]
        max_lim = np.maximum(max_lim, 350)
        ax.set_xlim(-padding, max_lim)
        ax.set_ylim(-padding, max_lim)

        scalebar = ScaleBar(1,
                            units='um',
                            location='lower left',
                            box_alpha=0,
                            pad=0)
        ax.add_artist(scalebar)

        ax.invert_yaxis()
        ax.axis('off')
        ax.axis('equal')