Example #1
0
def test_bbox_image_inverted():
    # This is just used to produce an image to feed to BboxImage
    image = np.arange(100).reshape((10, 10))

    fig, ax = plt.subplots()
    bbox_im = BboxImage(
        TransformedBbox(Bbox([[100, 100], [0, 0]]), ax.transData))
    bbox_im.set_data(image)
    bbox_im.set_clip_on(False)
    ax.set_xlim(0, 100)
    ax.set_ylim(0, 100)
    ax.add_artist(bbox_im)

    image = np.identity(10)

    bbox_im = BboxImage(
        TransformedBbox(Bbox([[0.1, 0.2], [0.3, 0.25]]),
                        ax.figure.transFigure))
    bbox_im.set_data(image)
    bbox_im.set_clip_on(False)
    ax.add_artist(bbox_im)
    def make_artists(self, axes, show_intruder):
        'make self.artists_dict'

        assert self.vec_list
        self.img = get_airplane_img()

        posa_list = [(v[0], v[1], v[2]) for v in self.vec_list]
        posb_list = [(v[3], v[4], v[5]) for v in self.vec_list]

        pos_lists = [posa_list, posb_list]

        if show_intruder:
            pos_lists.append(posb_list)

        for i, pos_list in enumerate(pos_lists):
            x, y, theta = pos_list[0]

            l = axes.plot(*zip(*pos_list), f'c-', lw=0, zorder=1)[0]
            l.set_visible(False)
            self.artists_dict[f'line{i}'] = l

            if i == 0:
                lc = LineCollection([], lw=2, animated=True, color='k', zorder=1)
                axes.add_collection(lc)
                self.artists_dict[f'lc{i}'] = lc

                int_lc = LineCollection([], lw=2, animated=True, color='k', zorder=1)
                axes.add_collection(int_lc)
                self.artists_dict[f'int_lc{i}'] = int_lc

            # only sim_index = 0 gets intruder aircraft
            if i == 0 or (i == 1 and show_intruder):
                size = State.plane_size
                box = Bbox.from_bounds(x - size/2, y - size/2, size, size)
                tbox = TransformedBbox(box, axes.transData)
                box_image = BboxImage(tbox, zorder=2)

                theta_deg = (theta - np.pi / 2) / np.pi * 180 # original image is facing up, not right
                img_rotated = ndimage.rotate(self.img, theta_deg, order=1)

                box_image.set_data(img_rotated)
                axes.add_artist(box_image)
                self.artists_dict[f'plane{i}'] = box_image

            if i == 0:
                dot = axes.plot([x], [y], 'k.', markersize=6.0, zorder=2)[0]
                self.artists_dict[f'dot{i}'] = dot

                rad = 1500
                c = patches.Ellipse((x, y), rad, rad, color='k', lw=3.0, fill=False)
                axes.add_patch(c)
                self.artists_dict[f'circle{i}'] = c
Example #3
0
        def plotImage(x, y, im):
            # TODO hard-coded size of images, breaks in some cases
            width = 1
            height = 2
            bb = Bbox.from_bounds(x,y,width, height)
            bb2 = TransformedBbox(bb,plot.transData)
            bbox_image = BboxImage(bb2,
                                norm = None,
                                origin=None,
                                clip_on=False)

            bbox_image.set_data(im)
            plot.add_artist(bbox_image)
Example #4
0
def plotImagesInWeightSpace( fig, wspace, orig_images, img_dims, margin_percent = 0.03, img_ratio = 0.035 ):
    # Author: C. Howard
    # function to robustly plot images in the weight space
    #
    # fig: Figure handle for plotting
    # wspace        : The lower dimensional features such that wspace = W*X where W maps
    #                 the input data X into lower dim data
    # orig_images   : This is basically X where each column is a vectorized image
    # img_dims      : This is the rectangular dimensions of each image in the data set
    # margin_percent: What percent of the data span we want to add margin in the plot
    # img_ratio     : What ratio we use to decide image sizes to be plotted,  relative to the data span


    # get number of original images
    (d,num_images) = orig_images.shape

    # get max dims of data
    x1max = np.max(wspace[0, :])
    x1min = np.min(wspace[0, :])
    x2max = np.max(wspace[1, :])
    x2min = np.min(wspace[1, :])

    # get the center
    x1c = 0.5 * (x1max + x1min)
    x2c = 0.5 * (x2max + x2min)

    # get width and height
    w = x1max - x1min
    h = x2max - x2min

    # compute how much to scale the width/height from the
    # center of the data to set the xlimits/ylimits
    scale = 0.5 + margin_percent

    # plot the images in the weight space
    ax = fig.add_subplot(111)

    for k in range(0, num_images):
        bb          = Bbox.from_bounds(wspace[0, k], wspace[1, k], w * img_ratio, h * img_ratio)
        bb2         = TransformedBbox(bb, ax.transData)
        bbox_img    = BboxImage(bb2, norm=None, origin=None, clip_on=False)
        bbox_img.set_data(orig_images[:, k].reshape(img_dims[0], img_dims[0]))
        ax.add_artist(bbox_img)

    # set the axis limits
    ax.set_xlim(x1c - scale * w, x1c + scale * w)
    ax.set_ylim(x2c - scale * h, x2c + scale * h)

    # return the fig handle and axis handle
    return (fig,ax)
