def show_predicted_values(ab_unscaled, lab): num_images = lab.shape[0] num_rows = int(math.sqrt(num_images)) num_columns = num_images/num_rows # reshape predictions into image grid a_grid = np.zeros([IMAGE_SIZE*num_rows,IMAGE_SIZE*num_columns,1]) b_grid = np.zeros([IMAGE_SIZE*num_rows,IMAGE_SIZE*num_columns,1]) rgb_grid = np.zeros([IMAGE_SIZE*num_rows,IMAGE_SIZE*num_columns,3]) for i in range(num_rows): for j in range(num_columns): a_grid[IMAGE_SIZE*i:IMAGE_SIZE*(i+1),IMAGE_SIZE*j:IMAGE_SIZE*(j+1),:] = ab_unscaled[num_columns*i+j,:,:,0:1] b_grid[IMAGE_SIZE*i:IMAGE_SIZE*(i+1),IMAGE_SIZE*j:IMAGE_SIZE*(j+1),:] = ab_unscaled[num_columns*i+j,:,:,1:2] rgb_grid[IMAGE_SIZE*i:IMAGE_SIZE*(i+1),IMAGE_SIZE*j:IMAGE_SIZE*(j+1),:] = color.lab2rgb(lab[10*i+j,:,:,:]) plt.imshow(a_grid[:,:,0], cmap='gray', norm=NoNorm()) plt.show() plt.title("Histogram of predicted a values (min 0, max 1)") plt.hist(a_grid.flatten()) plt.show() plt.imshow(b_grid[:,:,0], cmap='gray', norm=NoNorm()) plt.show() plt.title("Histogram of predicted b values (min 0, max 1)") plt.hist(b_grid.flatten()) plt.show() plt.imshow(rgb_grid) plt.show()
def show_im_with_uncertainty(img, uncertainty, row, col): mask = uncertainty mask = np.ma.masked_where(mask < 0.1, mask) plt.figure(figsize=(col / my_dpi, row / my_dpi), dpi=my_dpi) plt.imshow(img, cmap='gray', interpolation='bicubic', norm=NoNorm()) plt.imshow(mask, cmap='jet', interpolation='bicubic', norm=NoNorm()) plt.axis('off') fig = plt.gcf() return fig
def predicts_from_A_to_B(self, model_path=None): np.random.seed(0) if model_path != None: self.g_AB.load_weights(model_path) imgs_A = self.data_loader.load_data(domain='A', batch_size=100) imgs_B = self.data_loader.load_data(domain='B', batch_size=100) fake_B = self.g_AB.predict(imgs_A) rec_A = self.g_BA.predict(fake_B) r, c = 5, 4 # 5行4列 candidates = [] for ai in range(0, len(imgs_A)): candidates.append(imgs_A[ai] * 0.5 + 0.5) candidates.append(fake_B[ai] * 0.5 + 0.5) candidates.append(rec_A[ai] * 0.5 + 0.5) candidates.append(imgs_B[ai] * 0.5 + 0.5) if (ai + 1) % 10 == 0: cnt = 0 titles = ['Origin A', 'Translation B', 'Rec A', 'Origin B'] # candidates = np.concatenate(candidates) # candidates = 0.5 * candidates + 0.5 fig, axs = plt.subplots(nrows=r, ncols=c, figsize=(10, 10)) for ti, title in enumerate(titles): axs[0, ti].set_title(title) for i in range(r): for j in range(c): axs[i, j].imshow( np.squeeze(candidates[cnt], -1), cmap='gray', norm=NoNorm()) # squeeze减少不必要维度,NoNorm去除默认的归一化 axs[i, j].axis('off') cnt += 1 fig.savefig(self.predicts_dir + '/epoch_%d/%d.png' % (self.epoch, ai + 1)) candidates = []
def main(): # Parse flags cfg = forge.config() cfg.num_workers = 0 # Set manual seed torch.manual_seed(cfg.seed) np.random.seed(cfg.seed) # Make CUDA operations deterministic torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # Get data loaders train_loader, _, _ = fet.load(cfg.data_config, cfg) # Visualise for x in train_loader: fig, axes = plt.subplots(1, cfg.batch_size, figsize=(20, 10)) img = x['input'] for b_idx in range(cfg.batch_size): np_img = np.moveaxis(img.data.numpy()[b_idx], 0, -1) if img.shape[1] == 1: axes[b_idx].imshow( np_img[:, :, 0], norm=NoNorm(), cmap='gray') elif img.shape[1] == 3: axes[b_idx].imshow(np_img) axes[b_idx].axis('off') manager = plt.get_current_fig_manager() manager.resize(*manager.window.maxsize()) plt.show()
def show_classes(self): '''Show the class values.''' import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap, NoNorm from spectral import get_rgb if self.class_axes is not None: msg = 'ImageView.show_classes should only be called once.' warnings.warn(UserWarning(msg)) return elif self.classes is None: raise Exception('Unable to display classes: class array not set.') cm = ListedColormap(np.array(self.class_colors) / 255.) self._update_class_rgb() kwargs = self.imshow_class_kwargs.copy() kwargs.update({ 'cmap': cm, 'vmin': 0, 'norm': NoNorm(), 'interpolation': self._interpolation }) if self.axes is not None: # A figure has already been created for the view. Make it current. plt.figure(self.axes.figure.number) self.class_axes = plt.imshow(self.class_rgb, **kwargs) if self.axes is None: self.axes = self.class_axes.axes self.class_axes.set_zorder(1) if self.display_mode == 'overlay': self.class_axes.set_alpha(self._class_alpha) else: self.class_axes.set_alpha(1)
def show_initial_image(self): """ function that displays the initial image. """ if self.mybifs.image_file_loaded == True: self.ax1.clear() self.canvas.draw() self.ax1.set_title("Initial Image") if self.mybifs.imdim == 1: self.ax1.plot(self.mybifs.init_image()) elif self.mybifs.imdim == 2: self.ax1.imshow(self.mybifs.init_image(), cmap=cm.Greys_r, norm=NoNorm()) else: # assume for now that the only other possibility is 3D # can change later slice_index = np.intp( np.round(self.mybifs.view3Dslice[1] * self.mybifs.init_image().shape[ self.mybifs.view3Dslice[0]])) if self.mybifs.view3Dslice[0] == 0: init_im_slice = self.mybifs.init_image()[slice_index, :, :] elif self.mybifs.view3Dslice[0] == 1: init_im_slice = self.mybifs.init_image()[:, slice_index, :] elif self.mybifs.view3Dslice[0] == 2: init_im_slice = self.mybifs.init_image()[:, :, slice_index] else: raise BifsBadIndex( "Sorry slice index needs to be one of 0,1,2") self.ax1.imshow(init_im_slice, cmap=cm.Greys_r) self.canvas.draw() return
def plotBoard(idx, X, y): X = X.reshape(-1, 64, 50, 50, channels) for i in range(len(idx)): board = X[idx[i], :, :, :] board = board.reshape(64, 50, 50, channels) img = reshape_squares(board, 8, 8) fig, axs = plt.subplots(1, 2, figsize=[10, 5]) fig.patch.set_facecolor('black') plt.rcParams['savefig.facecolor'] = 'black' fig.patch.set_alpha(.5) if gray: axs[0].imshow(img.reshape(img.shape[0], -1), cmap='gray', norm=NoNorm()) else: axs[0].imshow(img) axs[0].set_xticks([]) axs[0].set_yticks([]) axs[1].text(0, 0, matrixToText(y[idx[i]]), color='white', fontproperties='monospace', fontsize=25) axs[1].set_xticks([]) axs[1].set_yticks([]) axs[1].set_frame_on(False) plt.tight_layout() plt.show() pass
def view_pics(pics,cols,titles,output_full_path='tmp.png'): #pics应为一维数组,每个为单通道灰度图 c = cols r = int(np.ceil(len(pics)/c)) print('子图共%d行,%d列'%(r,c)) fig, axs = plt.subplots(r, c) fig.set_size_inches(w=c*1.5, h=r*1.5) fig.set_dpi(300) # fig.savefig('test2png.png', dpi=100) print('画布生成完毕') cnt = 0 gen_imgs = np.array(pics) # Rescale images 0 - 1 gen_imgs = gen_imgs/255 print('图像归一化完毕') for i in range(r): for j in range(c): if cnt>= len(pics):break t = gen_imgs[cnt] axs[i, j].imshow(t, cmap='gray',norm=NoNorm()) #NoNorm去除默认的归一化 if i==0: axs[i, j].set_title(titles[j]) if i!=0 and j==0:axs[i, j].set_title(i,loc='left',color='r') axs[i, j].axis('off') cnt += 1 print('子图已绘制%d/%d行'%(i,r)) fig.savefig(output_full_path) plt.close()
def draw_constraint_plot(self): cmap = ListedColormap(['#00FF8C', '#E0E0E0']) action_name_list = [ self.action_no_label_mapping[self.action_map[str(row_id)].split( '_')[0]] for row_id in xrange(len(self.action_map)) ] fig = plt.figure() fig.set_figheight(5) fig.set_figwidth(12) ax = fig.add_subplot(1, 1, 1) ax.set_yticks(xrange(len(self.action_map))) ax.set_xticks(xrange(len(self.action_map))) ax.set_yticklabels(action_name_list, va='bottom', minor=False) ax.set_xticklabels(action_name_list, rotation='vertical', ha='left', minor=False) im = ax.pcolor(self.constraints, cmap=cmap, norm=NoNorm()) plt.title('Constraint plot') plt.xlabel('Actions') plt.ylabel('Constraint details') plt.grid(True) cbar = fig.colorbar(im, orientation='vertical') cbar.ax.set_yticklabels(['not required', 'required']) plt.show()
def draw_heatmaps(case_data, project, timestamp, diced_meta_dir): rownames, matrix = _build_heatmap_matrix(case_data) # def draw_heatmaps(rownames, matrix, cohort, timestamp, outputDir): if not len(matrix) > 0: raise ValueError('input matrix must have nonzero length') if not len(matrix) == len(rownames): raise ValueError('Number of row names does not match input matrix') #Sort heatmaps rows by row count sorted_rownames, sorted_matrix = __sort_rows(rownames, matrix) green = '#338855' white = '#FFFFFF' cmap = ListedColormap([white, green]) fig = Figure(figsize=(24, 12)) ax = fig.add_subplot(111) ax.set_title("%s: Data Type Breakdown by Participant" % project, weight="black") ax.set_ylabel("Data Type (Total Sample Count)", weight="black") ax.set_xlabel("Participant", weight="black") ax.set_xlim(0, len(sorted_matrix[0])) ax.set_yticks([0.5 + x for x in range(len(sorted_matrix))]) counts = [sum(row) for row in sorted_matrix] ax.set_yticklabels([ "%s (%s)" % (data_type, count) for data_type, count in zip(sorted_rownames, counts) ]) ax.pcolor(numpy.array(sorted_matrix), cmap=cmap, norm=NoNorm(), edgecolor="k") missing = Rectangle((0, 0), 1, 1, fc=white) present = Rectangle((0, 0), 1, 1, fc=green) ax.legend([present, missing], ["Present", "Absent"], loc=1) fig.set_size_inches(24, 12) ax.title.set_size("xx-large") ax.xaxis.label.set_size("xx-large") ax.yaxis.label.set_size("xx-large") ax.tick_params(axis="both", labelsize="x-large") canvas = FigureCanvasAgg(fig) high_res_filepath = os.path.join( diced_meta_dir, ".".join([project, timestamp, "high_res.heatmap.png"])) fig.tight_layout() canvas.print_figure(high_res_filepath) fig.set_size_inches(12, 6) ax.title.set_size("medium") ax.xaxis.label.set_size("small") ax.yaxis.label.set_size("small") ax.tick_params(axis="both", labelsize="x-small") fontProp = font_manager.FontProperties(size=9) ax.legend([present, missing], ["Present", "Absent"], loc=1, prop=fontProp) canvas = FigureCanvasAgg(fig) low_res_filepath = os.path.join( diced_meta_dir, ".".join([project, timestamp, "low_res.heatmap.png"])) fig.tight_layout() canvas.print_figure(low_res_filepath)
def draw_similarity(ax, hgt, X_gnomes, color=None): x_min, x_max = -1.1, 1.1 y_min, y_max = -1.1, 1.1 h = 0.02 xx, yy = np.meshgrid(np.arange(x_min, x_max + h, h), np.arange(y_min, y_max + h, h)) # print("mesh x/y size:", xx.shape, yy.shape) # mesh put together with x/y coordinates XY_mesh = np.c_[xx.ravel(), yy.ravel()] # print("evaluation meshgrid shape") # print(XY_mesh.shape) XY_gnomes = hgt.transform(XY_mesh) XY_gnomes = XY_gnomes.reshape(xx.shape[0], xx.shape[1], -1) heat_colors = sns.color_palette("Reds", n_colors=10) for i, clr in enumerate(heat_colors): temp_color = list(heat_colors[i]) if len(temp_color) == 3: temp_color += [ 1.0, ] temp_color[3] = i / 10 heat_colors[i] = temp_color gray_colors = sns.color_palette("Greys", n_colors=10) for i, clr in enumerate(gray_colors): temp_color = list(gray_colors[i]) if len(temp_color) == 3: temp_color += [ 1.0, ] temp_color[3] = i / 10 gray_colors[i] = temp_color # print("similarity contour colors") # print(heat_colors) no_norm = NoNorm(vmin=0, vmax=1.0, clip=True) heat_cmap = ListedColormap(heat_colors) gray_cmap = ListedColormap(gray_colors) mesh_gnome_result = gnome_similarity( X_gnomes.reshape(1, -1), XY_gnomes.reshape(-1, XY_gnomes.shape[2])) mesh_gnome_result = mesh_gnome_result.reshape(XY_gnomes.shape[0:2]) contour_set = ax.contourf(xx, yy, mesh_gnome_result, levels=10, norm=no_norm, cmap=gray_cmap) # contour_set = ax.contourf(xx, yy, mesh_gnome_result, levels=10, norm=no_norm, cmap=heat_cmap, nchunk=0, # antialiased=False) return contour_set
def show_im_withdef(input, pred, row, col): plt.figure(figsize=(col / my_dpi, row / my_dpi), dpi=my_dpi) this_diff = diff(input, pred) this_diff = np.ma.masked_where(this_diff < 0.05, this_diff) plt.imshow(pred, cmap='gray', interpolation='bicubic', norm=NoNorm()) plt.imshow(this_diff, cmap='jet', interpolation='bicubic') plt.axis('off') fig = plt.gcf() return fig
def plot_heatmap(ax, data, x_labels, y_labels, rotate=0): heatmap = ax.pcolor(data, cmap=plt.cm.Blues, norm=NoNorm()) # put the major ticks at the middle of each cell ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False) ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False) ax.xaxis.tick_top() ax.set_xticklabels(x_labels, minor=False, rotation=rotate) ax.set_yticklabels(y_labels, minor=False)
def test_nonorm(): plt.rcParams['svg.fonttype'] = 'none' data = [1, 2, 3, 4, 5] fig, ax = plt.subplots(figsize=(6, 1)) fig.subplots_adjust(bottom=0.5) norm = NoNorm(vmin=min(data), vmax=max(data)) cmap = cm.get_cmap("viridis", len(data)) mappable = cm.ScalarMappable(norm=norm, cmap=cmap) cbar = fig.colorbar(mappable, cax=ax, orientation="horizontal")
def plotSquares(squares): fig, axs = plt.subplots(8, 8) fig.patch.set_facecolor('black') plt.rcParams['savefig.facecolor'] = 'black' for i, ax in enumerate(axs.flatten()): if gray: ax.imshow(squares[i], cmap='gray', norm=NoNorm()) else: ax.imshow(squares[i]) ax.set_xticks([]) ax.set_yticks([]) plt.show() pass
def plot_images(*imgs, titles=[], channels='bgr', normalize=False, ticks_off=True): assert channels.lower() in [ 'bgr', 'rgb', 'mono' ], 'Possible values for channels are: bgr, rgb or mono!' # f = plt.figure(figsize=(30, 20)) width_def = 60 height_def = 60 width = math.ceil(math.sqrt(len(imgs))) height = math.ceil(len(imgs) / width) height_def = height_def / 5 * width # print(height_def) if height_def > 65: height_def = 65 f = plt.figure(figsize=(width_def, height_def)) # print(str(width) + ' , ' + str(height)) for i, img in enumerate(imgs, 1): ax = f.add_subplot(height, width, i) if ticks_off: ax.axis('off') if len(titles) != 0: if len(imgs) != len(titles): print( 'WARNING titles lenght is not the same as images lenght!') try: ax.set_title(str(titles[i - 1])) except: pass if channels.lower() == 'mono' or img.ndim == 2: if normalize: norm = Normalize() else: norm = NoNorm() ax.imshow(img, cmap=plt.get_cmap('gray'), norm=norm) elif channels.lower() == 'rgb': ax.imshow(img) else: ax.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
def apply(self, data, mask): """ Apply the colorizer to a data/mask set. TODO: Clean this up a bit """ self.rgba = None if len(self.bands) == 1: # Singleband pseudocolor data = data[0, :, :] else: # Multiband RGB. No colorizing to do, just transpose the # data array and add the mask band. Mask may be discarded # later when using jpg as output, for example. self.rgba = np.dstack((np.transpose(data, (1, 2, 0)), mask)) return self.rgba if self.interp == 'linear': norm = Normalize(self.ranges[0], self.ranges[-1]) sm = ScalarMappable(norm=norm, cmap=self.colormap) self.rgba = sm.to_rgba(data, bytes=True) if self.interp == 'discrete': norm = BoundaryNorm(boundaries=self.ranges, ncolors=256) sm = ScalarMappable(norm=norm, cmap=self.colormap) self.rgba = sm.to_rgba(data, bytes=True) if self.interp == 'exact': norm = NoNorm() sm = ScalarMappable(norm=norm, cmap=self.colormap) # Copy and mask the entire array. tmp_data = data.copy() tmp_data.fill(0) tmp_mask = mask.copy() tmp_mask.fill(0) # Reclassify the data for n, r in enumerate(self.ranges): ix = np.logical_and((data == r), (mask == 255)) tmp_data[ix] = n + 1 tmp_mask[ix] = 255 self.rgba = sm.to_rgba(tmp_data, bytes=True) mask = tmp_mask self.rgba[:, :, 3] = mask return self.rgba
def plot(axes, ax1, ax2, tensor=None, title=None, grey=False, axis=False, fontsize=4): if tensor is not None: im = convert_to_np_im(tensor) if grey: im = im[:, :, 0] axes[ax1, ax2].imshow(im, norm=NoNorm(), cmap='gray') else: axes[ax1, ax2].imshow(im) if not axis: axes[ax1, ax2].axis('off') else: axes[ax1, ax2].set_xticks([]) axes[ax1, ax2].set_yticks([]) if title is not None: axes[ax1, ax2].set_title(title, fontsize=fontsize)
def visual_convolution(image, kernel, debug=False): fig = plt.figure() _image = np.pad(image, ((1, 1), (1, 1)), 'constant') # padd with zeros output_image = np.copy(image) frames = [output_image] convolve(image, kernel, frames=frames) img = plt.imshow(np.copy(output_image), animated=True, cmap="gray", norm=NoNorm()) def update(f): img.set_array(f) return img ani = FuncAnimation(fig, update, frames=frames, interval=50) html = HTML(ani.to_html5_video()) plt.close() display(html)
def save_imgs(self, epoch): os.makedirs('images/%s' % self.dataset_name, exist_ok=True) r, c = 2, 3 imgs_A = self.data_loader.load_data(domain="A", batch_size=1, is_testing=True) imgs_B = self.data_loader.load_data(domain="B", batch_size=1, is_testing=True) # Demo (for GIF) # imgs_A = self.data_loader.load_img('datasets/apple2orange/testA/n07740461_1541.jpg') # imgs_B = self.data_loader.load_img('datasets/apple2orange/testB/n07749192_4241.jpg') # Translate images to the other domain fake_B = self.g_AB.predict(imgs_A) fake_A = self.g_BA.predict(imgs_B) # Translate back to original domain reconstr_A = self.g_BA.predict(fake_B) reconstr_B = self.g_AB.predict(fake_A) gen_imgs = np.concatenate( [imgs_A, fake_B, reconstr_A, imgs_B, fake_A, reconstr_B]) # Rescale images 0 - 1 gen_imgs = 0.5 * gen_imgs + 0.5 titles = ['Original', 'Translated', 'Reconstructed'] fig, axs = plt.subplots(r, c) cnt = 0 for i in range(r): for j in range(c): axs[i, j].imshow(np.squeeze(gen_imgs[cnt], -1), cmap='gray', norm=NoNorm()) # squeeze减少不必要维度,NoNorm去除默认的归一化 axs[i, j].set_title(titles[j]) axs[i, j].axis('off') cnt += 1 fig.savefig("images/%s/%d.png" % (self.dataset_name, epoch)) plt.close()
def show_initial_image(self): """ function that displays the initial image. """ try: if self.mybifs.image_file_loaded == True: self.ax1.clear() self.canvas.draw() self.ax1.set_title("Initial Image") if self.mybifs.imdim == 1: self.ax1.plot(self.mybifs.init_image) elif self.mybifs.imdim == 2: self.ax1.imshow(self.mybifs.init_image, cmap=cm.Greys_r, norm=NoNorm()) else: # assume for now that the only other possibility is 3D # can change later slice_index = np.int( np.round(self.mybifs.view3Dslice[1] * self.mybifs.init_image.shape[ self.mybifs.view3Dslice[0]])) if self.mybifs.view3Dslice[0] == 0: init_im_slice = self.mybifs.init_image[ slice_index, :, :] elif self.mybifs.view3Dslice[0] == 1: init_im_slice = self.mybifs.init_image[:, slice_index, :] elif self.mybifs.view3Dslice[0] == 2: init_im_slice = self.mybifs.init_image[:, :, slice_index] else: print("Sorry slice index needs to be one of 0,1,2") self.ax1.imshow(init_im_slice, cmap=cm.Greys_r) self.canvas.draw() return except: QtWidgets.QMessageBox.information(self, "Image Viewer", "No image loaded %s.") return
def we30Kings(n=30): X, y = importXy(n=n) kings = y.index[y['k'] == 1] kimg = X[kings] img = reshape_squares(kimg[:30, :, :, :], 3, 10) fig, ax = plt.subplots() fig.patch.set_facecolor('black') plt.rcParams['savefig.facecolor'] = 'black' fig.patch.set_alpha(.5) if gray: ax.imshow(img.reshape(img.shape[0], -1), cmap='gray', norm=NoNorm()) else: ax.imshow(img) ax.set_xticks([]) ax.set_yticks([]) plt.tight_layout() plt.show() pass
def gen_spec(df): """ Spectrogram generation: Power spectral density (PSD) computed for fixed window (100 ms) from onset of USV. If PSD > 0.4, spectrograms generated by Fast Fourier Transform and saved as .png files """ rec_start = 1237074.7 # time stamp of recording session onset call_list = df["call"] time_list = df["Nlx_adjusted"] # time stamps of USV onset for time, call in zip(time_list, call_list): spec_begin = (time - rec_start) * 250 spec_end = spec_begin + 25000 f, Pxx = welch( x_filt[int(spec_begin):int(spec_end)], fs, window="blackmanharris", nperseg=500, noverlap=400, nfft=500, ) if Pxx.max() > 0.4: f, t, Sxx = spectrogram( x_filt[int(spec_begin):int(spec_end)], fs, nfft=500, noverlap=400, nperseg=500, window="blackmanharris", ) plt.pcolormesh(t, f, Sxx, cmap="gray_r", norm=NoNorm()) plt.axis(ymin=20000, ymax=120000) plt.axis("off") plt.savefig(f"./spectrograms/{call}_ch1.png", bbox_inches="tight", pad_inches=0)
import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from matplotlib.colors import NoNorm from PIL import ImageEnhance, Image image = mpimg.imread('im.jpg') implot = plt.imshow(image) plt.show() arr = image.mean(axis=-1) plt.imshow(arr, norm=NoNorm(), vmin=30, vmax=100) plt.show() image1 = ImageEnhance.Contrast(Image.fromarray(np.uint8(image))).enhance(50.0) plt.imshow(image1) plt.show() i_red, i_blue, i_green = image.copy(), image.copy(), image.copy() i_red[:, :, 1], i_red[:, :, 2] = 0, 0 plt.imshow(i_red) plt.show() i_blue[:, :, 0], i_blue[:, :, 1] = 0, 0 plt.imshow(i_blue) plt.show() i_green[:, :, 0], i_green[:, :, 2] = 0, 0 plt.imshow(i_green) plt.show() arr = image.mean(axis=-1) plt.imshow(arr, cmap=plt.get_cmap('gray'))
data = load(filename) # unpack arrays X1, X2 = data['arr_0'], data['arr_1'] # scale from [0,255] to [-1,1] X1 = (X1 - 127.5) / 127.5 X2 = (X2 - 127.5) / 127.5 return [X1, X2] dataset = load_real_samples('TestSet.npz') print('Loaded', dataset[0].shape, dataset[1].shape) dataset[0] = dataset[0][:10] dataset[1] = dataset[1][:10] SUBSIZE = int(np.sqrt(len(dataset[0]))) + 1 FIGSIZE = 7 plt.figure(figsize=(FIGSIZE, FIGSIZE)) for i in range(len(dataset[0])): rj_inp, rj_re = [dataset[0][i], dataset[1][i]] plt.subplot(SUBSIZE, SUBSIZE, i + 1) plt.imshow((1 + rj_inp) / 2) plt.axis('off') plt.figure(figsize=(FIGSIZE, FIGSIZE)) for i in range(len(dataset[0])): rj_inp, rj_re = [dataset[0][i], dataset[1][i]] rj_re = rj_re[:, :, 0] plt.subplot(SUBSIZE, SUBSIZE, i + 1) plt.imshow((1 + rj_re) / 2, cmap='gray', norm=NoNorm()) plt.axis('off') plt.show()
def create_figure(self, frameno=0, binning=1, dpi=None, stretch='log', vmin=1, vmax=5000, cmap='gray', data_col='FLUX', annotate=True, time_format='ut', show_flags=False, label=None): """Returns a matplotlib Figure object that visualizes a frame. Parameters ---------- frameno : int Image number in the target pixel file. binning : int Number of frames around `frameno` to co-add. (default: 1). dpi : float, optional [dots per inch] Resolution of the output in dots per Kepler CCD pixel. By default the dpi is chosen such that the image is 440px wide. vmin : float, optional Minimum cut level (default: 1). vmax : float, optional Maximum cut level (default: 5000). cmap : str, optional The matplotlib color map name. The default is 'gray', can also be e.g. 'gist_heat'. raw : boolean, optional If `True`, show the raw pixel counts rather than the calibrated flux. Default: `False`. annotate : boolean, optional Annotate the Figure with a timestamp and target name? (Default: `True`.) show_flags : boolean, optional Show the quality flags? (Default: `False`.) label : str Label text to show in the bottom left corner of the movie. Returns ------- image : array An array of unisgned integers of shape (x, y, 3), representing an RBG colour image x px wide and y px high. """ # Get the flux data to visualize flx = self.flux_binned(frameno=frameno, binning=binning, data_col=data_col) # Determine the figsize and dpi shape = list(flx.shape) shape = [shape[1], shape[0]] if dpi is None: # Twitter timeline requires dimensions between 440x220 and 1024x512 # so we make 440 the default dpi = 440 / float(shape[0]) # libx264 require the height to be divisible by 2, we ensure this here: shape[0] -= ((shape[0] * dpi) % 2) / dpi # Create the figureand display the flux image using matshow fig = pl.figure(figsize=shape, dpi=dpi) # Display the image using matshow ax = fig.add_subplot(1, 1, 1) if self.verbose: print('{} vmin/vmax = {}/{} (median={})'.format( data_col, vmin, vmax, np.nanmedian(flx))) if stretch == 'linear': stretch_fn = visualization.LinearStretch() elif stretch == 'sqrt': stretch_fn = visualization.SqrtStretch() elif stretch == 'power': stretch_fn = visualization.PowerStretch(1.0) elif stretch == 'log': stretch_fn = visualization.LogStretch() elif stretch == 'asinh': stretch_fn = visualization.AsinhStretch(0.1) else: raise ValueError('Unknown stretch: {0}.'.format(stretch)) transform = (stretch_fn + visualization.ManualInterval(vmin=vmin, vmax=vmax)) flx_transform = 255 * transform(flx) # Make sure to remove all NaNs! flx_transform[~np.isfinite(flx_transform)] = 0 ax.imshow(flx_transform.astype(int), aspect='auto', origin='lower', interpolation='nearest', cmap=cmap, norm=NoNorm()) if annotate: # Annotate the frame with a timestamp and target name? fontsize = 3. * shape[0] margin = 0.03 # Print target name in lower left corner if label is None: label = self.objectname txt = ax.text(margin, margin, label, family="monospace", fontsize=fontsize, color='white', transform=ax.transAxes) txt.set_path_effects([ path_effects.Stroke(linewidth=fontsize / 6., foreground='black'), path_effects.Normal() ]) # Print a timestring in the lower right corner txt2 = ax.text(1 - margin, margin, self.timestamp(frameno, time_format=time_format), family="monospace", fontsize=fontsize, color='white', ha='right', transform=ax.transAxes) txt2.set_path_effects([ path_effects.Stroke(linewidth=fontsize / 6., foreground='black'), path_effects.Normal() ]) # Print quality flags in upper right corner if show_flags: flags = self.quality_flags(frameno) if len(flags) > 0: txt3 = ax.text(margin, 1 - margin, '\n'.join(flags), family="monospace", fontsize=fontsize * 1.3, color='white', ha='left', va='top', transform=ax.transAxes, linespacing=1.5, backgroundcolor='red') txt3.set_path_effects([ path_effects.Stroke(linewidth=fontsize / 6., foreground='black'), path_effects.Normal() ]) ax.set_xticks([]) ax.set_yticks([]) ax.axis('off') fig.subplots_adjust(left=0.0, right=1.0, top=1.0, bottom=0.0) fig.canvas.draw() return fig
def main(): # Parse flags cfg = forge.config() cfg.num_workers = 0 # Set manual seed torch.manual_seed(cfg.seed) np.random.seed(cfg.seed) # Make CUDA operations deterministic torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # Get data loaders train_loader, _, _ = fet.load(cfg.data_config, cfg) # Optimally distinct RGB colour palette (15 colours) colours = json.load(open('utils/colour_palette15.json')) # Visualise for x in train_loader: fig, axes = plt.subplots(2, cfg.batch_size, figsize=(20, 10)) for f_idx, field in enumerate(['input', 'instances']): for b_idx in range(cfg.batch_size): axes[f_idx, b_idx].axis('off') if field not in x: continue img = x[field] # Colour instance masks if field == 'instances': img_list = [] for b_idx in range(img.shape[0]): instances = img[b_idx, :, :, :] img_r = torch.zeros_like(instances) img_g = torch.zeros_like(instances) img_b = torch.zeros_like(instances) ins_idx = 0 for ins in range(instances.max().numpy()): ins_map = instances == ins + 1 if ins_map.any(): img_r[ins_map] = colours['palette'][ins_idx][0] img_g[ins_map] = colours['palette'][ins_idx][1] img_b[ins_map] = colours['palette'][ins_idx][2] ins_idx += 1 img_list.append(torch.cat([img_r, img_g, img_b], dim=0)) img = torch.stack(img_list, dim=0) for b_idx in range(cfg.batch_size): np_img = np.moveaxis(img.data.numpy()[b_idx], 0, -1) if img.shape[1] == 1: axes[f_idx, b_idx].imshow(np_img[:, :, 0], norm=NoNorm(), cmap='gray') elif img.shape[1] == 3: axes[f_idx, b_idx].imshow(np_img) manager = plt.get_current_fig_manager() manager.resize(*manager.window.maxsize()) plt.show()
def make2DPlots(snr_coded_list, snr_sns_list, snr_strobe_list, axis_values_list, labels, ax=None, plot_type='rgb', use_db=False, cmap='viridis', context='', title=None, clim=None, units=None, debug=False, show_hatches=False, show_divider=True, divider_color='w', include_comparison=False, figure_aspect_ratio=1.3, parameter_is_log_scaled=False, x_is_log_scaled=False, contour_pixel_offset=0, interpolation='gaussian', show_colorbar=False, normalize_pixels=True, show_labels_y=True, show_labels_x=True, show_legend=True, abbrev_label=False, log_colors=True, text_list=None): # Initialize lists of SNRS snr_list = [np.asarray(snr_sns_list).T, np.asarray(snr_strobe_list).T, np.asarray(snr_coded_list).T] snr_list_sns = [np.asarray(snr_sns_list).T] snr_list_cont = [np.asarray(snr_strobe_list).T, np.asarray(snr_coded_list).T] argmax_array = np.argmax(snr_list, axis=0) max_array = np.maximum.reduce(snr_list) # Reduce Arrays if Abbreviating Labels if abbrev_label == 'optical': argmax_array[argmax_array < 1] = 0 argmax_array = argmax_array > 1 max_array = np.maximum.reduce(snr_list_cont) elif abbrev_label == 'mechanical': argmax_array = argmax_array > 0 max_array = np.maximum.reduce(snr_list_sns + [np.maximum.reduce(snr_list_cont)]) # Initialize arrays to plot imshow_array = None to_contour = None im = None if 'bar' in plot_type: if isinstance(axis_values_list[1][0], tuple): # redo y labels yticklabels = [] for pair in axis_values_list[1]: yticklabels.append(str(pair[0])+'x / '+str(np.round(pair[1],2))) else: yticklabels = axis_values_list[1] # redo y positions new_y = np.arange(0,len(axis_values_list[1])+2) axis_values_list = (axis_values_list[0],new_y) # Make figure if plot_type in ['rgb', 'cmy', 'rgb_max', 'cmy_max']: # Create RGB image with the correct dimensions rgb_array = np.asarray(snr_list) rgb_array = np.transpose(rgb_array, (1,2,0)) if 'max' in plot_type: max_ind = np.argmax(rgb_array, 2) max_array = np.max(rgb_array, 2) max_array = max_array rgb_array = np.asarray([np.zeros_like(max_array)] * 3).transpose(1, 2, 0) for ind in range(3): rgb_array[:, :, ind][max_ind == ind] = max_array[max_ind == ind] rgb_array[rgb_array == 0.0] = np.min(rgb_array) rgb_array -= np.min(rgb_array) rgb_array /= np.max(rgb_array) for ind in range(3): rgb_array[:, :, ind] /= np.mean(rgb_array[:, :, ind], 1)[:, np.newaxis] elif normalize_pixels: rgb_array /= np.max(rgb_array, 2)[:, :, np.newaxis] rgb_array = rgb_array if plot_type == 'cmy': rgb_array = 1 - rgb_array # parameters for figure show_colorbar = False imshow_array = rgb_array to_contour = None if 'combined' in plot_type: imshow_array = max_array elif 'regions' in plot_type: imshow_array = argmax_array.astype(np.float) imshow_array += (max_array > 0).astype(np.float) log_colors = False if 'regions' in plot_type: to_contour = argmax_array contour_x = axis_values_list[0].flatten() - contour_pixel_offset contour_y = axis_values_list[1].flatten() - contour_pixel_offset if to_contour is not None: if abbrev_label == 'mechanical': contour_lim = [0.5, 1.5] hatches = ['/', '-'] elif abbrev_label == 'optical': contour_lim = [0.5, 1.5] hatches = ['/', '\\'] else: contour_lim = [0.5, 1.5, 2.5] hatches = ['-', '/', '\\'] if ax is None: fig, ax = plt.subplots() # color image background if imshow_array is not None: from matplotlib.colors import LogNorm, NoNorm if log_colors: cnorm = LogNorm() else: cnorm = NoNorm() if 'bar' not in plot_type: meshgrid = np.meshgrid(axis_values_list[0], axis_values_list[1]) im = ax.scatter(meshgrid[0], meshgrid[1], c=imshow_array, norm=None, cmap=cmap, edgecolors='none', marker='s',s=5, rasterized=True) else: meshgrid = np.meshgrid(axis_values_list[0], axis_values_list[1][1:-1]) im = ax.scatter(meshgrid[0], meshgrid[1], c=imshow_array, norm=cnorm, cmap=cmap, edgecolors='none', marker='s', s=5, rasterized=True) from matplotlib.patches import Rectangle # require that cmap was actual cmap argument get_rgba = lambda x: cmap(cnorm(x)) # Add rectangles meshgrid_to_diff = np.meshgrid(np.hstack([axis_values_list[0],axis_values_list[0][-1]]), axis_values_list[1][1:-1]) widths = np.diff(meshgrid_to_diff[0],axis=1).flatten() h = 0.5 #np.diff(meshgrid[1],axis=0).flatten() # (np.amax(axis_values_list[1]) - np.amin(axis_values_list[1])) / len(axis_values_list[1]) for x,y,c,w in zip(meshgrid[0].flatten(), meshgrid[1].flatten(), imshow_array.flatten(), widths): ax.add_patch(Rectangle(xy=(x-w/2, y-h/2), width=w*1.5, height=h, linewidth=0, color=get_rgba(c), fill=True, rasterized=True)) if yticklabels is None: yticklabels = axis_values_list[1][1:-1] if 'regions' in plot_type: for i,row in enumerate(argmax_array): # finding x position boundary = np.where(np.hstack([0, np.diff(row)]))[0] y = axis_values_list[1][1+i] w = 10; h = 1 for i in boundary: x = axis_values_list[0][i] w = 0.1 * x ax.add_patch(Rectangle(xy=(x-w/2, y-h/2), width=w, height=h, linewidth=0, color='black', fill=True)) to_contour = None if parameter_is_log_scaled: ax.set_yscale("log") if x_is_log_scaled: ax.set_xscale("log") ax.autoscale(enable=True, axis='both', tight=True) if clim is not None: im.set_clim(clim) if show_colorbar: plt.colorbar(im) ax.set_ylim(min(axis_values_list[1]), max(axis_values_list[1])) ax.set_xlim(min(axis_values_list[0]), max(axis_values_list[0])) # draw boundary for image regions if to_contour is not None: ax.contour(contour_x, contour_y, to_contour, contour_lim, colors=divider_color, linewidths=2) # Show hatches, if desired if show_hatches: ax.contourf(contour_x, contour_y, to_contour, contour_lim, hatches=hatches, extend='both', alpha=0) if title is not None: ax.set_title(title) if show_labels_y: if units: ax.set_ylabel(labels[1] + ' (%s)' % units) else: ax.set_ylabel(labels[1]) if show_labels_x: ax.set_xlabel(labels[0]) # Add legend if show_legend: if not abbrev_label or abbrev_label == 'mechanical': ax.scatter([-1], [-1], marker='s', s=100, facecolor='white', hatch=3*hatches[1], label='SNS') if not abbrev_label or abbrev_label == 'optical': ax.scatter([-1], [-1], marker='s', s=100, facecolor='white', hatch=3*hatches[0], label='Strobed') if not abbrev_label or abbrev_label == 'optical': ax.scatter([-1], [-1], marker='s', s=100, facecolor='white', hatch=3*hatches[1], label='Coded') if abbrev_label == 'mechanical': ax.scatter([-1], [-1], marker='s', s=100, facecolor='white', hatch=3*hatches[0], label='Continuous') ax.set_ylim((min(axis_values_list[1]), max(axis_values_list[1]))) ax.set_xlim((min(axis_values_list[0]), max(axis_values_list[0]))) ax.legend() if 'bar' in plot_type: ax.set_yticks(axis_values_list[1][1:-1]) ax.set_yticklabels(yticklabels) if text_list is not None: for text, pos in text_list: ax.text(pos[0], pos[1], text, color='black', size=18) return im
def texture_seg(self, src_gray): """ Genetate texture feature images. Input: The gray scaled image. """ # Store the number of features contained. num_texture_feature = 0 # cv2.getGaborKernel(ksize, sigma, theta, lambda, gamma, psi, ktype) # For example, # g_kernel = cv2.getGaborKernel(\ # (21, 21), 8.0, np.pi/4, 10.0, 0.5, 0, ktype=cv2.CV_32F) # ksize - size of gabor filter (n, n) # sigma - standard deviation of the gaussian function # theta - orientation of the normal to the parallel stripes # for lawn, should be 0.0 rad. # lambda - wavelength of the sinusoidal factor # gamma - spatial aspect ratio # psi - phase offset # ktype - type and range of values that each pixel in the gabor kernel can hold # g_kernel = cv2.getGaborKernel((15, 15), 7.0, 3.14159/12*0, 2.5, 1.0, 0, ktype=cv2.CV_32F) ksize = 15 sigma = 4.0 theta_max = np.pi theta_seq = np.pi/6 theta_num = int(np.floor(theta_max/theta_seq)+1) wavelength_max = ksize/2 wavelength_min = 2.5 wavelength_num = 6 wavelength_seq = (wavelength_max - wavelength_min)/wavelength_num gamma = 1.0 psi = 0.0 # Stored for plotting the gaber filters in the spatial domain. gabor_kernels = [] theta_arr = [] wavelength_arr = [] # Iterate over both wavelength and theta. for j in range(theta_num): theta = j*theta_seq theta_arr.append( np.degrees(theta) ) for k in range(wavelength_num): wavelength = wavelength_min + k*wavelength_seq if (j == 0): wavelength_arr.append(wavelength) g_kernel = cv2.getGaborKernel((ksize, ksize), sigma, theta, wavelength, gamma, psi, ktype=cv2.CV_32F) filtered_img = cv2.filter2D(src_gray, cv2.CV_8UC3, g_kernel) # Stored for plotting the gaber filters in the spatial domain. gabor_kernels.append(g_kernel) # gray_bound_low, gray_bound_up = self.color_sample(filtered_img, self.select_precentage) # gray_mask, self.gray_threshold = self.color_mask(self.src, gray_bound_low, gray_bound_up) # filtered_img = cv2.cvtColor(filtered_img, cv2.COLOR_BGR2GRAY) logger.debug('Theta = {}, wavelength = {}.'.format(theta, wavelength)) if (self.texture_feature_valid(filtered_img) == 0): if (self.feature_mat_empty): filtered_img = self.feature_normalize(filtered_img, self.feature_range_texture) self.feature_mat = filtered_img.reshape((-1, 1)) self.feature_mat_empty = False num_texture_feature = 1 else: filtered_img = self.feature_normalize(filtered_img, self.feature_range_texture) self.feature_append(self.feature_mat, filtered_img, 1) logger.debug('\tThe feature matrix now has the shape {}.'.format(self.feature_mat.shape)) num_texture_feature += 1 # cv2.imshow('Filtered Image', filtered_img) # cv2.imshow('Filtered Image Thresholded', gray_mask) # cv2.waitKey(0) # To plot the Gabor filters. if(self.show_gabor_filters): # plt.figure(self.fig_num) # self.fig_num += 1 i = 0 # fig, axs = plt.subplots(ncols=wavelength_num, nrows=theta_num, gridspec_kw={'hspace': 0.0, 'wspace': 0.0}) fig, axs = plt.subplots( nrows=theta_num, ncols=wavelength_num, figsize=(6, 6) ) plt.setp(axs.flat, xticks=[], yticks=[]) print(theta_arr) print(wavelength_arr) # plt.setp(axes.flat, xticks=[], yticks=[]) for ax in axs.flat: k = gabor_kernels[i] h, w = k.shape[:2] k = cv2.resize(k, (3*w, 3*h), interpolation=cv2.INTER_CUBIC) # ax.axis('off') ax.imshow(k, cmap='gray', norm=NoNorm()) i += 1 for ax, wl in zip(axs[-1], wavelength_arr): ax.set_xlabel('{0}'.format(wl)) for ax, angle in zip(axs[:, 0], theta_arr): ax.set_ylabel( '{0}'.format(angle) ) # for ax, ve in zip(axes[0], [0.1, 1, 10]): # ax.set_title('{0}'.format(ve), size=18) # for ax, mode in zip(axes[:, 0], ['Hillshade', 'hsv', 'overlay', 'soft']): # ax.set_ylabel(mode, size=18) plt.suptitle('Gabor filters in the spatial domain') # or plt.suptitle('Main title') fig.text(0.5, 0.04, 'Wavelength (pixel)', ha='center') fig.text(0.04, 0.5, 'Angle (degree)', va='center', rotation='vertical') # fig.tight_layout() plt.show() return num_texture_feature
def plot_raster( fname_base, interval='full', plot_relative_position=True, fignum=1, program='python', flipx=False, flipy=True, normalize=True ): """ Plot a raster scan acquired using either the Excel program or (in the future) the python program. The core of this function is the same either way; the only reason for including the "program" flag is that I didn't want to be tied to the horiz, vert encoding process for the python program. """ plt.figure( fignum ) if '*.SPE' in fname_base: files = glob.glob( fname_base ) else: files = glob.glob( fname_base + '*.SPE' ) # get a list of all spe files if len(files) == 0: # nothing to plot return None files.sort() # example file name: # PbS10_wire06_vert9083_horiz12796_1.txt # first just get the range of horizontal and vertical locations: vlist = [] hlist = [] if program == 'python': for fullfname in files: fname = str( os.path.splitext( os.path.basename( fullfname ) )[0] ) horiz = float( fname.split('x')[1].split('_')[0] ) # this is an absolute position in nanometers hlist.append( horiz ) vert = float( fname.split('y')[1] ) vlist.append( vert ) elif program == 'excel': raise ValueError( 'now only supporting python-generated data' ) for fname in files: vert = float( fname.split('vert')[1].split('_')[0] ) # this is an absolute position in nanometers vlist.append( vert ) horiz = float( fname.split('horiz')[1].split('.')[0] ) hlist.append( horiz ) vlist = list( set(vlist) ) # remove duplicate elements vlist.sort() vcen = centers_to_corners( vlist ) hlist = list( set(hlist) ) hlist.sort() hcen = centers_to_corners( hlist ) if plot_relative_position: " plot relative distance, not absolute piezo position" vcen = vcen-vcen.min() hcen = hcen-hcen.min() # these step across in horizontal positions for each vertical position # (i.e. they go along a row before switching rows) dist. are in nm lum = np.zeros([ len(vlist), len(hlist) ]) # initialize matrix for holding luminescence data fname_matrix = [ [0]*len(hlist) for i in range(len(vlist)) ] # initialize matrix for holding names of files for fullfname in files: fname = str( os.path.splitext( os.path.basename( fullfname ) )[0] ) horiz = float( fname.split('x')[1].split('_')[0] ) # this is an absolute position in nanometers vert = float( fname.split('y')[1] ) wavelen, d = spe.getSpectrum( fullfname ) lum[ vlist.index(vert), hlist.index(horiz) ] = ( np.sum(d) if type(interval) is str else np.sum(d[interval]) ) fname_matrix[vlist.index(vert)][hlist.index(horiz)] = fullfname xlabel('Position ($\mu m$)') ylabel('Position ($\mu m$)') if flipx: hpoints = (-hcen+hcen.max())/1000 else: hpoints = hcen/1000 if flipy: vpoints =( -vcen+vcen.max())/1000 else: vpoints = vcen/1000 if normalize: plot = pcolormesh( hpoints, vpoints, lum, cmap='copper' ) else: from matplotlib.colors import NoNorm plot = plt.pcolormesh( hpoints, vpoints, lum/lum.max(), cmap='copper', norm=NoNorm() ) #pcolormesh( hcen/1000, vcen/1000, (lum-xpol_min)/(lum.max()-xpol_min), cmap='copper', norm=NoNorm() ) plt.axis([ hpoints.min(), hpoints.max(), vpoints.min(), vpoints.max() ]) ax = plt.gca() ax.set_aspect('equal') ax.axis('image') # not sure what this does, but it keeps ginput from changing the axes after a click... plt.show() return plot, (fname_matrix, vcen/1000, hcen/1000)