def scatter_image(filename): """ Args: feature_x: x座標 feature_y: y座標 image_paths: """ feature_x = Y[:, 0] feature_y = Y[:, 1] image_paths = imgList fig = plt.figure() ax = fig.add_subplot(111) xlim = [feature_x.min() - 10, feature_x.max() + 10] ylim = [feature_y.min() - 10, feature_y.max() + 10] for (x, y, path) in zip(feature_x, feature_y, image_paths): img = cv2.imread(path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) bb = Bbox.from_bounds(x, y, 3, 3) 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) ax.set_ylim(*ylim) ax.set_xlim(*xlim) plt.savefig(filename, dpi=1200)
def plot_images(ax, xData, yData, ims, width_physical=None, labs=None, normalize=True): if labs is None: labs = ["" for _ in range(len(ims))] if normalize: vmin, vmax = np.min(ims), np.max(ims) ims_plot = (ims - vmin) / (vmax - vmin) # normalize ims_plot[:, 0, 0] = 1 # keep topleft pixel 1 to enforce normalization for idx, (x, y) in enumerate(zip(xData, yData)): if width_physical is None: small_im_dim = 0.5 else: small_im_dim = width_physical[idx] / 8 x -= small_im_dim / 2 y -= small_im_dim / 2 bb = Bbox.from_bounds(x, y, small_im_dim, small_im_dim) bb2 = TransformedBbox(bb, ax.transData) bbox_image = BboxImage(bb2, norm = None, origin=None, clip_on=False) #, cmap='gray_r') plt.title(labs[idx]) bbox_image.set_data(ims_plot[idx]) bbox_image.set_alpha(1.0) ax.add_artist(bbox_image) # Hide the right and top spines ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) # Only show ticks on the left and bottom spines ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') plt.xlim(-0.25, max(xData) + 0.5 / 2) plt.ylim(-0.25, max(yData) + 0.5 / 2)
def scatter_image(feature_x, feature_y, image_paths, title, output_file_name=None): fig = plt.figure() ax = fig.add_subplot(111) xlim = [min(feature_x) - 5, max(feature_x) + 5] ylim = [min(feature_y) - 5, max(feature_y) + 5] for (x, y, path) in zip(feature_x, feature_y, image_paths): img = plt.imread(path) img_height, img_width = img.shape[:2] bb = Bbox.from_bounds(x, y, img_height / 200, img_width / 200) 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) ax.set_ylim(*ylim) ax.set_xlim(*xlim) plt.title(title) if output_file_name is not None: plt.savefig(output_file_name) plt.show()
def imagesAtPositions(ax, images, positions): for s in range(len(positions)): #print(positions[s,:]) bbox = Bbox(corners(ax, positions[s,:],20)) bbox_image = BboxImage(bbox) image = imread(images[s]) bbox_image.set_data(image) ax.add_artist(bbox_image)
def imagesAtPositions(ax, images, positions): for s in range(len(positions)): #print(positions[s,:]) bbox = Bbox(corners(ax, positions[s, :], 20)) bbox_image = BboxImage(bbox) image = imread(images[s]) bbox_image.set_data(image) ax.add_artist(bbox_image)
def _init_bbox_image(self, im): bbox_image = BboxImage(self.get_window_extent, norm = None, origin=None, ) bbox_image.set_transform(IdentityTransform()) bbox_image.set_data(im) self.bbox_image = bbox_image
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # create a bounding box to house the image bb = Bbox.from_bounds(xdescent - 30, ydescent - 84, width + 84, height + 84) tbb = TransformedBbox(bb, trans) image = BboxImage(tbb) image.set_data(self.image_data) return [image]
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)
def _init_bbox_image(self, im): bbox_image = BboxImage(self.get_window_extent, norm=None, origin=None, ) bbox_image.set_transform(IdentityTransform()) bbox_image.set_data(im) self.bbox_image = bbox_image
def plotImage(x, y, im, x_scale, y_scale): """ Plots an image at each x and y location. """ bb = Bbox.from_bounds(x, y, x_scale, y_scale) # Change figure aspect ratio 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 plot(self, img, val, act): x, y = random.random() - 0.5, val w, h = self.img_shape bb = Bbox.from_bounds(x, y, w, h) bb2 = TransformedBbox(bb, self.ax.transData) bbox_image = BboxImage(bb2, norm=None, origin=None, clip_on=True) bbox_image.set_data(img) self.ax.add_artist(bbox_image)
class Scene(object): @property def t(self): return self._t @t.setter def t(self, value): self._t = value set_image(self.human, CAR_HUMAN, x=self.snapshot.human.ix(self.t)) xs = self.snapshot.human.ix(self.ts[self.ts<=self.t]) self.h_past.set_data(xs[:, 0], xs[:, 1]) xs = self.snapshot.human.ix(self.ts[self.ts>=self.t]) self.h_future.set_data(xs[:, 0], xs[:, 1]) for robot, traj in zip(self.robots, self.snapshot.robots): set_image(robot, CAR_ROBOT, x=traj.ix(self.t)) 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)
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
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)
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)
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]
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)
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]
def test_bbox_image_inverted(): # This is just used to produce an image to feed to BboxImage image = np.arange(100).reshape((10, 10)) ax = plt.subplot(111) 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 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)
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 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]
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'} )
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
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)
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)
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()
class PathClippedImagePatch(PathPatch): """ The given image is used to draw the face of the patch. Internally, it uses BboxImage whose clippath set to the path of the patch. FIXME : The result is currently dpi dependent. """ 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) def set_facecolor(self, color): """Simply ignore facecolor.""" super().set_facecolor("none") def draw(self, renderer=None): # the clip path must be updated every draw. any solution? -JJ self.bbox_image.set_clip_path(self._path, self.get_transform()) self.bbox_image.draw(renderer) super().draw(renderer)
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])
def plot_wind_data2(ax, so, time_nums): so.wind_speed = np.array(so.wind_speed) wind_speed_max = np.nanmax(so.wind_speed) 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'} )
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]
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()
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")) ncol = 2 nrow = len(maps) // ncol + 1 xpad_fraction = 0.3
# bbox_image.set_data( # imread( # "emoji/images/%s.png" % names[i] # ) # ) # f.add_artist(bbox_image) # print("emoji/images/%s.png" % names[i]) lowerCorner = f.transData.transform((.8,LABEL_Y_POS-.225)) upperCorner = f.transData.transform((1.2,LABEL_Y_POS+.225)) bbox_image = BboxImage(Bbox([[lowerCorner[0], lowerCorner[1]], [upperCorner[0], upperCorner[1]], ]), norm = None, origin=None, clip_on=False, ) bbox_image.set_data(imread('emoji/images/1f602.png')) f.add_artist(bbox_image) # f.xticks(_rl(data), names) plt.title("emojis!!!") plt.show()
class OffsetImage(OffsetBox): def __init__(self, arr, zoom=1, cmap = None, norm = None, interpolation=None, origin=None, filternorm=1, filterrad=4.0, resample = False, dpi_cor=True, **kwargs ): self._dpi_cor = dpi_cor self.image = BboxImage(bbox=self.get_window_extent, cmap = cmap, norm = norm, interpolation=interpolation, origin=origin, filternorm=filternorm, filterrad=filterrad, resample = resample, **kwargs ) self._children = [self.image] self.set_zoom(zoom) self.set_data(arr) OffsetBox.__init__(self) def set_data(self, arr): self._data = np.asarray(arr) self.image.set_data(self._data) def get_data(self): return self._data def set_zoom(self, zoom): self._zoom = zoom def get_zoom(self): return self._zoom # def set_axes(self, axes): # self.image.set_axes(axes) # martist.Artist.set_axes(self, axes) # def set_offset(self, xy): # """ # set offset of the container. # Accept : tuple of x,y cooridnate in disokay units. # """ # self._offset = xy # self.offset_transform.clear() # self.offset_transform.translate(xy[0], xy[1]) def get_offset(self): """ return offset of the container. """ return self._offset def get_children(self): return [self.image] def get_window_extent(self, renderer): ''' get the bounding box in display space. ''' w, h, xd, yd = self.get_extent(renderer) ox, oy = self.get_offset() return mtransforms.Bbox.from_bounds(ox-xd, oy-yd, w, h) def get_extent(self, renderer): if self._dpi_cor: # True, do correction dpi_cor = renderer.points_to_pixels(1.) else: dpi_cor = 1. zoom = self.get_zoom() data = self.get_data() ny, nx = data.shape[:2] w, h = nx*zoom, ny*zoom return w, h, 0, 0 def draw(self, renderer): """ Draw the children """ self.image.draw(renderer)
def plotDif_ind(leap, est, tMag, setName): dif = leap - est normed = np.linalg.norm(dif, axis=1) mean = np.mean(normed) std = np.var(normed) ** 2 # mean = np.mean(dif,axis=0) # std = np.var(dif, axis=0)**2 print "mean: %s +- %s" % (mean, std) ##Direct input plt.rcParams["text.latex.preamble"] = [r"\usepackage{lmodern}"] # Options params = { "text.usetex": True, "font.size": 11, "font.family": "lmodern", "text.latex.unicode": True # 'figure.autolayout': True } plt.rcParams.update(params) # figHeight = 5 figWidth = 6 # fig = plt.figure(figsize=(figWidth, figHeight), dpi=300) # plt.figure() ax = fig.add_axes([0, 0, figWidth, figHeight], frameon=False) # ax = fig.set_axis_off() styleL = ["solid", "dashed", "dotted", "dashdot"] if len(est[0]) == 3: leap = leap[:, :-1] fMCP = plt.subplot(411) fMCP.plot(tMag, leap[:, 0], c="r", ls=styleL[0]) fMCP.plot(tMag, est[:, 0], c="g", ls=styleL[0]) fMCP.set_ylabel(r"$\theta_{MCP}$ [rad]") plt.setp(fMCP.get_xticklabels(), visible=False) fPIP = plt.subplot(412, sharey=fMCP, sharex=fMCP) fPIP.plot(tMag, leap[:, 1], c="r", ls=styleL[0]) fPIP.plot(tMag, est[:, 1], c="g", ls=styleL[0]) fPIP.plot(tMag, leap[:, 2], c="r", ls=styleL[1]) fPIP.plot(tMag, est[:, 2], c="g", ls=styleL[1]) fPIP.set_ylabel(r"$\theta_{PIP}$\\ \, $\theta_{DIP}$ [rad]") plt.setp(fPIP.get_xticklabels(), visible=False) aMCP = plt.subplot(413, sharey=fMCP, sharex=fMCP) aMCP.plot(tMag, leap[:, 3], c="r", ls=styleL[0]) aMCP.plot(tMag, est[:, 3], c="g", ls=styleL[0]) aMCP.set_ylabel(r"$\phi_{MCP}$ [rad]") plt.setp(aMCP.get_xticklabels(), visible=True) fMCP.set_title("Difference " + setName) difP = plt.subplot(414, sharey=fMCP, sharex=fMCP) dif = leap - est normedDif = np.linalg.norm(dif, axis=1) difP.plot(tMag, normedDif, c="k", ls="-") difP.set_ylabel("Normed\nDifference [rad]") difP.set_xlabel("Time [sec]") difP.set plt.xlim([0, tMag[-1] + 1]) plt.xticks(np.arange(0, tMag[-1], 5)) linePerf = mlines.Line2D([], [], color="r", markersize=15, label="Leap") lineEst = mlines.Line2D([], [], color="g", markersize=15, label="Estimated") plt.figlegend((linePerf, lineEst), ("Leap", "Estimated"), loc="upper center") # plt.figlegend((linePerf,lineEst), # ('Leap','Estimated'), loc='upper center', bbox_to_anchor=(0.5,1.04), ncol=2) """ adding the pictures... """ TICKYPOS = -0.75 difP.get_xaxis().set_ticklabels([]) # lowerCorner = difP.transData.transform((.8,TICKYPOS-.2)) # upperCorner = difP.transData.transform((1.2,TICKYPOS+.2)) lowPos = [-1.6, TICKYPOS - 1.2] upPos = [lowPos[0] + 6, lowPos[1] + 1.5] print lowPos print upPos lowerCorner = difP.transData.transform((lowPos[0], lowPos[1])) upperCorner = difP.transData.transform((upPos[0], upPos[1])) # first bbox_image0 = BboxImage( Bbox([[lowerCorner[0], lowerCorner[1]], [upperCorner[0], upperCorner[1]]]), norm=None, origin=None, clip_on=False, ) bbox_image0.set_data(imread("../thesis/pictures/statePics/bestLeap/out-0.jpg")) difP.add_artist(bbox_image0) # second lowC1 = difP.transData.transform((lowPos[0] + 6.5, lowPos[1])) upC1 = difP.transData.transform((upPos[0] + 6.5, upPos[1])) bbox_image1 = BboxImage(Bbox([[lowC1[0], lowC1[1]], [upC1[0], upC1[1]]]), norm=None, origin=None, clip_on=False) bbox_image1.set_data(imread("../thesis/pictures/statePics/bestLeap/out-5.jpg")) difP.add_artist(bbox_image1) plt.savefig("../thesis/pictures/plots/bestEstTEST.png", dpi=300, bbox_inches="tight")
class OffsetImage(OffsetBox): def __init__(self, arr, zoom=1, cmap=None, norm=None, interpolation=None, origin=None, filternorm=1, filterrad=4.0, resample=False, dpi_cor=True, **kwargs): self._dpi_cor = dpi_cor self.image = BboxImage(bbox=self.get_window_extent, cmap=cmap, norm=norm, interpolation=interpolation, origin=origin, filternorm=filternorm, filterrad=filterrad, resample=resample, **kwargs) self._children = [self.image] self.set_zoom(zoom) self.set_data(arr) OffsetBox.__init__(self) def set_data(self, arr): self._data = np.asarray(arr) self.image.set_data(self._data) def get_data(self): return self._data def set_zoom(self, zoom): self._zoom = zoom def get_zoom(self): return self._zoom # def set_axes(self, axes): # self.image.set_axes(axes) # martist.Artist.set_axes(self, axes) # def set_offset(self, xy): # """ # set offset of the container. # Accept : tuple of x,y cooridnate in disokay units. # """ # self._offset = xy # self.offset_transform.clear() # self.offset_transform.translate(xy[0], xy[1]) def get_offset(self): """ return offset of the container. """ return self._offset def get_children(self): return [self.image] def get_window_extent(self, renderer): ''' get the bounding box in display space. ''' w, h, xd, yd = self.get_extent(renderer) ox, oy = self.get_offset() return mtransforms.Bbox.from_bounds(ox - xd, oy - yd, w, h) def get_extent(self, renderer): if self._dpi_cor: # True, do correction dpi_cor = renderer.points_to_pixels(1.) else: dpi_cor = 1. zoom = self.get_zoom() data = self.get_data() ny, nx = data.shape[:2] w, h = nx * zoom, ny * zoom return w, h, 0, 0 def draw(self, renderer): """ Draw the children """ self.image.draw(renderer)
if 1: # __name__ == "__main__": fig = plt.figure(1) ax = plt.subplot(121) txt = ax.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) ax.add_artist(bbox_image) ax = plt.subplot(122) a = np.linspace(0, 1, 256).reshape(1, -1) a = np.vstack((a, a)) maps = sorted( m for m in plt.cm.cmap_d if not m.endswith("_r") and # Skip reversed colormaps. not m.startswith(('spectral', 'Vega')) # Skip deprecated colormaps. ) # fig.subplots_adjust(top=0.99, bottom=0.01, left=0.2, right=0.99) ncol = 2
ax.add_patch(patches.Rectangle((8-.1,TICKYPOS-.05),.2,.2, fill=False,clip_on=False)) ticks = [0,2,4,6,8] a = [] for i in ticks[:2]: lowerCorner = ax.transData.transform(((i+1-.225),TICKYPOS-.225)) # lowerCorner = ax.transData.transform((0.775,TICKYPOS-.225)) upperCorner = ax.transData.transform(((i+1+.225),TICKYPOS+.225)) # upperCorner = ax.transData.transform((1.225,TICKYPOS+.225)) bbox_image = BboxImage(Bbox([[lowerCorner[0], lowerCorner[1]], [upperCorner[0], upperCorner[1]], ]), norm = None, origin=None, clip_on=False, ) bbox_image.set_data(imread('emoji/images/%s.png' % names[i])) a.append(bbox_image) ax.add_artist(bbox_image) plt.xticks(_rl(a), a) plt.show()
# -*- coding: utf-8 -*- import numpy as np from matplotlib import pyplot as plt from matplotlib.image import BboxImage from matplotlib.transforms import Bbox, TransformedBbox img = np.random.randint(0, 255, (100, 200, 3)) print img.shape ax = plt.subplot() loc = np.array([[0, 0], [200.0, 100.0]]) bbox0 = Bbox(loc) bbox = TransformedBbox(bbox0, ax.transData) bbox_image = BboxImage(bbox) bbox_image.set_data(img) ax.add_artist(bbox_image) bbox_image.bbox._bbox.set_points(loc + [10, 5]) bbox_image.bbox.invalidate() ax.set_xlim(-10, 210) ax.set_ylim(-10, 110) ax.axis("off") plt.show()
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')
# upperCorner = difP.transData.transform((1.2,TICKYPOS+.2)) lowPos = [0,TICKYPOS-1.2] upPos = [lowPos[0]+1.2,lowPos[1]+1.2] print lowPos print upPos lowerCorner = plt.gca().transData.transform((lowPos[0],lowPos[1])) upperCorner = plt.gca().transData.transform((upPos[0],upPos[1])) # first bbox_image0 = BboxImage(Bbox([[lowerCorner[0], lowerCorner[1]], [upperCorner[0], upperCorner[1]]]), norm = None, origin=None, clip_on=False, ) bbox_image0.set_data(imread('../thesis/pictures/statePics/set14/set14_0.jpg')) plt.gca().add_artist(bbox_image0) # second #lowC1 = plt.gca().transData.transform((lowPos[0]+6.5,lowPos[1])) #upC1 = plt.gca().transData.transform((upPos[0]+6.5,upPos[1])) #bbox_image1 = BboxImage(Bbox([[lowC1[0], lowC1[1]], # [upC1[0], upC1[1]]]), # norm = None, # origin=None, # clip_on=False, # ) #bbox_image1.set_data(imread('../thesis/pictures/statePics/set14/set14_1.jpg')) #plt.gca().add_artist(bbox_image1) ## third #lowC2 = plt.gca().transData.transform((lowPos[0]+6.5,lowPos[1])) #upC2 = plt.gca().transData.transform((upPos[0]+6.5,upPos[1]))