Example #5
0
def test_bbox_image_inverted():
    # This is just used to produce an image to feed to BboxImage
    fig = plt.figure()
    axes = fig.add_subplot(111)
    axes.plot([1, 2, 3])

    im_buffer = io.BytesIO()
    fig.savefig(im_buffer)
    im_buffer.seek(0)
    image = imread(im_buffer)

    bbox_im = BboxImage(Bbox([[100, 100], [0, 0]]))
    bbox_im.set_data(image)
    axes.add_artist(bbox_im)
Example #6
0
    def show(data, eps=0.0):
        # Make box slightly larger
        box_extent = data.space.partition.extent * (1.0 + eps)
        box_min = data.space.min_pt - data.space.partition.extent * eps / 2.0

        bbox0 = Bbox.from_bounds(*box_min, *box_extent)
        bbox = TransformedBbox(bbox0, ax.transData)
        # TODO: adapt interpolation
        bbox_image = BboxImage(bbox,
                               norm=normalization,
                               cmap='bone',
                               interpolation='nearest',
                               origin=False)
        bbox_image.set_data(np.asarray(data).T)
        ax.add_artist(bbox_image)
Example #7
0
    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):
        scale = 1.5
        bb = Bbox.from_bounds(
            xdescent + self.offset,
            ydescent,
            height * self.image_data.shape[1] / self.image_data.shape[0] * scale,
            height * scale)

        tbb = TransformedBbox(bb, trans)
        image = BboxImage(tbb)
        image.set_data(self.image_data)

        self.update_prop(image, orig_handle, legend)
        return [image]
Example #8
0
    def create_artists(self, legend, orig_handle, xdescent, ydescent, width,
                       height, fontsize, trans):

        # enlarge the image by these margins
        sx, sy = self.image_stretch

        # create a bounding box to house the image
        bb = Bbox.from_bounds(xdescent - sx, ydescent - sy, width + sx,
                              height + sy)

        tbb = TransformedBbox(bb, trans)
        image = BboxImage(tbb)
        image.set_data(self.image_data)

        self.update_prop(image, orig_handle, legend)

        return [image]
Example #9
0
    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):

        l = matplotlib.lines.Line2D([xdescent+self.offset,xdescent+(width-self.space)/3.+self.offset],
                                     [ydescent+height/2., ydescent+height/2.])
        l.update_from(orig_handle)
        l.set_clip_on(False)
        l.set_transform(trans)

        bb = Bbox.from_bounds(xdescent +(width+self.space)/3.+self.offset,
                              ydescent,
                              height*self.image_data.shape[1]/self.image_data.shape[0],
                              height)

        tbb = TransformedBbox(bb, trans)
        image = BboxImage(tbb)
        image.set_data(self.image_data)

        self.update_prop(image, orig_handle, legend)
        return [l,image]
Example #10
0
def plot_wind_data2(ax, so, time_nums):

    so.wind_speed = np.array(so.wind_speed)
    max_index = so.wind_speed.argmax()
    wind_speed_max = so.wind_speed[max_index]
    print('max speed', wind_speed_max, len(so.wind_speed))

    logo = image.imread('north.png', None)
    bbox2 = Bbox.from_bounds(210, 330, 30, 40)
    #     trans_bbox2 = bbox2.transformed(ax.transData)
    bbox_image2 = BboxImage(bbox2)
    bbox_image2.set_data(logo)
    ax.add_image(bbox_image2)

    #     for x in range(0,len(time_nums),100):
    U = so.u
    V = so.v

    #          if x == max_index:
    Q = ax.quiver(time_nums,
                  -.15,
                  U,
                  V,
                  headlength=0,
                  headwidth=0,
                  headaxislength=0,
                  alpha=1,
                  color='#045a8d',
                  width=.0015,
                  scale=wind_speed_max * 5)
    ax.quiverkey(
        Q,
        0.44,
        0.84,
        wind_speed_max * .6,
        labelpos='N',
        label=
        '                                    0 mph                      %.2f mph'
        % wind_speed_max,
        #                    fontproperties={'weight': 'bold'}
    )
Example #11
0
    def create_artists(self, legend, orig_handle, xdescent, ydescent, width,
                       height, fontsize, trans):
        # save original visibility and then make it visible
        orig_vis = orig_handle.get_visible()
        orig_handle.set_visible(1)
        # set correct state and image data
        if not orig_vis:
            image_data = VisibilityHandler._unchecked
            self.state = False
        else:
            image_data = VisibilityHandler._checked
            self.state = True

        # ratio for square checkbox
        image_ratio = image_data.shape[1] / image_data.shape[0]

        # create a checkbox artist
        bb = Bbox.from_bounds(xdescent, ydescent, height * image_ratio, height)
        tbb = TransformedBbox(bb, trans)
        image = BboxImage(tbb)
        image.set_data(image_data)

        # update self
        self.update_prop(image, orig_handle, legend)
        self.set_events(image, orig_handle)

        # artists to be returned
        artists = [image]

        # if a handler is given, create artists to be return
        if self.handler is not None:
            artists += self.handler.create_artists(legend, orig_handle,
                                                   xdescent - (height * 2.),
                                                   ydescent,
                                                   width - (height * 2.),
                                                   height, fontsize, trans)

        # revert visibility
        orig_handle.set_visible(orig_vis)
        return artists
Example #12
0
def plotBWImage(x, y, im, ax, lims=(3, 3)):
    """
        Plots image im on a x,y scatter plot

        :param x: x plot location
        :param y: y plot location
        :param im: bw image to be plotted, should be a 2D numpy matrix
        :param ax: axis to plot the image on
        :param lims: (xlim,ylim) tuple where |x| > xlim and |y| > ylim are not
                        plotted
        :returns: matplotlib.image.BboxImage handle to the plotted image
                    or None if x,y outside of lims
    """
    if np.abs(x) > lims[0] or np.abs(y) > lims[1]:
        return

    bb = Bbox.from_bounds(x, y, 0.1, 0.1)
    bb2 = TransformedBbox(bb, ax.transData)
    bbox_image = BboxImage(bb2, norm=None, origin=None, clip_on=False)

    bbox_image.set_data(im)
    ax.add_artist(bbox_image)
Example #13
0
def imagesAsTickMarks(ax, images):
    TICKYPOS = -.6
    lowerCorner = ax.transData.transform((.8, TICKYPOS - .2))
    upperCorner = ax.transData.transform((1.2, TICKYPOS + .2))
    print(lowerCorner)
    print(upperCorner)
    bbox_image = BboxImage(
        Bbox([
            lowerCorner[0],
            lowerCorner[1],
            upperCorner[0],
            upperCorner[1],
        ]),
        norm=None,
        origin=None,
        clip_on=False,
    )

    image = imread(images[0])
    print('img loaded')
    bbox_image.set_data(image)
    ax.add_artist(bbox_image)
Example #14
0
def scatter_image(feature_x, feature_y, image_paths, title, save=None, code_list=None):
	"""
	Args:
	feature_x: x座標
	feature_y: y座標
	image_paths: 
	"""
	global Scale

	fig = plt.figure()
	ax = fig.add_subplot(111)
	xlim = [np.min(feature_x)-5, np.max(feature_x)+5]
	ylim = [feature_y.min()-5, feature_y.max()+5]

	for (x, y, path) in zip(feature_x, feature_y, image_paths):
		img = plt.imread(path)

		if EmpCode != "" and get_class ( path ) == EmpCode :
			img = frame_image ( img, 30, 0 )
			
		elif code_list != None :
			idx = code_list.index ( get_class (path) )
			img = frame_image ( img, 30, float(idx) / len(code_list), cmap=cm )

		disp_size = max ( xlim[1]-xlim[0], ylim[1]-ylim[0] ) / Num
		bb = Bbox.from_bounds(x, y, disp_size*Scale, disp_size * Scale)
		bb2 = TransformedBbox(bb, ax.transData)
		bbox_image = BboxImage(bb2, cmap=None, norm=None, origin=None, clip_on=False)
			
		bbox_image.set_data(img)
		ax.add_artist(bbox_image)

	ax.set_ylim(*ylim)
	ax.set_xlim(*xlim)
	plt.title(title)
	if save is not None:
		plt.savefig(save, dpi=600)
	plt.show()
Example #15
0
    def __init__(self, ax, snapshot):
        self.snapshot = snapshot
        self.ax = ax
        self.ax.set_aspect('equal', 'box-forced')

        self.grass = BboxImage(ax.bbox, interpolation='bicubic', zorder=-1000)
        self.ax.add_artist(self.grass)
        self.grass.set_data(GRASS)

        for lane in self.snapshot.lanes:
            path = Path([
                lane.p-LANE_SCALE*lane.m-lane.n*lane.w*0.5,
                lane.p-LANE_SCALE*lane.m+lane.n*lane.w*0.5,
                lane.q+LANE_SCALE*lane.m+lane.n*lane.w*0.5,
                lane.q+LANE_SCALE*lane.m-lane.n*lane.w*0.5,
                lane.p-LANE_SCALE*lane.m-lane.n*lane.w*0.5
            ], [
                Path.MOVETO,
                Path.LINETO,
                Path.LINETO,
                Path.LINETO,
                Path.CLOSEPOLY
            ])
            ax.add_artist(PathPatch(path, facecolor=LANE_COLOR, lw=0.5, edgecolor=LANE_BCOLOR, zorder=-100))

        self.robots = [AxesImage(self.ax, interpolation='bicubic', zorder=0) for robot in self.snapshot.robots]
        for robot in self.robots:
            self.ax.add_artist(robot)

        self.human = AxesImage(self.ax, interpolation='bicubic', zorder=100)
        self.ax.add_artist(self.human)
        self.ts = np.linspace(0., self.snapshot.human.T, STEPS)
        xs = self.snapshot.human.ix(self.ts)
        self.h_future = ax.plot(xs[:, 0], xs[:, 1], zorder=50, linestyle='--', color='white', linewidth=1.)[0]
        self.h_past = ax.plot(xs[:, 0], xs[:, 1], zorder=40, linestyle='-', color='blue', linewidth=2.)[0]

        self.ax.set_xlim(-0.5, 0.5)
        self.ax.set_ylim(-0.2, 0.8)
Example #16
0
def graph_update(i):
    ax1.clear()
    ax1.set_ylim(myGraph.ymin, myGraph.ymax)
    ax1.set_xlim(myGraph.xmin, myGraph.xmax)
    champ_count = df['name'][:i].value_counts()
    champs = champ_count.index.values
    play_count = champ_count.values
    for j, champ in enumerate(champs):
        lowerCorner = ax1.transData.transform((-.4 + j, .85 * myGraph.ymin))
        upperCorner = ax1.transData.transform((.4 + j, 0.1 * myGraph.ymin))
        bbox_image = BboxImage(
            Bbox([
                [lowerCorner[0], lowerCorner[1]],
                [upperCorner[0], upperCorner[1]],
            ]),
            norm=None,
            origin=None,
            clip_on=False,
        )
        bbox_image.set_data(imread('{}.png'.format(champs[j])))
        ax1.add_artist(bbox_image)
    ax1.bar(champs, play_count)
    myGraph.update_graph(champ_count[0])
Example #17
0
def main(argv):
    parser = argparse.ArgumentParser(prog='VIZ')
    parser.add_argument('source', help='path to the source metadata file')
    args = parser.parse_args(argv[1:])

    # read in the data file
    data = pandas.read_csv(args.source, sep='\t')

    # load up data
    vis_x = data['x'].tolist()
    vis_y = data['y'].tolist()
    img_data = data['filename'].tolist()

    # Create figure
    fig = plt.figure()
    ax = fig.add_subplot(111)

    for x, y, filepath in zip(vis_x, vis_y, img_data):
        im = plt.imread(filepath)

        bb = Bbox.from_bounds(x, y, 1, 1)
        bb2 = TransformedBbox(bb, ax.transData)
        bbox_image = BboxImage(bb2, norm=None, origin=None, clip_on=False)

        bbox_image.set_data(im)
        ax.add_artist(bbox_image)

    #plt.scatter(vis_x, vis_y, marker='s', c=vis_y)
    #plt.colorbar(ticks=range(10))
    #plt.clim(-0.5, 9.5)

    # Set the x and y limits
    ax.set_ylim(-50, 50)
    ax.set_xlim(-50, 50)

    plt.show()
Example #18
0
    def create_artists(self, legend, orig_handle, xdescent, ydescent, width,
                       height, fontsize, trans):

        l = Line2D([xdescent + self.offset], [ydescent + height / 2.],
                   c=self.color,
                   ls="",
                   marker="o",
                   mfc=self.color,
                   mec=self.color)
        l.set_clip_on(False)

        bb = Bbox.from_bounds(
            xdescent + (width + self.space) / 3. + self.offset, ydescent,
            height * self.image_data.shape[1] / self.image_data.shape[0],
            height)

        tbb = TransformedBbox(bb, trans)
        image = BboxImage(tbb)
        image.set_data(self.image_data)
        image.set_alpha(1.0)
        legend.set_alpha(1.0)

        self.update_prop(image, orig_handle, legend)
        return [l, image]
Example #19
0
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox, TransformedBbox
from matplotlib.image import BboxImage
from pathlib import Path

c = Path.cwd() / "checked.png"

# Create figure and axes
fig, ax = plt.subplots()

# Add the Bbox Image to add the checked.png image
bb = Bbox.from_bounds(0.2, 0.2, 0.6, 0.6)
image_data = plt.imread(c, 0)
tbb = TransformedBbox(bb, ax.transData)
bbox_image = BboxImage(tbb)
bbox_image.set_data(image_data)
ax.add_artist(bbox_image)

plt.show()
    fmt = ScalarFormatter(useOffset=False)
    ax.xaxis.set_major_formatter(fmt)

    for year, h, bc in zip(years, heights, box_colors):
        bbox0 = Bbox.from_extents(year - 0.4, 0., year + 0.4, h)
        bbox = TransformedBbox(bbox0, ax.transData)
        rb_patch = RibbonBoxImage(bbox, bc, interpolation="bicubic")

        ax.add_artist(rb_patch)

        ax.annotate(r"%d" % (int(h / 100.) * 100), (year, h),
                    va="bottom",
                    ha="center")

    patch_gradient = BboxImage(
        ax.bbox,
        interpolation="bicubic",
        zorder=0.1,
    )
    gradient = np.zeros((2, 2, 4), dtype=float)
    gradient[:, :, :3] = [1, 1, 0.]
    gradient[:, :, 3] = [[0.1, 0.3], [0.3, 0.5]]  # alpha channel
    patch_gradient.set_array(gradient)
    ax.add_artist(patch_gradient)

    ax.set_xlim(years[0] - 0.5, years[-1] + 0.5)
    ax.set_ylim(0, 10000)

    fig.savefig('ribbon_box.png')
    plt.show()
Example #21
0
def plotImage(x, y, im):
    bb = Bbox.from_bounds(x, y, 1, 1)
    bb2 = TransformedBbox(bb, ax.transData)
    bbox_image = BboxImage(bb2, norm=None, origin=None, clip_on=False)
    bbox_image.set_data(im)
    ax.add_artist(bbox_image)
def display_patches_ticklabels():
    ytickspace = 0
    S0_ticks = np.array([
        dist_echo[echodepth > -1000],
        [ytickspace] * len(dist_echo[echodepth > -1000])
    ]).T
    S1_ticks = np.array([
        dist_echo[(echodepth < -1000) & (echodepth > -1500)], [ytickspace] *
        len(dist_echo[(echodepth < -1000) & (echodepth > -1500)])
    ]).T
    S2_ticks = np.array([
        dist_echo[(echodepth < -1500) & (echodepth > -2000)], [ytickspace] *
        len(dist_echo[(echodepth < -1500) & (echodepth > -2000)])
    ]).T
    S3_ticks = np.array([
        dist_echo[(echodepth < -2000) & (echodepth > -3000)], [ytickspace] *
        len(dist_echo[(echodepth < -2000) & (echodepth > -3000)])
    ]).T
    S4_ticks = np.array([
        dist_echo[(echodepth < -3000)],
        [ytickspace] * len(dist_echo[(echodepth < -3000)])
    ]).T

    xaxislen = np.max(dist_gline) + 20 - (np.min(dist_gline) - 20)
    ytickspace = 50
    for i in range(len(S0_ticks)):
        lowerCorner = contour_ax.transData.transform(
            (S0_ticks[i][0] - 0.05 * xaxislen, S0_ticks[i][1] - ytickspace))
        upperCorner = contour_ax.transData.transform(
            (S0_ticks[i][0] + 0.05 * xaxislen, S0_ticks[i][1] + ytickspace))
        print([lowerCorner[0], lowerCorner[1], upperCorner[0], upperCorner[1]])
        bbox_image = BboxImage(Bbox([[lowerCorner[0], lowerCorner[1]],
                                     [upperCorner[0], upperCorner[1]]]),
                               norm=None,
                               origin=None,
                               clip_on=False)
        bbox_image.set_data(plt.imread('./Images/acrossASF/markers/cross.png'))
        contour_ax.add_artist(bbox_image)

    for i in range(len(S1_ticks)):
        lowerCorner = contour_ax.transData.transform(
            (S1_ticks[i][0] - 0.05 * xaxislen, S0_ticks[i][1] - ytickspace))
        upperCorner = contour_ax.transData.transform(
            (S1_ticks[i][0] + 0.05 * xaxislen, S0_ticks[i][1] + ytickspace))
        bbox_image = BboxImage(Bbox([[lowerCorner[0], lowerCorner[1]],
                                     [upperCorner[0], upperCorner[1]]]),
                               norm=None,
                               origin=None,
                               clip_on=False)
        bbox_image.set_data(
            plt.imread('./Images/acrossASF/markers/circle.png'))
        contour_ax.add_artist(bbox_image)

    for i in range(len(S2_ticks)):
        lowerCorner = contour_ax.transData.transform(
            (S2_ticks[i][0] - 0.05 * xaxislen, S0_ticks[i][1] - ytickspace))
        upperCorner = contour_ax.transData.transform(
            (S2_ticks[i][0] + 0.05 * xaxislen, S0_ticks[i][1] + ytickspace))
        bbox_image = BboxImage(Bbox([[lowerCorner[0], lowerCorner[1]],
                                     [upperCorner[0], upperCorner[1]]]),
                               norm=None,
                               origin=None,
                               clip_on=False)
        bbox_image.set_data(
            plt.imread('./Images/acrossASF/markers/square.png'))
        contour_ax.add_artist(bbox_image)

    for i in range(len(S3_ticks)):
        lowerCorner = contour_ax.transData.transform(
            (S3_ticks[i][0] - 0.05 * xaxislen, S0_ticks[i][1] - ytickspace))
        upperCorner = contour_ax.transData.transform(
            (S3_ticks[i][0] + 0.05 * xaxislen, S0_ticks[i][1] + ytickspace))
        bbox_image = BboxImage(Bbox([[lowerCorner[0], lowerCorner[1]],
                                     [upperCorner[0], upperCorner[1]]]),
                               norm=None,
                               origin=None,
                               clip_on=False)
        bbox_image.set_data(
            plt.imread('./Images/acrossASF/markers/triangle.png'))
        contour_ax.add_artist(bbox_image)

    for i in range(len(S4_ticks)):
        lowerCorner = contour_ax.transData.transform(
            (S4_ticks[i][0] - 0.05 * xaxislen, S0_ticks[i][1] - ytickspace))
        upperCorner = contour_ax.transData.transform(
            (S4_ticks[i][0] + 0.05 * xaxislen, S0_ticks[i][1] + ytickspace))
        bbox_image = BboxImage(Bbox([[lowerCorner[0], lowerCorner[1]],
                                     [upperCorner[0], upperCorner[1]]]),
                               norm=None,
                               origin=None,
                               clip_on=False)
        bbox_image.set_data(plt.imread('./Images/acrossASF/markers/plus.png'))
        contour_ax.add_artist(bbox_image)
Example #23
0
images = torch.from_numpy(raw_data.astype('float32'))
images = [image.view(-1) for image in images]

for image in images:
    state = vae_append(state, image)
bb_ans_compressed = bytes_to_img(rans.flatten(state).tobytes())

raw_data = np.concatenate(~raw_data, axis=1)

labels = ["BB-ANS",          "bz2",          "PNG",          "MNIST"]
data   = [bb_ans_compressed, bz2_compressed, png_compressed, raw_data          ]

yticks = []
for i, d in enumerate(data):
    bbox = Bbox.from_bounds(0, 28 * (spacing + i * (h + spacing)),
                            28 * d.shape[1], 28 * h)
    bbox = TransformedBbox(bbox, ax.transData)
    bbox_image = BboxImage(bbox, cmap='gray', origin=None)
    bbox_image.set_data(d)
    ax.add_artist(bbox_image)
    yticks.append(28 * (spacing + i * (h + spacing) + h // 2))

ax.set_xlim(0, max(28 * d.shape[1] for d in data))
ax.set_yticks(yticks)
ax.set_yticklabels(labels)
ax.set_ylim(0, 28 * (spacing + (i + 1) * (h + spacing)))
ax.set_xlabel('Size (bits)')
ax.set_aspect('equal')
plt.savefig('compression_plot.png', dpi=800, bbox_inches='tight')
Example #24
0
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.image import BboxImage
from matplotlib.transforms import Bbox, TransformedBbox

fig, (ax1, ax2) = plt.subplots(ncols=2)

# ----------------------------
# Create a BboxImage with Text
# ----------------------------
txt = ax1.text(0.5, 0.5, "test", size=30, ha="center", color="w")
kwargs = dict()

bbox_image = BboxImage(txt.get_window_extent,
                       norm=None,
                       origin=None,
                       clip_on=False,
                       **kwargs)
a = np.arange(256).reshape(1, 256) / 256.
bbox_image.set_data(a)
ax1.add_artist(bbox_image)

# ------------------------------------
# Create a BboxImage for each colormap
# ------------------------------------
a = np.linspace(0, 1, 256).reshape(1, -1)
a = np.vstack((a, a))

# List of all colormaps; skip reversed colormaps.
maps = sorted(m for m in plt.colormaps() if not m.endswith("_r"))
Example #25
0
Y = np.array(Y)
print(X.shape, Y.shape)

from sklearn.decomposition import PCA
pca = PCA(n_components=2)
pca.fit(X)
transformed = pca.transform(X)
print(transformed.shape)
plt.scatter(transformed[:, 0], transformed[:, 1], c=Y)
plt.colorbar()
plt.show()

X = transformed
from matplotlib.image import BboxImage
from matplotlib.transforms import Bbox, TransformedBbox
fig = plt.figure()
ax = fig.add_subplot(111)
for (r, label, path) in zip(X, Y, Z):
    x, y = r
    img = plt.imread(path)
    bb = Bbox.from_bounds(x, y, 1, 1)
    bb2 = TransformedBbox(bb, ax.transData)
    bbox_image = BboxImage(bb2, norm=None, origin=None, clip_on=False)
    bbox_image.set_data(img)
    ax.add_artist(bbox_image)
xlim = [X[:, 0].min() - 2, X[:, 0].max() + 2]
ylim = [X[:, 1].min() - 2, X[:, 1].max() + 2]
ax.set_xlim(*xlim)
ax.set_ylim(*ylim)
plt.show()
# plots T-SNE embeddings as a scatter plot (for reference)
plt.clf()
plt.scatter(embedded[:, 0], embedded[:, 1], marker='.', color='blue')
plt.savefig("tests/tsne_test.png")
plt.clf()

# generates 2d T-SNE visualization of image embeddings
plt.clf()
fig = plt.figure(figsize=(25, 25))
plt.xlim([-20, 20])
plt.ylim([-20, 20])
ax = fig.add_subplot(111)
plt.axis('off')

# adapted from https://stackoverflow.com/questions/25329583/matplotlib-using-image-for-points-on-plot
for i in range(0, len(img_filepaths)):
    bb = Bbox.from_bounds(embedded[i][0], embedded[i][1], 1.0, 1.0)
    bb2 = TransformedBbox(bb, ax.transData)
    bbox_image = BboxImage(bb2,
                           norm=None,
                           origin=None,
                           clip_on=False,
                           cmap='gray')
    im = plt.imread(img_filepaths[i])
    bbox_image.set_data(im)
    ax.add_artist(bbox_image)

# saves figure
plt.savefig("tests/testfig.png", dpi=500, bbox_inches='tight')
plt.clf()
Example #27
0
                                                                                                                                                                                                                                                                    def draw(self, renderer, *args, **kwargs):

                                                                                                                                                                                                                                                                                bbox = self.get_window_extent(renderer)
                                                                                                                                                                                                                                                                                        stretch_factor = bbox.height / bbox.width

                                                                                                                                                                                                                                                                                                ny = int(stretch_factor*self._ribbonbox.nx)
                                                                                                                                                                                                                                                                                                        if self._cached_ny != ny:
                                                                                                                                                                                                                                                                                                                        arr = self._ribbonbox.get_stretched_image(stretch_factor)
                                                                                                                                                                                                                                                                                                                                    self.set_array(arr)
                                                                                                                                                                                                                                                                                                                                                self._cached_ny = ny

                                                                                                                                                                                                                                                                                                                                                        BboxImage.draw(self, renderer, *args, **kwargs)


                                                                                                                                                                                                                                                                                                                                                        if 1:
                                                                                                                                                                                                                                                                                                                                                                from matplotlib.transforms import Bbox, TransformedBbox
                                                                                                                                                                                                                                                                                                                                                                    from matplotlib.ticker import ScalarFormatter

                                                                                                                                                                                                                                                                                                                                                                        fig, ax = plt.subplots()

                                                                                                                                                                                                                                                                                                                                                                            years = np.arange(2004, 2009)
                                                                                                                                                                                                                                                                                                                                                                                box_colors = [(0.8, 0.2, 0.2),
                                                                                                                                                                                                                                                                                                                                                                                                          (0.2, 0.8, 0.2),
                                                                                                                                                                                                                                                                                                                                                                                                                            (0.2, 0.2, 0.8),
                                                                                                                                                                                                                                                                                                                                                                                                                                              (0.7, 0.5, 0.8),
                                                                                                                                                                                                                                                                                                                                                                                                                                                                (0.3, 0.8, 0.7),
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ]
                                                                                                                                                                                                                                                                                                                                                                                    heights = np.random.random(years.shape) * 7000 + 3000

                                                                                                                                                                                                                                                                                                                                                                                        fmt = ScalarFormatter(useOffset=False)
                                                                                                                                                                                                                                                                                                                                                                                            ax.xaxis.set_major_formatter(fmt)

                                                                                                                                                                                                                                                                                                                                                                                                for year, h, bc in zip(years, heights, box_colors):
                                                                                                                                                                                                                                                                                                                                                                                                            bbox0 = Bbox.from_extents(year-0.4, 0., year+0.4, h)
                                                                                                                                                                                                                                                                                                                                                                                                                    bbox = TransformedBbox(bbox0, ax.transData)
                                                                                                                                                                                                                                                                                                                                                                                                                            rb_patch = RibbonBoxImage(bbox, bc, interpolation="bicubic")

                                                                                                                                                                                                                                                                                                                                                                                                                                    ax.add_artist(rb_patch)

                                                                                                                                                                                                                                                                                                                                                                                                                                            ax.annotate(r"%d" % (int(h/100.)*100),
                                                                                                                                                                                                                                                                                                                                                                                                                                                                        (year, h), va="bottom", ha="center")

                                                                                                                                                                                                                                                                                                                                                                                                                                                patch_gradient = BboxImage(ax.bbox,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       interpolation="bicubic",
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      zorder=0.1,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     )
                                                                                                                                                                                                                                                                                                                                                                                                                                                    gradient = np.zeros((2, 2, 4), dtype=np.float)
                                                                                                                                                                                                                                                                                                                                                                                                                                                        gradient[:,:,:3] = [1, 1, 0.]
                                                                                                                                                                                                                                                                                                                                                                                                                                                            gradient[:,:,3] = [[0.1, 0.3],[0.3, 0.5]] # alpha channel
                                                                                                                                                                                                                                                                                                                                                                                                                                                                patch_gradient.set_array(gradient)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                    ax.add_artist(patch_gradient)


                                                                                                                                                                                                                                                                                                                                                                                                                                                                        ax.set_xlim(years[0]-0.5, years[-1]+0.5)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                            ax.set_ylim(0, 10000)

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                fig.savefig('ribbon_box.png')
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    plt.show()
Example #28
0
 def __init__(self, path, bbox_image, **kwargs):
     super().__init__(path, **kwargs)
     self.bbox_image = BboxImage(self.get_window_extent,
                                 norm=None,
                                 origin=None)
     self.bbox_image.set_data(bbox_image)
Example #29
0
           for name_color in args.players_colors)
players = [{'name': name_color.split('_')[0][:17].upper(),
            'color': name_color.split('_')[1],
            'wedges': set()}
           for name_color in args.players_colors]

# rectangular axes for legend, die rolls, and key to topics
fig, ax = plt.subplots(1, 1, figsize=(11, 9))
plt.subplots_adjust(left=-.15)
ax.set_axis_off()

# images for rolling die
dice = {i: plt.imread(f'images/{i}.png') for i in range(7)}
bb = Bbox.from_bounds(.84, .46, .065, .1)
bb2 = TransformedBbox(bb, ax.transData)
bbox_image = BboxImage(bb2)

# perimiter spaces
p_coords = [(6, i * (2 * np.pi / 42)) for i in range(42)]
p_coords.append((0, 0))
# will plot 'wedge' spaces a second time with larger markers
w_coords = [(6, i * (2 * np.pi / 42)) for i in range(42) if i % 7 == 0]

# 'spoke' spaces
s_coords = [(k, j * (2 * np.pi / 42)) for k in range(1, 6) for j in range(0, 42, 7)]

# coordinates for plotting
p_r, p_th = zip(*p_coords)
p_r = np.asarray(p_r)
p_th = np.asarray(p_th)