def plot_data_lines(lidar, results=None, offset=None, cells=None, intensity=None): """ Plot point cloud and boundaries @return: None """ fig = plt.figure() plt.set_cmap('rainbow') plt.title("Final Product") ax = fig.add_subplot(111, projection='3d') #, axisbg='black') # colors = (lidar[ELE] / lidar[ELE].max()) * 255 colors = lidar[INT] #/255. ax.scatter(lidar[LAT], lidar[LONG], zs=lidar[ELE], zdir='z', marker='+', c=colors, s=1) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') m = np.std(lidar[ELE]) print lidar[LAT].max(), lidar[LONG].max() inter_results = grid_to_map_lines(cells, offset, results) for line in inter_results: xc1, xc2, yc1, yc2, zc1, zc2 = line[0][0],line[0][1],line[1][0],line[1][1],line[2][0],line[2][1] ax.plot([xc1, xc2], [yc1, yc2], zs=[zc1+m, zc2+m], zdir='z') # plt.savefig("demo.png") plt.show() return inter_results
def plot_band_array(band_array,refl_extent,colorlimit,ax=plt.gca(),title='',cbar ='on',cmap_title='',colormap='spectral'): '''plot_band_array reads in and plots a single band of a reflectance array -------- Parameters -------- band_array: flightline array of reflectance values, created from h5refl2array function refl_extent: extent of reflectance data to be plotted (xMin, xMax, yMin, yMax) - use metadata['extent'] from h5refl2array function colorlimit: range of values to plot (min,max). Best to look at the histogram of reflectance values before plotting to determine colorlimit. ax: optional, default = current axis title: string, optional; plot title cmap_title: string, optional; colorbar title colormap: string, optional; see https://matplotlib.org/examples/color/colormaps_reference.html for list of colormaps -------- Returns -------- plots flightline array of single band of reflectance data -------- See Also -------- plot_subset_band: plots a subset of a full flightline reflectance band array Example: -------- plot_band_array(SERC_b56_clean,sercRefl_md['extent'],(0,0.3),ax,title='SERC Band 56 Reflectance',cmap_title='Reflectance',colormap='spectral') ''' plot = plt.imshow(band_array,extent=refl_extent,clim=colorlimit); if cbar == 'on': cbar = plt.colorbar(plot,aspect=40); plt.set_cmap(colormap); cbar.set_label(cmap_title,rotation=90,labelpad=20) plt.title(title); ax = plt.gca(); ax.ticklabel_format(useOffset=False, style='plain'); #do not use scientific notation # rotatexlabels = plt.setp(ax.get_xticklabels(),rotation=90); #rotate x tick labels 90 degrees
def findall2(all_trees,all_files): #show 10 candidates k=10 for files in all_files: for f in files: temp={'ds':[],'ids':[],'files':[]} fsg=getHash3(f) for tree in all_trees: ds,ids=tree.query(fsg,k) temp['ds'].append(ds) temp['ids'].append(ids) temp['files'].append(files) id_sort=np.argsort(temp['ds']) sort_d=temp['ds'][id_sort[0:k]] sort_ids=temp['ids'][id_sort[0:k]] sort_files=temp['files'][id_sort[0:k]] plt.figure(1) for i in xrange(k): print "%03d dis: %.3f %s"%(sort_ids[i],sort_d[i],sort_files[i]) plt.subplot(2,5,i+1) plt.title("%03d dis: %.3f"%(sort_ids[i],sort_d[i]),fontsize=10) im_icon=np.array(Image.open(sort_files[i]).convert('L')) plt.imshow(im_icon) plt.axis('off') plt.set_cmap('gray') plt.show() plt.ginput(1)
def plotTwoContours(contour, contour2, diffmap, mapName1="map1", mapName2="map2", colormap="jet", plot_scalebar=False): #DEBUG: #max_range = 0.07 max_range = max(diffmap.max(),abs(diffmap.min())) norm = colors.Normalize(vmin=-max_range, vmax=max_range) print('max_range is '+str(max_range)) title = mapName1+' - '+mapName2 filename = title+'.pdf' fig = plt.figure() plt.title(title) plt.hold(True) plt.imshow(diffmap, origin='upper', norm=norm) ax = plt.axes() if plot_scalebar: addScaleBar(ax) else: scaleTicks(ax) #if(colormap == "rwb") plt.set_cmap(colormap) plt.colorbar() plt.contour(contour, [0], colors='r') #plt.contour(image2, [0], colors='b') plt.contour(contour2, [0], colors='b') plt.hold(False) plt.savefig(filename) #plt.show() return diffmap
def dim_sensitivity_plot(x, Y, fname, show_legend=True): plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.figure(figsize=(3, 3)) plt.xlabel('$d$', size=FONTSIZE) plt.ylabel('ROC AUC', size=FONTSIZE) plt.set_cmap('Set2') lines = [] for i, label in enumerate(KEYS): line_data = Y.get(label) if line_data is None: continue line, = plt.plot(x, line_data, label=label, marker=MARKERS[i], markersize=0.5 * FONTSIZE, color=COLORS[i]) lines.append(line) if show_legend: plt.legend(handles=lines) plt.legend(loc='lower right') plt.xscale('log', basex=2) plt.xticks(x, [str(y) for y in x], size=FONTSIZE) plt.yticks(size=FONTSIZE) plt.tight_layout() plt.savefig(fname)
def display_data(images, order='F'): # Select as many images as can neatly fit in a square display. w = int(math.sqrt(len(images))) h = int(len(images) / w) images = images[:w*h] print("Displaying images in a {}x{} array.".format(h, w)) size = int(math.sqrt(images[0].shape[0])) combined_image = np.zeros((size * h, size * w)) for i in range(h): for j in range(w): image = images[i * w + j] start_x = i * size; start_y = j * size; combined_image[start_y:(start_y + size), start_x:(start_x + size)] = image.reshape((size, size), order=order) # NOTE: IF this is failing to display anything, there's a known issue on Ubuntu. # See: # http://www.pyimagesearch.com/2015/08/24/resolved-matplotlib-figures-not-showing-up-or-displaying/ plt.set_cmap('gray') plt.axis('off') plt.imshow(combined_image, interpolation='nearest') plt.show()
def main(): for unitFile in os.listdir(sourceFolder): if os.path.isdir(sourceFolder+unitFile): unitName = unitFile.rsplit('_', 1)[0] print unitName staMatrixFile = scipy.io.loadmat(sourceFolder+unitFile+'/stavisual_lin_array_'+unitName+'.mat') staMatrix = staMatrixFile['STAarray_lin'] xLength = staMatrix.shape[0] yLength = staMatrix.shape[1] zLength = staMatrix.shape[2] for zAxis in range(zLength): print 'desde disco' fig = plt.figure() fig.set_size_inches(1, 1) data = staMatrix[:,:,zAxis] #plt.pcolormesh( staMatrix[:,:,zAxis],vmin = 0,vmax = 255, cmap=cm.jet ) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.set_cmap(cm.jet) ax.imshow(data, aspect = 'auto') plt.savefig(outputFolder+unitName+str(zAxis)+".png",format='png',dpi=31) plt.close() return 0
def doubleslit(b=0.1,a=0.4,lambda_1=632,z=0.5): """ Return a Young's doubleslit(Frauhofer Diffraction) Input: -------------------------------- b: slit of width in mm a: slit separation of in mm lambda_1: wavelength in nm z: slit-to-screen distance in m. """ lambda_1 = float(lambda_1) theta = __np__.linspace(-0.04,0.04,1000) theta1 = __np__.ones(100) [theta,theta1] = __np__.meshgrid(theta,theta1) beta = __np__.pi*(b/1000)/(lambda_1/(10**9))*__sin__(theta) alpha = __np__.pi*(a/1000)/(lambda_1/(10**9))*__sin__(theta) y = 4*(__sin__(beta)**2/(beta**2)*__cos__(alpha)**2) fig = __plt__.figure(1,figsize=(12,8), dpi=80) __plt__.imshow(-y) __plt__.set_cmap('Greys') __plt__.show() theta = __np__.linspace(-0.04,0.04,1000) beta = __np__.pi*(b/1000)/(lambda_1/(10**9))*__sin__(theta) alpha = __np__.pi*(a/1000)/(lambda_1/(10**9))*__sin__(theta) y = 4*(__sin__(beta)**2/(beta**2)*__cos__(alpha)**2) y1 = 4*__sin__(beta)**2/(beta**2) fig = __plt__.figure(2,figsize=(12, 8), dpi=80) __plt__.plot(theta*z*1000,y) __plt__.plot(theta*z*1000,y1,"g--") __plt__.show()
def _vis_readout_maps(outputs, global_step, output_dir, metric_summary, N): # outputs is [gt_map, pred_map]: if N >= 0: outputs = outputs[:N] N = len(outputs) plt.set_cmap('jet') fig, axes = utils.subplot(plt, (N, outputs[0][0].shape[4]*2), (5,5)) axes = axes.ravel()[::-1].tolist() for i in range(N): gt_map, pred_map = outputs[i] for j in [0]: for k in range(gt_map.shape[4]): # Display something like the midpoint of the trajectory. id = np.int(gt_map.shape[1]/2) ax = axes.pop(); ax.imshow(gt_map[j,id,:,:,k], origin='lower', interpolation='none', vmin=0., vmax=1.) ax.set_axis_off(); if i == 0: ax.set_title('gt_map') ax = axes.pop(); ax.imshow(pred_map[j,id,:,:,k], origin='lower', interpolation='none', vmin=0., vmax=1.) ax.set_axis_off(); if i == 0: ax.set_title('pred_map') file_name = os.path.join(output_dir, 'readout_map_{:d}.png'.format(global_step)) with fu.fopen(file_name, 'w') as f: fig.savefig(f, bbox_inches='tight', transparent=True, pad_inches=0) plt.close(fig)
def make_spectrogram(dat, npts, fs=333333.3, winwidth=None, window=None, fstart=0, fstop=120000, fstep=5000, cmap='gist_heat_r', **kwargs): tstep = int(round(dat.shape[0] / float(npts))) winwidth = winwidth or tstep if window: windowa = np.linspace(0, 1, winwidth) windowa = np.concatenate([window, window[::-1]]) nft = winwidth + 1 ind = np.arange(fstart, fstop, fstep) ind = nft * ind / (fs / 2.0) ind = ind.astype(np.int32)[::-1] xind = np.arange(winwidth, dat.shape[0] - winwidth, tstep).astype(np.int32) ft = np.zeros((xind.shape[0], ind.shape[0])) for i in range(xind.shape[0]): d = dat[xind[i] - winwidth:xind[i] + winwidth] #warning, very strange behavior of rfft for 2d arrays, #even if shape is Nx1 or 1xN. if window: d = d * windowa d = np.fft.rfft(d) ft[i, :] = abs(d[ind][range(d[ind].shape[0] - 1, -1, -1)]) plt.imshow(ft.transpose(), aspect='auto') if cmap: plt.set_cmap(cmap) return ft
def plot_summary(self): import matplotlib import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,8)) ax = plt.axes((0.08, 0.08, 0.87, 0.80)) plt.set_cmap("Spectral") # Get all candidates and sort by sigma allcands = self.get_all_cands() sigmas = Num.array([c.sigma for c in allcands]) isort = sigmas.argsort() sigmas = sigmas[isort] freqs = Num.array([c.f for c in allcands])[isort] dms = Num.array([c.DM for c in allcands])[isort] numharms = Num.array([c.numharm for c in allcands])[isort] # Plot the all candidates plt.scatter(freqs, dms, s=8+sigmas**1.7, c=Num.log2(numharms), \ marker='o', alpha=0.7, zorder=-1) # Add colorbar fmtr = matplotlib.ticker.FuncFormatter(lambda x, pos: "%d" % 2**x) cb = plt.colorbar(ticks=(0,1,2,3,4), format=fmtr) cb.set_label("Num harmonics summed") plt.xscale('log', base=10.0) plt.xlim(0.5, 10000) plt.ylim(-10, 1200) plt.xlabel("Freq (Hz)") plt.ylabel(r"DM (pc cm$^{-3}$)") return fig
def compare_spectra(): import mywfc3.stgrism as st import unicorn ### Fancy colors import seaborn as sns import matplotlib.pyplot as plt cmap = sns.cubehelix_palette(as_cmap=True, light=0.95, start=0.5, hue=0.4, rot=-0.7, reverse=True) cmap.name = 'sns_rot' plt.register_cmap(cmap=cmap) sns.set_style("ticks", {"ytick.major.size":3, "xtick.major.size":3}) plt.set_cmap('sns_rot') #plt.gray() fig = st.compare_methods(x0=787, y0=712, v=np.array([-1.5,4])*0.6, NX=180, NY=40, direct_off=100, final=True, mask_lim = 0.02) #fig.tight_layout() unicorn.plotting.savefig(fig, '/tmp/compare_model_star.pdf', dpi=300) fig = st.compare_methods(x0=485, y0=332, v=np.array([-1.5,4])*0.2, NX=180, NY=40, direct_off=100, final=True, mask_lim = 0.1) unicorn.plotting.savefig(fig, '/tmp/compare_model_galaxy.pdf', dpi=300) fig = st.compare_methods(x0=286, y0=408, v=np.array([-1.5,4])*0.08, NX=180, NY=40, direct_off=100, final=True, mask_lim = 0.1) unicorn.plotting.savefig(fig, '/tmp/compare_model_galaxy2.pdf', dpi=300) fig = st.compare_methods(x0=922, y0=564, v=np.array([-1.5,4])*0.2, NX=180, NY=40, direct_off=100, final=True, mask_lim = 0.15) unicorn.plotting.savefig(fig, '/tmp/compare_model_galaxy3.pdf', dpi=300)
def produce_regions(masks, visualize=False): """given the proposal segmentation masks for an image as a [width, height, proposal_num] matrix outputs all regions in the image""" width, height, n_prop = masks.shape t = ('u8,'*int(np.math.ceil(float(n_prop) / 64)))[:-1] bv = np.zeros((width, height), dtype=np.dtype(t)) for i in range(n_prop): m = masks[:, :, i] a = 'f%d' % (i / 64) h = m * np.long(2 ** (i % 64)) if n_prop >= 64: bv[a] += h else: bv += h un = np.unique(bv) regions = np.zeros((width, height), dtype="uint16") for i, e in enumerate(un): regions[bv == e] = i if visualize: plt.figure() plt.imshow(regions) plt.set_cmap('prism') plt.colorbar() return regions
def show_network(images, side_length, sample=1): """ Expects images to be (n_pixels, n_images). n_pixels should be == side_length ** 2 """ n_images = int(images.shape[1] * sample) cols = int(math.sqrt(n_images)) rows = math.ceil(n_images / cols) # padding image_size = side_length + 1 output = np.zeros((image_size * rows, image_size * cols)) image_mask = np.random.randint(0, images.shape[1], n_images) norm = Normalize() for i, img in enumerate(image_mask): this_image = images[:, img].reshape((side_length, side_length)).copy() # Center and normalize this_image -= this_image.mean() this_image = norm(this_image) # Get offsets offset_col = image_size * (i % cols) offset_col_end = offset_col + image_size - 1 offset_row = image_size * (math.floor(i / cols)) offset_row_end = offset_row + image_size - 1 output[offset_row:offset_row_end, offset_col:offset_col_end] = this_image pyplot.imshow(output) pyplot.set_cmap(cm.gray) pyplot.show()
def getHash(im_file): im = np.array(Image.open(im_file).convert('L')) f=np.fft.fft2(im) rmax,cmax=f.shape sg_r=np.zeros((2*wd,wd)) sg_r[0:wd,:]=np.abs(f.real[0:wd,0:wd]) sg_r[wd:2*wd,:]=np.abs(f.real[rmax-wd:rmax,0:wd]) sg_i=np.zeros((2*wd,wd)) sg_i[0:wd,:]=np.abs(f.imag[0:wd,0:wd]) sg_i[wd:2*wd,:]=np.abs(f.imag[rmax-wd:rmax,0:wd]) bsg=np.zeros((2*wd,2*wd-2),dtype=bool) bsg[:,0:wd-1]=sg_r[:,0:wd-1]<sg_r[:,1:wd] bsg[:,wd-1:2*wd-2]=sg_i[:,0:wd-1]<sg_i[:,1:wd] return bsg f2=np.zeros((rmax,cmax))+1j*np.zeros((rmax,cmax)) f2.real[0:wd,0:wd-1]=bsg[0:wd,0:wd-1] f2.imag[wd:2*wd,0:wd-1]=bsg[0:wd,wd-1:2*wd-2] f2.real[rmax-wd:rmax,0:wd-1]=bsg[wd:2*wd,0:wd-1] f2.imag[rmax-wd:rmax,0:wd-1]=bsg[wd:2*wd,wd-1:2*wd-2] #plt.close("all") plt.figure() plt.imshow(bsg,interpolation='none') plt.set_cmap("gray")
def example_dct2(): import scipy.ndimage as sn import matplotlib.pyplot as plt name = os.path.join(path, 'autumn.gif') rgb = np.asarray(sn.imread(name), dtype=np.float16) # np.fft.fft(rgb) print(np.max(rgb), np.min(rgb)) plt.set_cmap('jet') J = dctn(rgb) irgb = idctn(J) print(np.abs(rgb-irgb).max()) plt.imshow(np.log(np.abs(J))) # plt.colorbar() #colormap(jet), colorbar plt.show('hold') v = np.percentile(np.abs(J.ravel()), 10.0) print(len(np.flatnonzero(J)), v) J[np.abs(J) < v] = 0 print(len(np.flatnonzero(J))) plt.imshow(np.log(np.abs(J))) plt.show('hold') K = idctn(J) print(np.abs(rgb-K).max()) plt.figure(1) plt.imshow(rgb) plt.figure(2) plt.imshow(K, vmin=0, vmax=255) plt.show('hold')
def test_mask_loss_sobel(): th_mask, th_img = T.tensor4(), T.tensor4() ml = mask_loss_sobel(th_mask, th_img) mask_loss = theano.function([th_mask, th_img], [ml.loss] + list(ml.sobel_mask) + list(ml.sobel_img)) mask_idx = next(masks(1)) image_ok = 0.5 * np.ones_like(mask_idx) image_ok[mask_idx > MASK["IGNORE"]] = 1 image_ok[mask_idx < MASK["BACKGROUND_RING"]] = 0 print() loss, sobel_mask_x, sobel_mask_y, sobel_img_x, sobel_img_y = \ mask_loss(mask_idx, image_ok) plt.set_cmap('gray') plt.subplot(221) plt.imshow(sobel_mask_x[0, 0]) plt.subplot(222) plt.imshow(sobel_mask_y[0, 0]) plt.colorbar() plt.subplot(223) plt.imshow(sobel_img_x[0, 0]) plt.subplot(224) plt.imshow(sobel_img_y[0, 0]) plt.colorbar() plt.savefig("mask_loss_sobel.png") print() print("mask_loss: {}".format(mask_loss(mask_idx, image_ok))) assert loss == 0
def start(): if SHOW_INTEGRATION_PATH: show_complex_plain() plt.set_cmap('gray') else: plt.set_cmap('jet') if not SHOW_INTEGRATION_PATH: E_s, saddle_distance, dd_evaluated = steepest_descent() mask = ask_for_mask(E_s, saddle_distance, dd_evaluated) else: E_s = 0 mask = np.zeros((2,2)) E_i, new_mask = integration_method(E_s, mask) if not SHOW_INTEGRATION_PATH: E = plot(E_i, E_s, mask, new_mask) dct = copy(locals()) dct.update(copy(globals())) if FILENAME: vars_to_save = ['E', 'E_i', 'E_s', 'saddle_distance', 'dd_evaluated', 'mask', 'LIMITS', 'RESOLUTION', 'N_ROOTS', 'N_SADDLES', 'THRESHOLDS', 'NUM_WEIGHTS', 'SHOW_INTEGRATION_PATH', 'CALCULATE_ARC_EVERY_N_STEPS', 'N_THREADS', 'D', 'ORDER'] savemat(FILENAME, { key: dct[key] for key in vars_to_save }) else: E = None return E, E_i, E_s
def __init__(self, global_counter, path_to_mha=None, how_many_from_one=1, saving_path='./test_data/'): if path_to_mha is None: raise NameError(' missing .mha path ') self.images = [] for i in range(0, len(path_to_mha)): self.images.append(np.array(sitk.GetArrayFromImage(sitk.ReadImage(path_to_mha[i])))) mkdir_p(saving_path) plt.set_cmap('gray') while how_many_from_one > 0: image_to_save = np.zeros((5, 216, 160)) rand_value = rnd.randint(30, len(self.images[0]) - 30) for i in range(0, len(path_to_mha)): try: image_to_save[i] = self.images[i][rand_value] except: print('ahi') print(self.images[i][rand_value].shape) print(type(self.images)) print(type(self.images)) print('*') continue print(image_to_save.shape) image_to_save = image_to_save.reshape((216 * 5, 160)) print(image_to_save.shape) # image_to_save = resize(image_to_save, (5*216, 160), mode='constant') # image_to_save = image_to_save.resize(5*216, 160) plt.imsave(saving_path + str(global_counter) + '.png', image_to_save) global_counter += 1 how_many_from_one -= 1
def displayData(X): width = 20 rows, cols = 10, 10 out = zeros((width * rows, width * cols)) m = X.shape[0] # データ数 # 5000個のデータセットから適当に100個選ぶ rand_indices = random.permutation(m)[0: rows * cols] counter = 0 for y in range(0, rows): for x in range(0, cols): start_x = x * width start_y = y * width out[start_x: start_x + width, start_y: start_y + width] = X[rand_indices[counter]].reshape(width, width).T counter += 1 img = scipy.misc.toimage(out) figure = pyplot.figure() pyplot.tick_params(labelbottom="off") pyplot.tick_params(labelleft="off") pyplot.set_cmap(pyplot.gray()) axes = figure.add_subplot(111) axes.imshow(img) pyplot.savefig("digits.png")
def scattergrid(points,sizes=[],colors=[]): """ Plots a scatter graphic in a X,Y axes with sized symbols. Input: - points <[(,)]> : a list of tuples of X,Y datapoints - sizes <[]> : a list of numbers for symbols sizing - colors <[]> : a list of numbers for symbols colors Output: - fig <pyplot.figure()> : A matplotlib figure instance Save (fig.savefig()) or show (fig.show()) the object. --- """ if len(points) != len(sizes) and len(sizes) != 0: return False; RA,DEC = zip(*points); RA_min = min(RA); RA_max = max(RA); DEC_min = min(DEC); DEC_max = max(DEC); ra_ = abs(RA_max-RA_min)/20 dec_ = abs(DEC_max-DEC_min)/20 sizes = np.asarray(sizes) sizes = 100 * (sizes-sizes.min()) / (sizes.max()-sizes.min()) sizes = sizes.astype('uint32').tolist(); x,y = zip(*points); # Sort the data just to get it(the plot) right done when # 'scatter' run through datasets. tosort_ = zip(sizes,colors,x,y); tosort_.sort(); tosort_.reverse(); sizes,colors,x,y = zip(*tosort_); # plt.set_cmap('hot'); fig = plt.figure(); ax = fig.add_subplot(111); ax.patch.set_facecolor('0.9'); ax.grid(True); ax.set_xlabel('RA'); ax.set_ylabel('DEC'); # ax.set_title('Massive objects scatter (position) plot') ax.scatter(x,y,s=sizes,c=colors,marker='o',edgecolor='black',alpha=0.75) s2 = [sizes[0],sizes[-1]] x2 = [1,1] y2 = [1,2] # fig.show(); return fig;
def _plot_single_map1(self, path, cmap, signo, dist_map, threshold, constrained, stretch, colorMap, suffix): import matplotlib.pyplot as plt if path != None: plt.ioff() grad = self.get_single_map(signo, cmap, dist_map, threshold, constrained, stretch) plt.imshow(grad, interpolation='none') plt.set_cmap(colorMap) cbar = plt.colorbar() cbar.set_ticks([]) if path != None: if suffix == None: fout = osp.join(path, '{0}_{1}.png'.format(self.label, signo)) else: fout = osp.join(path, '{0}_{1}_{2}.png'.format(self.label, signo, suffix)) try: plt.savefig(fout) except IOError: raise IOError('in classifiers.output, no such file or directory: {0}'.format(path)) else: if suffix == None: plt.title('{0} - EM{1}'.format(self.label, signo)) else: plt.title('{0} - EM{1} - {2}'.format(self.label, signo, suffix)) plt.show() plt.close()
def plot_reals(self, nr=25, hardcopy=0, hardcopy_filename='reals', nanval=-997799, filternan=1): import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import numpy as np from scipy import squeeze nx, ny, nz = self.par['simulation_grid_size'] nr = np.min((self.par['n_real'], nr)) nsp = int(np.ceil(np.sqrt(nr))) fig = plt.figure(1) sp = gridspec.GridSpec(nsp, nsp, wspace=0.1, hspace=0.1) plt.set_cmap('hot') for i in range(0, nr): ax1 = plt.Subplot(fig, sp[i]) fig.add_subplot(ax1) if filternan==1: self.sim[i][self.sim[i]==nanval] = np.nan D=squeeze(np.transpose(self.sim[i])) plt.imshow(D, extent=[self.x[0], self.x[-1], self.y[0], self.y[-1]], interpolation='none') plt.title("Real %d" % (i + 1)) fig.suptitle(self.method + ' - ' + self.parameter_filename, fontsize=16) if (hardcopy): plt.savefig(hardcopy_filename) plt.show(block=False)
def set_cmap(self, i): """Set colormap.""" if 0 <= i < len(self.cmaps): name = self.cmaps[i] if self.is_reverse_cmap: name = dwi.plot.reverse_cmap(name) plt.set_cmap(name)
def tracestackedslab(infile,depthinc=5,llinc=((6371*np.pi)/360),cval=0.5): ''' Takes a netcdf file containing a stacked, normed profiles and attempts to contour what might be a slab - can use this to estimate dip, profile etc The values of depthinc and llinc are defaults from the Ritsema code, which creates slices over angles of 180 degrees and with a depth increment of 5 km This produces a map showing the slice and contours in stacked velocity perturbation at a chosen level (typically 0.5) ''' Mantlebase = 2895 infile = Dataset(infile, model='r') filevariables = infile.variables.keys() #Get data from the netCDF file depths = infile.variables['y'][:] lengths = infile.variables['x'][:] data = infile.variables['z'][:][:] infile.close() #print np.shape(data) #print np.shape(lengths) #print np.shape(depths) #Use image processing suite to find contours contours = measure.find_contours(data,cval) #Various plotting commands to produce the figure fig, ax = plt.subplots() thousandkm = int((Mantlebase-1000)/depthinc) sixsixtykm = int((Mantlebase-660)/depthinc) plt.set_cmap('jet_r') ax.imshow(data, interpolation='linear',aspect='auto') ax.plot([0,len(lengths)],[thousandkm,thousandkm],'k--',label='1000km') ax.plot([0,len(lengths)],[sixsixtykm,sixsixtykm],'k-',label='660km') for n, contour in enumerate(contours): if n == 0: ax.plot(contour[:, 1], contour[:, 0], 'r-', linewidth=2,label='contour at %g' %cval) else: ax.plot(contour[:, 1], contour[:, 0], 'r-', linewidth=2) ax.set_ylim([0,len(depths)]) ax.set_xlim([len(lengths),0]) ax.set_title('Stacked slab image from netCDF') plt.xlabel('Cross section x increment') plt.ylabel('Cross section depth increment') plt.legend(loc='best') #plt.gca().invert_yaxis() #plt.gca().invert_xaxis() plt.show(block=False)
def visualize_matrix(matrix, n_imgs, imgsize, outputfile, cmap="gray", dpi=150): """ """ n_h,n_w = layout_shape(n_imgs) receptive_fields = numpy.zeros((n_h * imgsize, n_w * imgsize), dtype=theano.config.floatX) for i in range(n_h): for j in range(n_w): img = matrix[i * n_w + j] img = img.reshape((imgsize, imgsize)) receptive_fields[i * imgsize: (i + 1) * imgsize, j * imgsize: (j + 1) * imgsize] = img fig = plt.figure() ax = fig.add_subplot(1,1,1) xticks = numpy.arange(0, n_w * imgsize, imgsize) yticks = numpy.arange(0, n_h * imgsize, imgsize) ax.set_xticks(xticks) ax.set_xticklabels([i for (i,x) in enumerate(xticks)]) ax.set_yticks(yticks) ax.set_yticklabels([i for (i,y) in enumerate(yticks)]) ax.grid(which="both", linestyle='-') plt.set_cmap(cmap) plt.imshow(receptive_fields) plt.savefig(outputfile, dpi=dpi)
def testModel(modelFilename, testData, size): # Create shared data test_x, test_y = make_shared(testData, size) # Load the model persistence = PersistenceManager() persistence.set_filename(modelFilename) x, y, classifier = persistence.load_model() # Create prediction function. pred_func = theano.function(inputs = [], outputs = [classifier.y_pred, classifier.errors(y)], givens = {x:test_x, y:test_y}) preds = pred_func() print("prediction done") plt.set_cmap('gray') for i in range(len(testData)): s = testData[i] print("Dist: {0}".format(preds[1][i])) normalizedCoords = preds[0][i] px = np.round(normalizedCoords[0] * s.width) py = np.round(normalizedCoords[1] * s.height) pxCopy = s.getAnnotated() pxCopy[py, px] = 0.85*np.max(pxCopy) plt.imshow(pxCopy) plt.show()
def plot1(self, img, path=None, mask=None, interpolation='none', colorMap='jet', suffix=''): import matplotlib.pyplot as plt if path != None: plt.ioff() if isinstance(mask, np.ndarray): img = img[:,:] * mask plt.imshow(img, interpolation=interpolation) plt.set_cmap(colorMap) cbar = plt.colorbar() cbar.set_ticks([]) if path != None: if suffix == None: fout = osp.join(path, '{0}.png'.format(self.label)) else: fout = osp.join(path, '{0}_{1}.png'.format(self.label, suffix)) try: plt.savefig(fout) except IOError: raise IOError('in classifiers.output, no such file or directory: {0}'.format(path)) else: if suffix == None: plt.title('{0}'.format(self.label)) else: plt.title('{0} - {1}'.format(self.label, suffix)) plt.show() plt.close()
def plot_topography(grid, elev): ''' This function takes the DEM read in below and plots the elevations for visualization purposes. ''' # Get a 2D array version of the elevations for plotting purposes elev_raster = grid.node_vector_to_raster(elev,True) # Everything below plots the topography and sampling points levels = [] # To better create a colorbar... x_up = 2475 while x_up !=2600: levels.append(x_up) x_up+=1 plt.figure('Topography') plt.contourf(elev_raster, levels, colors='k') plt.set_cmap('bone') plt.colorbar() # To plot the study node and outlet node on the DEM... plt.plot([122],[140],'cs', label= 'Study Node') plt.plot([152],[230], 'wo', label= 'Outlet') plt.legend(loc=3)
def show(self): import matplotlib.pyplot as plt print("number of images: {}".format(len(self.I))) for i in xrange(len(self.jsonfiles)): f=open(self.jsonfiles[i],"r") js=json.loads(f.read()) f.close() ##init and show img_path='' if js['path'][0:2]=='./': img_path= rootdir + js['path'][1:] elif js['path'][0]=='/': img_path= rootdir + js['path'] else: img_path= rootdir + '/' +js['path'] print(img_path) im=np.array(Image.open(img_path).convert('L')) plt.hold(False) plt.imshow(im) plt.hold(True) for j in range(self.size): #samples[x]=[0_class,1_img, 2_row, 3_column]^T if self.samples[1,j]==i: plt.text(self.samples[3,j], self.samples[2,j], "%03d"%self.samples[0,j], fontsize=12,color='red') #plt.plot(self.samples[3,j],self.samples[2,j],markers[self.samples[0,j]]) plt.set_cmap('gray') plt.show() plt.ginput(1) plt.close('all')
tmp = inn.lat[j, i] + 40. tmp = np.float64(tmp) lbrei = myround(tmp) if lbrei >= 0 and lbrei <= 80 and inn.vke.mask[k, j, i] == False: lbrei = np.int64(lbrei) amoc[k, lbrei] = amoc[k, lbrei] - inn.vke[ k, j, i] * dlxv[j, i] * ddue[k, j, i] * 1025. amoc_count[k, lbrei] = amoc_count[k, lbrei] + 1 write.write_depth_meridional("amoc_untouched_v3.nc", amoc, 'amoc', y, z) amoc_old = amoc.copy() amoc_untouched = amoc.copy() for kb in range(1, amoc.shape[0] - 2): #if abs(np.mean(amoc[:,kb])) > 1.: amoc[kb, :] = amoc[kb - 1, :] + amoc[kb, :] amoc_down = amoc.copy() amoc = amoc_old.copy() for kb in range(amoc.shape[0] - 2, -1, -1): #if abs(np.mean(amoc[:,kb])) > 1.: amoc[kb, :] = amoc[kb + 1, :] + amoc[kb, :] amoc_up = amoc.copy() f1 = plt.figure() plt.set_cmap('coolwarm') v = np.linspace(-3e10, 3e10, 100, endpoint=True) plt.contourf(y, -z, amoc, v, extend="both") plt.colorbar()
# Add y-axis label plt.ylabel('Temperatures') # Add label for color bar plt.colorbar().ax.set_title('Longtitude') # Save plot as image file plt.savefig('lat_temps_long.png') # Show plot plt.show() plt.scatter(long, temps, c=lat) plt.xlabel('Longitude') plt.ylabel('Temperatures') plt.colorbar().ax.set_title('Latitude') # Set colormap to the selected one # See more colormap selection in the reference at the end of Exercise 5 plt.set_cmap('RdBu') plt.savefig('long_temps_lat.png') plt.show() # P6 import csv import matplotlib.pyplot as plt def read_file(file_name): data = [] with open(file_name, 'r', encoding='ISO-8859-1') as f: rows = csv.DictReader(f) for r in rows: data.append(r)
def setup(center_freq, sample_rate, final): def power(val): p = abs(val**2) pdb = math.log10(p) return (pdb) ##SDR Setup Commands power = np.vectorize(power) fname = center_freq / 1e9 name = str('{:.3f}Ghz'.format(fname)) sdr = adi.Pluto("ip:192.168.2.1") sdr.sample_rate = int(sample_rate) sdr.rx_rf_bandwidth = int( sample_rate) # filter cutoff, just set it to the same as sample rate sdr.rx_lo = int(center_freq) sdr.rx_buffer_size = 1024 # this is the buffer the Pluto uses to buffer samples ##Sampling Signal at Carrier Freq samples = sdr.rx() freqx = np.linspace(int(-sample_rate // 2 + center_freq), int(sample_rate // 2 + center_freq), int(1024)) frq = np.fft.fft(samples) freq = np.fft.fftshift(frq) sig_avg = signal.find_peaks(filter( b, a, freq), height=10000) #Detecting Required Amplitude Peaks print( 'Size:', sig_avg[0].size ) #if(tuple!=empty)->then Adjust OffsetCorrection->then append in final[] if (sig_avg[0].size > 0): print("Active Band:{}Ghz".format(name)) temp = np.array(sig_avg[0]) print("Signal Avg:", temp) for i in range(0, temp.size): temp[i] = temp[i] * (sample_rate / 1000) + center_freq print("Signal Avg:", temp) final = np.concatenate((final, temp)) ##Storing Dataframe in .csv format store = pd.DataFrame( freq) # Storing Dataframe using PANDAS -> IMPORT TO TX IN PANDAS store.to_csv(name + "-Dataframe.png") store = pd.DataFrame( sig_avg[0]) # Storing Dataframe using PANDAS -> IMPORT TO TX IN PANDAS store.to_csv(name + "-Peaks_Dataframe.png") ##Plotting Frequency Response #freq1=power(freq) plt.plot(freqx, freq) #plt.plot(freq) plt.xlim((-10, 1030)) plt.ylim((-10000, 55000)) plt.xlabel('Frequency(Base Freq+Offset*10)Hz') plt.ylabel('Amplitude of Signal') plt.title("Frequency Amplitude:" + name) #for Single TimeFrame plt.savefig(name + "-FA.png") #plt.show() plt.close() samplegroup = [] #Ploting Waterfall Diagram for _ in range(1000): samples = sdr.rx() frq = np.fft.fft(samples) freq = np.fft.fftshift(frq) #freq=power(freq) samplegroup.append(abs(freq)) plt.imshow(samplegroup) plt.set_cmap('hot') plt.xlabel('Frequency(Base Freq+offset*10)Hz') plt.title("Waterfall Diagram:" + name) #for 1000ms TimeFrame plt.savefig(name + "-WD.png") #plt.show() plt.close() return final
def plot_corr(df, size=11): plt.set_cmap('YlOrRd') plt.figure(figsize=(size, size)) sns.heatmap(df.corr()) plt.show()
rSC = np.zeros(shape=(len(livePSTHs),len(livePSTHs), len(ori))) #preallocate for rowind,rowkey in enumerate(livePSTHs.keys()): #loop over rows (units) for colind,colkey in enumerate(livePSTHs.keys()): #loop over columns (same units) for orind,oo in enumerate(ori): #loop over orientations rSC[rowind,colind,orind],dummy = sc.pearsonr(livePSTHs[rowkey][oo][11:211], livePSTHs[colkey][oo][11:211]) #noise correlation ONLY OVER STIM (11:211)) globalMean = np.mean(rSC) # %% Plot correlations #important for resizing colorbar!! from mpl_toolkits.axes_grid1 import make_axes_locatable plt.set_cmap('jet') fig=plt.figure(facecolor='w') for orind,oo in enumerate(ori): ax = fig.add_subplot(1,numOris,orind+1) img=ax.imshow(rSC[:,:,orind]) # ax.axis('equal') # create an axes on the right side of ax. The width of cax will be 5% # of ax and the padding between cax and ax will be fixed at 0.05 inch. divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(img, cax=cax) ax.set_title('Orientation: '+str(oo)+'\xb0')
def plotCCDMap2d(ax, ccdOffsets, parArray, cbLabel, loHi=None): """ Plot CCD map with Chebyshev fits for each CCD parameters ---------- ax: plot axis object ccdOffsets: ccdOffset recarray parArray: float array (nCCD, nPars) cbLabel: string Color bar label loHi: tuple [2], optional (lo, hi) or else scaling is computed from data. """ import matplotlib.pyplot as plt import matplotlib.colors as colors import matplotlib.cm as cmx cm = plt.get_cmap('rainbow') plt.set_cmap('rainbow') plotRARange = [ ccdOffsets['DELTA_RA'].min() - ccdOffsets['RA_SIZE'].max() / 2., ccdOffsets['DELTA_RA'].max() + ccdOffsets['RA_SIZE'].max() / 2. ] plotDecRange = [ ccdOffsets['DELTA_DEC'].min() - ccdOffsets['DEC_SIZE'].max() / 2., ccdOffsets['DELTA_DEC'].max() + ccdOffsets['DEC_SIZE'].max() / 2. ] # compute central values... centralValues = np.zeros(ccdOffsets.size) for i in range(ccdOffsets.size): field = Cheb2dField(ccdOffsets['X_SIZE'][i], ccdOffsets['Y_SIZE'][i], parArray[i, :]) centralValues[i] = -2.5 * np.log10(field.evaluateCenter()) * 1000.0 if (loHi is None): st = np.argsort(centralValues) lo = centralValues[st[int(0.02 * st.size)]] hi = centralValues[st[int(0.98 * st.size)]] else: lo = loHi[0] hi = loHi[1] cNorm = colors.Normalize(vmin=lo, vmax=hi) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm) Z = [[0, 0], [0, 0]] levels = np.linspace(lo, hi, num=150) CS3 = plt.contourf(Z, levels, cmap=cm) ax.clear() ax.set_xlim(plotRARange[0] - 0.05, plotRARange[1] + 0.05) ax.set_ylim(plotDecRange[0] - 0.05, plotDecRange[1] + 0.05) ax.set_xlabel(r'$\delta\,\mathrm{R.A.}$', fontsize=16) ax.set_ylabel(r'$\delta\,\mathrm{Dec.}$', fontsize=16) ax.tick_params(axis='both', which='major', labelsize=14) for k in range(ccdOffsets.size): xValues = np.linspace(0.0, ccdOffsets['X_SIZE'][i], 50) yValues = np.linspace(0.0, ccdOffsets['Y_SIZE'][i], 50) xGrid = np.repeat(xValues, yValues.size) yGrid = np.tile(yValues, xValues.size) field = Cheb2dField(ccdOffsets['X_SIZE'][i], ccdOffsets['Y_SIZE'][i], parArray[k, :]) zGrid = -2.5 * np.log10( np.clip(field.evaluate(xGrid, yGrid), 0.1, None)) * 1000.0 # This seems to be correct extent = [ ccdOffsets['DELTA_RA'][k] - ccdOffsets['RASIGN'][k] * ccdOffsets['RA_SIZE'][k] / 2., ccdOffsets['DELTA_RA'][k] + ccdOffsets['RASIGN'][k] * ccdOffsets['RA_SIZE'][k] / 2., ccdOffsets['DELTA_DEC'][k] - ccdOffsets['DECSIGN'][k] * ccdOffsets['DEC_SIZE'][k] / 2., ccdOffsets['DELTA_DEC'][k] + ccdOffsets['DECSIGN'][k] * ccdOffsets['DEC_SIZE'][k] / 2. ] zGridPlot = zGrid.reshape(xValues.size, yValues.size) if ccdOffsets['XRA'][k]: zGridPlot = zGridPlot.T plt.imshow(zGridPlot, interpolation='bilinear', origin='lower', extent=extent, norm=cNorm) cb = None cb = plt.colorbar(CS3, ticks=np.linspace(lo, hi, 5)) cb.set_label('%s' % (cbLabel), fontsize=14) return None
max_E_ind = np.argmax(gammae) max_E_ind = np.argmax(gammae) #if you want to track particles lower down the energy list #gammae[max_E_ind] = 0 print('highest gamma we have:') print(gammae[max_E_ind]) #max_E_ind = np.argmax(gammae) # 2nd most energetic particle max_E_proc_val = proce[max_E_ind] max_E_ind_val = inde[max_E_ind] print("index , proc") print(max_E_ind_val, max_E_proc_val) plt.set_cmap("viridis") gamma_list = [] t_list = [] u_list = [] v_list = [] w_list = [] #t_max = 350 EoverB_list = [] wpar_list = [] for t in range( 1, 40, 1 ): #in some cases the high E particle is injected later in time, so it' t_list.append(t) t_string = '%03d' % t
@author: stewjo """ import matplotlib.pyplot as plt import numpy as np A = np.random.rand(128, 128) A[:, :] = 0.0 A[30:40, 0] = 100 A[-1, 115:120] = -100 A[0, 70:80] = -100 A[60:80, -1] = 100 # Display it p = plt.imshow(A, interpolation='nearest') plt.set_cmap('OrRd') plt.pause(1) eps = 0.9 for t in range(200000): Aold = np.copy(A) """A[1:-2,1:-2] = (1-eps)*Aold[1:-2,1:-2] + eps*( A[0:-3,1:-2]+A[2:-1,1:-2]+A[1:-2,0:-3]+A[1:-2,2:-1])/4.0 """ #Same as: ??? for i in range(1, 127): for j in range(1, 127): A[i, j] = (1 - eps) * Aold[i, j] + eps * (Aold[i, j - 1] + Aold[ i, j + 1] + Aold[i - 1, j] + Aold[i + 1, j]) / 4.0 A[:, 0] = A[:, 1] A[:, -1] = A[:, -2]
trained_file = data.lbp_frontal_face_cascade_filename() # Initialize the detector cascade. detector = Cascade(trained_file) img = data.astronaut() img = skimage.io.imread("WIN_20200110_17_15_25_Pro.jpg") detected = detector.detect_multi_scale(img=img, scale_factor=1.2, step_ratio=1, min_size=(60, 60), max_size=(123, 123)) plt.imshow(img) img_desc = plt.gca() plt.set_cmap('gray') for patch in detected: print(patch) img_desc.add_patch( patches.Rectangle((patch['c'], patch['r']), patch['width'], patch['height'], fill=False, color='r', linewidth=2)) plt.show()
import scipy import torch from sklearn.cluster import KMeans base_uri = '/Users/juanjogarau/Documents/MIT/HackMIT2017/png_maps' img_path = os.path.join(base_uri, '1_0.png') img = Image.open(img_path).convert('L') pix = np.array(img) * 1. / 255. pix = (pix < 0.7).astype(int) corners = np.array(corner_peaks(corner_harris(pix), min_distance=1)) plt.figure() plt.set_cmap('gray_r') plt.imshow(pix) plt.scatter(corners[:,1], corners[:,0], s=1) aux = np.zeros(pix.shape) for corner in corners: aux[corner[0], corner[1]] = 1 selem_mat = np.ones((12,12)) for _ in range(5): aux = dilation(aux) plt.figure() plt.set_cmap('gray_r') plt.imshow(aux)
def Gdcm_image(filepath): lstFilesDCM = [] DcmName = [] for dirName, subdirList, fileList in sorted(os.walk(filepath)): fileList = natsorted(fileList) for filename in fileList: if ".dcm" in filename.lower(): # 判断文件是否为dicom文件 lstFilesDCM.append(os.path.join(dirName, filename)) # 加入到列表中 DcmName.append(filename) reader = sitk.ImageSeriesReader() dicom_names = reader.GetGDCMSeriesFileNames(filepath) reader.SetFileNames(dicom_names) image = reader.Execute() image_arr = sitk.GetArrayFromImage(image) image_arr = image_arr.transpose() ConstOrigin = image.GetOrigin() ConstPixelSpacing = image.GetSpacing() ConstPixelDims = numpy.shape(image_arr) image_1 = int(ConstPixelDims[0] // 2) image_2 = int(ConstPixelDims[1] // 2) image_3 = int(ConstPixelDims[2] // 2) x = numpy.arange(0.0, (ConstPixelDims[0] + 1) * ConstPixelSpacing[0], ConstPixelSpacing[0]) y = numpy.arange(0.0, (ConstPixelDims[1] + 1) * ConstPixelSpacing[1], ConstPixelSpacing[1]) z = numpy.arange(0.0, (ConstPixelDims[2] + 1) * ConstPixelSpacing[2], ConstPixelSpacing[2]) fig1 = pyplot.figure(dpi=300) pyplot.axes().set_aspect('equal', 'datalim') pyplot.set_cmap(pyplot.gray()) pyplot.pcolormesh( x, y, numpy.flipud(image_arr[:, :, image_3]).transpose()) # 第三个维度表示现在展示的是第几层 pyplot.axis('off') buffer_ = io.BytesIO() pyplot.savefig(buffer_, format='png') buffer_.seek(0) img1 = PIL.Image.open(buffer_) img_arr1 = numpy.asarray(img1) buffer_.close() fig2 = pyplot.figure(dpi=300) pyplot.axes().set_aspect('equal', 'datalim') pyplot.set_cmap(pyplot.gray()) pyplot.pcolormesh(y, z, numpy.fliplr(numpy.rot90((image_arr[image_1, :, :]), 3))) pyplot.axis('off') buffer_ = io.BytesIO() pyplot.savefig(buffer_, format='png') buffer_.seek(0) img2 = PIL.Image.open(buffer_) img_arr2 = numpy.asarray(img2) buffer_.close() fig3 = pyplot.figure(dpi=300) pyplot.axes().set_aspect('equal', 'datalim') pyplot.set_cmap(pyplot.gray()) pyplot.pcolormesh(x, z, numpy.fliplr(numpy.rot90((image_arr[:, image_2, :]), 3))) pyplot.axis('off') buffer_ = io.BytesIO() pyplot.savefig(buffer_, format='png') buffer_.seek(0) img3 = PIL.Image.open(buffer_) img_arr3 = numpy.asarray(img3) buffer_.close() pyplot.figure(figsize=(3, 1), dpi=300) pyplot.subplot(131) pyplot.imshow(img_arr1) pyplot.title('AxialSlice', fontsize=4, y=0.9) pyplot.axis('off') pyplot.xticks([]) pyplot.yticks([]) pyplot.subplot(132) pyplot.imshow(img_arr2) pyplot.title('CoronalSlice', fontsize=4, y=0.9) pyplot.axis('off') pyplot.xticks([]) pyplot.yticks([]) pyplot.subplot(133) pyplot.imshow(img_arr3) pyplot.title('SagitalSlice', fontsize=4, y=0.9) pyplot.axis('off') pyplot.xticks([]) pyplot.yticks([]) pyplot.tight_layout(pad=0.5, w_pad=2) pyplot.subplots_adjust(wspace=0, hspace=0) pyplot.savefig(filepath + '/' + 'image.jpg') pyplot.show() Array_vtk = numpy_support.numpy_to_vtk(image_arr.ravel('F'), deep=True, array_type=vtk.VTK_FLOAT) imagedata = vtk.vtkImageData() imagedata.SetOrigin(ConstOrigin) imagedata.SetSpacing(ConstPixelSpacing) imagedata.SetDimensions(ConstPixelDims) imagedata.GetPointData().SetScalars(Array_vtk) origin = numpy.array(ConstOrigin) ConstPixelSpacing = numpy.array(ConstPixelSpacing) ConstPixelDims = numpy.array(ConstPixelDims) center = origin + (ConstPixelSpacing * ConstPixelDims / 2) DirectionCosines_x = (0, 0, 1, 0, 1, 0, -1, 0, 0) DirectionCosines_y = (1, 0, 0, 0, 0, -1, 0, 1, 0) DirectionCosines_z = (1, 0, 0, 0, 1, 0, 0, 0, 1) def mip_x(): ImageSlab = vtk.vtkImageSlabReslice() ImageSlab.SetInputData(imagedata) ImageSlab.SetResliceAxesOrigin(center) ImageSlab.SetResliceAxesDirectionCosines(DirectionCosines_x) ImageSlab.SetSlabThickness(ConstPixelSpacing[0] * ConstPixelDims[0]) ImageSlab.SetBlendModeToMax() ImageSlab.SetSlabResolution(ConstPixelSpacing[0]) ImageSlab.Update() image = ImageSlab.GetOutput() m = image.GetDimensions() vtk_data = image.GetPointData().GetScalars() arr = numpy_support.vtk_to_numpy(vtk_data).reshape(m[1], m[0]) arr = (arr - numpy.min(arr)) / ( (numpy.max(arr) - numpy.min(arr)) / 255) width = ConstPixelDims[1] height = int(ConstPixelDims[2] * (ConstPixelSpacing[2] / ConstPixelSpacing[1])) dim = (width, height) resized = cv2.resize(numpy.rot90(arr, 1), dim, interpolation=cv2.INTER_AREA) # cv2.imwrite( path + name +'.jpg', resized) return resized def mip_y(): ImageSlab = vtk.vtkImageSlabReslice() ImageSlab.SetInputData(imagedata) ImageSlab.SetResliceAxesOrigin(center) ImageSlab.SetResliceAxesDirectionCosines(DirectionCosines_y) ImageSlab.SetSlabThickness(ConstPixelSpacing[1] * ConstPixelDims[1]) ImageSlab.SetBlendModeToMax() ImageSlab.SetSlabResolution(ConstPixelSpacing[1]) ImageSlab.Update() image = ImageSlab.GetOutput() m = image.GetDimensions() vtk_data = image.GetPointData().GetScalars() arr = numpy_support.vtk_to_numpy(vtk_data).reshape(m[1], m[0]) arr = (arr - numpy.min(arr)) / ( (numpy.max(arr) - numpy.min(arr)) / 255) width = int(ConstPixelDims[2] * (ConstPixelSpacing[2] / ConstPixelSpacing[0])) height = ConstPixelDims[0] dim = (width, height) resized = cv2.resize(numpy.rot90(arr, -1), dim, interpolation=cv2.INTER_AREA) # cv2.imwrite( path + name +'.jpg', resized) return resized def mip_z(): ImageSlab = vtk.vtkImageSlabReslice() ImageSlab.SetInputData(imagedata) ImageSlab.SetResliceAxesOrigin(center) ImageSlab.SetResliceAxesDirectionCosines(DirectionCosines_z) ImageSlab.SetSlabThickness(ConstPixelSpacing[2] * ConstPixelDims[2]) ImageSlab.SetBlendModeToMax() ImageSlab.SetSlabResolution(ConstPixelSpacing[2]) ImageSlab.Update() image = ImageSlab.GetOutput() m = image.GetDimensions() vtk_data = image.GetPointData().GetScalars() arr = numpy_support.vtk_to_numpy(vtk_data).reshape(m[1], m[0]) arr = (arr - numpy.min(arr)) / ( (numpy.max(arr) - numpy.min(arr)) / 255) # cv2.imwrite( path + name +'.jpg', arr) return arr pyplot.figure(figsize=(3, 1), dpi=300) pyplot.subplot(131) pyplot.imshow(numpy.rot90(mip_z(), 2), cmap='gray') pyplot.title('AxialSlice_MIP', fontsize=4, y=1.1) pyplot.xticks([]) pyplot.yticks([]) pyplot.subplot(132) pyplot.imshow(mip_x(), cmap='gray') pyplot.title('CoronalSlice_MIP', fontsize=4, y=1.1) pyplot.xticks([]) pyplot.yticks([]) pyplot.subplot(133) pyplot.imshow(numpy.rot90(mip_y(), 1), cmap='gray') pyplot.title('SagitalSlice_MIP', fontsize=4, y=1.1) pyplot.xticks([]) pyplot.yticks([]) pyplot.tight_layout(pad=1.3, w_pad=2) pyplot.subplots_adjust(wspace=0, hspace=0) pyplot.savefig(filepath + '/' + 'MIP_image.jpg') pyplot.show() return None
hidden_l7 = np.load( '/home/aurora/workspaces/PycharmProjects/tensorflow/L_SoftMax_TensorFlow/data/hidden_m7.npy' ) labels_l7 = np.load( '/home/aurora/workspaces/PycharmProjects/tensorflow/L_SoftMax_TensorFlow/data/labels_m7.npy' ) hidden_l8 = np.load( '/home/aurora/workspaces/PycharmProjects/tensorflow/L_SoftMax_TensorFlow/data/hidden_m8.npy' ) labels_l8 = np.load( '/home/aurora/workspaces/PycharmProjects/tensorflow/L_SoftMax_TensorFlow/data/labels_m8.npy' ) plt.set_cmap('hsv') plt.subplot(241) m1 = plt.scatter(hidden[:, 0], hidden[:, 1], c=labels, label='m=1, test_acc=0.9811') plt.legend(handles=[m1], bbox_to_anchor=(0., 1.02, 1., .102), loc=3, mode="expand", borderaxespad=0.) plt.subplot(242) m2 = plt.scatter(hidden_l2[:, 0], hidden_l2[:, 1], c=labels_l2,
#Loading Dataset iris = np.loadtxt('iris.csv', delimiter=',') x, y = iris[:, :4], iris[:, 4].astype( np.int ) # x: (observations x attributes) matrix, y: classes (1: setosa, 2: versicolor, 3: virginica) x.shape y.shape #Dimensionality reduction by Principal Component Analysis (PCA) pca = mlpy.PCA() # new PCA instance pca.learn(x) # learn from data z = pca.transform(x, k=2) # embed x into the k=2 dimensional subspace z.shape #Plot the principal components: plt.set_cmap(plt.cm.Paired) fig1 = plt.figure(1) title = plt.title("PCA on iris dataset") plot = plt.scatter(z[:, 0], z[:, 1], c=y) labx = plt.xlabel("First component") laby = plt.ylabel("Second component") plt.show() #Learning by Kernel Support Vector Machines (SVMs) on principal components: linear_svm = mlpy.LibSvm(kernel_type='linear') # new linear SVM instance linear_svm.learn(z, y) # learn from principal components #For plotting purposes, we build the grid where we will compute the predictions (zgrid): xmin, xmax = z[:, 0].min() - 0.1, z[:, 0].max() + 0.1 ymin, ymax = z[:, 1].min() - 0.1, z[:, 1].max() + 0.1 xx, yy = np.meshgrid(np.arange(xmin, xmax, 0.01), np.arange(ymin, ymax, 0.01))
), ) grid = ImageGrid(fig, 111, nrows_ncols=(4, ncols), axes_pad=0.1) fig2, axp = plt.subplots( dpi=150, figsize=(plot_size * ncols, 4), subplotpars=mpl.figure.SubplotParams( bottom=0.1, left=0.025, right=0.975, top=0.925, ), ) plt.set_cmap("inferno") for (i, p), l, col in zip(enumerate(psfs), labels, grid.axes_column): print(p) p = p.PSF p /= p.max() psf_plot_style = dict(norm=mpl.colors.PowerNorm(gam), interpolation=interpolation, cmap="Greys_r") col[0].imshow(p.max(1), **psf_plot_style) col[1].imshow(p.max(0), **psf_plot_style) col[0].set_title(l)
def showimage(img): if img.ndim == 3: img = img[:, :, ::-1] plt.set_cmap('jet') plt.imshow(img, vmin=0, vmax=0.2)
def Get_image(filepath): lstFilesDCM = [] DcmName = [] for dirName, subdirList, fileList in sorted(os.walk(filepath)): fileList = natsorted(fileList) for filename in fileList: if ".dcm" in filename.lower(): # 判断文件是否为dicom文件 lstFilesDCM.append(os.path.join(dirName, filename)) # 加入到列表中 DcmName.append(filename) gap = len(DcmName) - 1 file_one = pydicom.read_file(lstFilesDCM[0], force=True) z_one = file_one.ImagePositionPatient[2] file_tow = pydicom.read_file(lstFilesDCM[gap], force=True) z_tow = file_tow.ImagePositionPatient[2] columns = file_one.Columns row = file_one.Rows ConstPixelDims = (int(row), int(columns), len(lstFilesDCM)) if z_one > z_tow: slice_gap = (z_one - z_tow) / gap ConstOrigin = (file_tow.ImagePositionPatient[0], file_tow.ImagePositionPatient[1], file_tow.ImagePositionPatient[2]) ConstPixelSpacing = (float(file_tow.PixelSpacing[0]), float(file_tow.PixelSpacing[1]), float(slice_gap)) else: slice_gap = (z_tow - z_one) / gap ConstOrigin = (file_one.ImagePositionPatient[0], file_one.ImagePositionPatient[1], file_one.ImagePositionPatient[2]) ConstPixelSpacing = (float(file_one.PixelSpacing[0]), float(file_one.PixelSpacing[1]), float(slice_gap)) image_1 = int(ConstPixelDims[0] // 2) image_2 = int(ConstPixelDims[1] // 2) image_3 = int(ConstPixelDims[2] // 2) x = numpy.arange( 0.0, (ConstPixelDims[0] + 1) * ConstPixelSpacing[0], ConstPixelSpacing[0]) # 0到(第一个维数加一*像素间的间隔),步长为constpixelSpacing y = numpy.arange(0.0, (ConstPixelDims[1] + 1) * ConstPixelSpacing[1], ConstPixelSpacing[1]) # z = numpy.arange(0.0, (ConstPixelDims[2] + 1) * ConstPixelSpacing[2], ConstPixelSpacing[2]) # ArrayDicom = numpy.zeros(ConstPixelDims, dtype=file_one.pixel_array.dtype) # 遍历所有的dicom文件,读取图像数据,存放在numpy数组中 for filenameDCM in lstFilesDCM: ds = pydicom.read_file(filenameDCM) ArrayDicom[:, :, lstFilesDCM.index(filenameDCM)] = ds.pixel_array pyplot.figure(dpi=300) pyplot.axes().set_aspect('equal', 'datalim') pyplot.set_cmap(pyplot.gray()) pyplot.pcolormesh(x, y, numpy.flipud(ArrayDicom[:, :, image_3])) # 第三个维度表示现在展示的是第几层 pyplot.axis('off') buffer_ = io.BytesIO() pyplot.savefig(buffer_, format='png') buffer_.seek(0) img1 = PIL.Image.open(buffer_) img_arr1 = numpy.asarray(img1) buffer_.close() pyplot.figure(dpi=300) pyplot.axes().set_aspect('equal', 'datalim') pyplot.set_cmap(pyplot.gray()) pyplot.pcolormesh( y, z, numpy.fliplr(numpy.rot90((ArrayDicom[image_1, :, :]), 3))) pyplot.axis('off') buffer_ = io.BytesIO() pyplot.savefig(buffer_, format='png') buffer_.seek(0) img2 = PIL.Image.open(buffer_) img_arr2 = numpy.asarray(img2) buffer_.close() pyplot.figure(dpi=300) pyplot.axes().set_aspect('equal', 'datalim') pyplot.set_cmap(pyplot.gray()) pyplot.pcolormesh( x, z, numpy.fliplr(numpy.rot90((ArrayDicom[:, image_2, :]), 3))) pyplot.axis('off') buffer_ = io.BytesIO() pyplot.savefig(buffer_, format='png') buffer_.seek(0) img3 = PIL.Image.open(buffer_) img_arr3 = numpy.asarray(img3) buffer_.close() pyplot.figure(figsize=(3, 1), dpi=300) pyplot.subplot(131) pyplot.imshow(img_arr1) pyplot.title('AxialSlice', fontsize=4, y=0.9) pyplot.axis('off') pyplot.xticks([]) pyplot.yticks([]) pyplot.subplot(132) pyplot.imshow(img_arr2) pyplot.title('CoronalSlice', fontsize=4, y=0.9) pyplot.axis('off') pyplot.xticks([]) pyplot.yticks([]) pyplot.subplot(133) pyplot.imshow(img_arr3) pyplot.title('SagitalSlice', fontsize=4, y=0.9) pyplot.axis('off') pyplot.xticks([]) pyplot.yticks([]) pyplot.tight_layout(pad=0.5, w_pad=2) pyplot.subplots_adjust(wspace=0, hspace=0) pyplot.savefig(filepath + '/' + 'image.jpg') pyplot.show() Array_vtk = numpy_support.numpy_to_vtk(ArrayDicom.ravel('F'), deep=True, array_type=vtk.VTK_FLOAT) imagedata = vtk.vtkImageData() imagedata.SetOrigin(ConstOrigin) imagedata.SetSpacing(ConstPixelSpacing) imagedata.SetDimensions(ConstPixelDims) imagedata.GetPointData().SetScalars(Array_vtk) origin = numpy.array(ConstOrigin) ConstPixelSpacing = numpy.array(ConstPixelSpacing) ConstPixelDims = numpy.array(ConstPixelDims) center = origin + (ConstPixelSpacing * ConstPixelDims / 2) DirectionCosines_x = (0, 0, 1, 0, 1, 0, -1, 0, 0) DirectionCosines_y = (1, 0, 0, 0, 0, -1, 0, 1, 0) DirectionCosines_z = (1, 0, 0, 0, 1, 0, 0, 0, 1) def mip_x(): ImageSlab = vtk.vtkImageSlabReslice() ImageSlab.SetInputData(imagedata) ImageSlab.SetResliceAxesOrigin(center) ImageSlab.SetResliceAxesDirectionCosines(DirectionCosines_x) ImageSlab.SetSlabThickness(ConstPixelSpacing[0] * ConstPixelDims[0]) ImageSlab.SetBlendModeToMax() ImageSlab.SetSlabResolution(ConstPixelSpacing[0]) ImageSlab.Update() image = ImageSlab.GetOutput() m = image.GetDimensions() vtk_data = image.GetPointData().GetScalars() arr = numpy_support.vtk_to_numpy(vtk_data).reshape(m[1], m[0]) arr = (arr - numpy.min(arr)) / ( (numpy.max(arr) - numpy.min(arr)) / 255) width = columns height = int( len(lstFilesDCM) * (ConstPixelSpacing[2] / ConstPixelSpacing[1])) dim = (width, height) resized = cv2.resize(numpy.rot90(arr, 1), dim, interpolation=cv2.INTER_AREA) return resized def mip_y(): ImageSlab = vtk.vtkImageSlabReslice() ImageSlab.SetInputData(imagedata) ImageSlab.SetResliceAxesOrigin(center) ImageSlab.SetResliceAxesDirectionCosines(DirectionCosines_y) ImageSlab.SetSlabThickness(ConstPixelSpacing[1] * ConstPixelDims[1]) ImageSlab.SetBlendModeToMax() ImageSlab.SetSlabResolution(ConstPixelSpacing[1]) ImageSlab.Update() image = ImageSlab.GetOutput() m = image.GetDimensions() vtk_data = image.GetPointData().GetScalars() arr = numpy_support.vtk_to_numpy(vtk_data).reshape(m[1], m[0]) arr = (arr - numpy.min(arr)) / ( (numpy.max(arr) - numpy.min(arr)) / 255) width = int( len(lstFilesDCM) * (ConstPixelSpacing[2] / ConstPixelSpacing[0])) height = row dim = (width, height) resized = cv2.resize(numpy.rot90(arr, -1), dim, interpolation=cv2.INTER_AREA) # cv2.imwrite( path +'/'+ name +'.jpg', resized) return resized def mip_z(): ImageSlab = vtk.vtkImageSlabReslice() ImageSlab.SetInputData(imagedata) ImageSlab.SetResliceAxesOrigin(center) ImageSlab.SetResliceAxesDirectionCosines(DirectionCosines_z) ImageSlab.SetSlabThickness(ConstPixelSpacing[2] * ConstPixelDims[2]) ImageSlab.SetBlendModeToMax() ImageSlab.SetSlabResolution(ConstPixelSpacing[2]) ImageSlab.Update() image = ImageSlab.GetOutput() m = image.GetDimensions() vtk_data = image.GetPointData().GetScalars() arr = numpy_support.vtk_to_numpy(vtk_data).reshape(m[1], m[0]) arr = (arr - numpy.min(arr)) / ( (numpy.max(arr) - numpy.min(arr)) / 255) arr = numpy.rot90(arr, -1) # cv2.imwrite(path+'/'+name+'.jpg', numpy.rot90(arr, -1)) return arr pyplot.figure(figsize=(3, 1), dpi=300) pyplot.subplot(131) pyplot.imshow(mip_z(), cmap='gray') pyplot.title('AxialSlice_MIP', fontsize=4, y=1.1) pyplot.xticks([]) pyplot.yticks([]) pyplot.subplot(132) pyplot.imshow(mip_x(), cmap='gray') pyplot.title('CoronalSlice_MIP', fontsize=4, y=1.1) pyplot.xticks([]) pyplot.yticks([]) pyplot.subplot(133) pyplot.imshow(numpy.rot90(mip_y(), 1), cmap='gray') pyplot.title('SagitalSlice_MIP', fontsize=4, y=1.1) pyplot.xticks([]) pyplot.yticks([]) pyplot.tight_layout(pad=1.3, w_pad=2) pyplot.subplots_adjust(wspace=0, hspace=0) pyplot.savefig(filepath + '/' + 'MIP_image.jpg') pyplot.show() return None
plt.xlabel("time (sec)") plt.margins(0, .1) # make the phase plot plt.subplot(133) plt.grid(alpha=.5) plt.plot(Y, dY, alpha=.5, lw=.5, color=cm(abf.sweep / abf.sweeps)) plt.title("phase plot") plt.ylabel("dV (mV/ms)") plt.xlabel("V (mV)") plt.margins(.1, .1) # tighten up the figure plt.tight_layout() if __name__ == "__main__": #abf=swhlab.ABF(R"X:\Data\SCOTT\2017-07-13 OXT-Tom OneOff\17713015.abf") abf = swhlab.ABF(R"X:\Data\SCOTT\2017-07-13 OXT-Tom OneOff\17713013.abf") plt.figure(figsize=(12, 4)) for sweep in abf.setsweeps(): #if sweep<abf.sweeps-1: continue print("plotting sweep", sweep, '...') plt.set_cmap('winter') drawPhasePlot(abf) plt.savefig("phase_%s.png" % abf.ID, dpi=300) plt.show() plt.close('all') print("DONE")
#Load spacing values (in mm) ConstPixelSpacing = (float(Ref_CT.PixelSpacing[1]), float(Ref_CT.PixelSpacing[0]), float(Ref_CT.SliceThickness)) x = np.arange(0.0, (ConstPixelDims[0] + 1) * ConstPixelSpacing[0], ConstPixelSpacing[0]) y = np.arange(-(ConstPixelDims[1] + 1) * ConstPixelSpacing[1], 0.0, ConstPixelSpacing[1]) z = np.arange(0.0, (ConstPixelDims[2] + 1) * ConstPixelSpacing[2], ConstPixelSpacing[2]) ArrayDicom = np.zeros(ConstPixelDims, dtype=Ref_CT.pixel_array.dtype) for i, DCMfile in enumerate(CT_slide): ArrayDicom[:, :, i] = DCMfile.pixel_array """ plt.figure(dpi=300) plt.axes().set_aspect('equal', 'datalim') plt.set_cmap(plt.gray()) plt.pcolormesh(x, y, np.flipud(ArrayDicom[:, :, 50])) plt.show() """ ResArray = ndinter.zoom(ArrayDicom, ConstPixelSpacing, order=1) plt.figure(dpi=300) plt.axes().set_aspect('equal', 'datalim') plt.set_cmap(plt.gray()) #plt.pcolormesh(x, y, ResArray[:, :, 150])) plt.imshow(ResArray[:, :, 100]) plt.show()
def plot2D(result, par1, par2, colorMap=getColorMap(), labelSize=15, fontSize=10, axisHandle=None, showImediate=True): """ This function constructs a 2 dimensional marginal plot of the posterior density. This is the same plot as it is displayed in plotBayes in an unmodifyable way. The result struct is passed as result. par1 and par2 should code the two parameters to plot: 0 = threshold 1 = width 2 = lambda 3 = gamma 4 = eta Further plotting options may be passed. """ # convert strings to dimension number par1, label1 = _utils.strToDim(str(par1)) par2, label2 = _utils.strToDim(str(par2)) assert ( par1 != par2 ), 'par1 and par2 must be different numbers to code for the parameters to plot' if axisHandle == None: axisHandle = plt.gca() try: plt.axes(axisHandle) except TypeError: raise ValueError('Invalid axes handle provided to plot in.') plt.set_cmap(colorMap) marg, _, _ = marginalize(result, np.array([par1, par2])) if par1 > par2: marg = marg.T if 1 in marg.shape: if len(result['X1D'][par1]) == 1: plotMarginal(result, par2) else: plotMarginal(result, par2) else: e = [result['X1D'][par2][0], result['X1D'][par2][-1], \ result['X1D'][par1][0], result['X1D'][par1][-1]] plt.imshow(marg, extent=e) plt.ylabel(label1, fontsize=labelSize) plt.xlabel(label2, fontsize=labelSize) plt.tick_params(direction='out', right='off', top='off') for side in ['top', 'right']: axisHandle.spines[side].set_visible(False) plt.ticklabel_format(style='sci', scilimits=(-2, 4)) if (showImediate): plt.show(0)
# いらすとやの画像はアルファチャンネルがあるのでこれをまず白にする # ImageMagickの convert -flatten x.png y.png に対応 img = cv2.imread(path, cv2.IMREAD_UNCHANGED) # if img.shape[2] == 4: # mask = img[:,:,3] == 0 # img[mask] = [255] * 4 # img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # ノイズ除去が必要なら # gray = cv2.fastNlMeansDenoising(gray, h=20) # 白い部分を膨張させる dilated = cv2.dilate(gray, kernel, iterations=1) # 差をとる diff = cv2.absdiff(dilated, gray) # 白黒反転して2値化 _, contour = cv2.threshold(255 - diff, 240, 255, cv2.THRESH_BINARY) # あるいは #contour = cv2.adaptiveThreshold(255 - diff, 255, # cv2.ADAPTIVE_THRESH_GAUSSIAN_C, # cv2.THRESH_BINARY, 7, 8) return contour # plt.close("all") # plt.figure(figsize=[8, 8]) plt.set_cmap("gray") # plt.clf() contour = makecontour("IMG_3147.PNG") plt.imshow(contour) cv2.imwrite("190831a.png", contour)
FIG = plt.figure(figsize=(30,25)) AuG_type = 'AuGMEnT' tit_aug = 'AuGMEnT' d = 3 S = d+2 savestr = 'DATA/'+AuG_type+'_'+task+'_'+'distr'+str(d)+'_weights_Vm.txt' X_a3 = np.loadtxt(savestr) plt.subplot(2,3,1) plt.pcolor(np.flipud(X_a3),edgecolors='k', linewidths=1) plt.set_cmap('bwr') cb = plt.colorbar() cb.ax.tick_params(labelsize=fontLabel) tit = tit_aug+' (L='+str(d+2)+')' plt.title(tit,fontweight="bold",fontsize=fontTitle) plt.xticks(np.linspace(0.5,M-0.5,M,endpoint=True),mem_vec_c,fontsize=fontTicks) plt.yticks(np.linspace(0.5,2*S-0.5,2*S,endpoint=True),np.flipud(cues_vec_3),fontsize=fontTicks) plt.ylabel('Transient Unit Labels', fontsize=fontLabel) d = 8 S = d+2 savestr = 'DATA/'+AuG_type+'_'+task+'_'+'distr'+str(d)+'_weights_Vm.txt' X_a8 = np.loadtxt(savestr) plt.subplot(2,3,4) plt.pcolor(np.flipud(X_a8),edgecolors='k', linewidths=1)
fig = plt.figure(figsize=(2, 4)) gs = GridSpec(2, 1, figure=fig) ax = [] #ax_rthist=fig.add_subplot(gs[5:7,0:4]) #ax2_rthist=fig.add_subplot(gs[1:3,12:]) #ax2_bthist=fig.add_subplot(gs[7:,6:12]) frames_to_plot = [49, 50] for ind, crframe in enumerate(frames_to_plot): try: ax.append(fig.add_subplot(gs[ind, 0])) except: pdb.set_trace() for crind in np.arange(len(file_names)): plt.set_cmap('viridis') dt = util.read_in_tif(data_path + file_names[crind]) for ind, crframe in enumerate(frames_to_plot): #mean_xy=np.mean(dt['tifstack'],axis=0) #mean_z=np.mean(dt['tifstack'],axis=1) imshowobj = ax[ind].imshow(dt['tifstack'][crframe, :, :]) #imshowobj.set_clim(20,28) fpl.adjust_spines(ax[ind], []) ax[ind].set_xlim(200, 1150) ax[ind].set_ylim(50, 200) #microns_mean_z=np.shape(mean_z)[1]*microns_per_pixel #ax.plot([970,970+20/microns_per_pixel],[775,775],'w') #aspect_ratio=microns_mean_z/100. #imshowobj2=ax2.imshow(mean_z) #imshowobj2.set_clim(14.6,16.5) #fpl.adjust_spines(ax2,[])
def _visualize(self, data, out_name): from matplotlib import pyplot as plt plt.set_cmap('viridis') plot_and_save(out_name, nlp.plot_design_matrix, data)
def bias_plot2D(self, mod, ctx: Context, spotfilter, tag): sf_d, g2d_d = self.simflux_fit(mod, ctx, spotfilter=spotfilter) shift = sf_d.get_xyI()[:, [0, 1]] - g2d_d.get_xyI()[:, [0, 1]] pos = g2d_d.get_xyI() rms = np.sqrt(np.mean(shift**2, 0)) print( f"RMS x shift={rms[0]*self.pixelsize}, y shift={rms[1]*self.pixelsize}" ) shape = self.locs.get_image_size() w = 100 print(f"running 2D bias fit over {len(pos)} points") gridshape = [w, w] # statfn = 'median' def median_mincount(x, minsize): if len(x) < minsize: return np.nan return np.median(x) def rms_mincount(x, minsize): if len(x) < minsize: return np.nan return np.sqrt(np.mean(x**2)) statfn = lambda x: median_mincount(x, 20) metric = 'Median bias' # statfn = lambda x: rms_mincount(x,20) # metric='RMS' scatter = True clustergrid = [w, w] xysx = fitpoints2D.hist2d_statistic_points(pos[:, 0], pos[:, 1], shift[:, 0], shape, clustergrid, statistic=statfn) xysy = fitpoints2D.hist2d_statistic_points(pos[:, 0], pos[:, 1], shift[:, 1], shape, clustergrid, statistic=statfn) rms_x = np.sqrt(np.mean(xysx[:, 2]**2)) rms_y = np.sqrt(np.mean(xysy[:, 2]**2)) print( f"RMS clusters x shift={rms_x*self.pixelsize}, y shift={rms_y*self.pixelsize}" ) print(f"2D bias plot: plotting {len(xysx)} clusters") plt.figure(figsize=figsize) plt.hist([xysx[:, 2] * self.pixelsize, xysy[:2] * self.pixelsize], label=['X bias', 'Y bias'], range=[-50, 50], bins=50) plt.title('SMLM-SIMFLUX difference histogram') plt.xlabel( 'Mean difference between SMLM and SIMFLUX within one cluster [nm]') plt.legend() plt.savefig(self.outdir + tag + "bias-hist.svg") plt.savefig(self.outdir + tag + "bias-hist.png") xysx[:, 2] = np.clip(xysx[:, 2], -1, 1) xysy[:, 2] = np.clip(xysy[:, 2], -1, 1) img_x, coeff_x = fitpoints2D.fitlsq(xysx[:, 0], xysy[:, 1], xysx[:, 2], shape, gridshape) img_y, coeff_y = fitpoints2D.fitlsq(xysy[:, 0], xysy[:, 1], xysy[:, 2], shape, gridshape) plt.figure(figsize=figsize) plt.set_cmap('viridis') # plt.imshow(img_x, origin='lower',extent=[0,shape[1],0,shape[0]]) s = self.pixelsize / 1000 sc = self.pixelsize if scatter: plt.scatter(s * xysx[:, 0], s * xysx[:, 1], c=sc * xysx[:, 2]) cb = plt.colorbar() cb.set_label('Bias in X [nm]') plt.clim([-20, 20]) plt.xlabel(u'X position in FOV [um]') plt.ylabel(u'Y position in FOV [um]') plt.title(f'{metric} in X over FOV') plt.savefig(self.outdir + tag + "x-bias-fov.png") plt.savefig(self.outdir + tag + "x-bias-fov.svg") plt.figure(figsize=figsize) # plt.imshow(img_y, origin='lower', extent=[0,shape[1],0,shape[0]]) if scatter: plt.scatter(s * xysy[:, 0], s * xysy[:, 1], c=sc * xysy[:, 2]) cb = plt.colorbar() cb.set_label('Bias in Y [nm]') plt.clim([-20, 20]) plt.xlabel(u'X position in FOV [um]') plt.ylabel(u'Y position in FOV [um]') plt.title(f'{metric} in Y over FOV') plt.savefig(self.outdir + tag + "y-bias-fov.png") plt.savefig(self.outdir + tag + "y-bias-fov.svg")
def _view_matrix(self, matrix, figsize, colormap, colorbar, bestmatches, bestmatchcolors, labels, zoom, filename): """Internal function to plot a map with best matching units and labels. """ if zoom is None: zoom = ((0, self._n_rows), (0, self._n_columns)) if figsize is None: figsize = (8, 8 / float(zoom[1][1] / zoom[0][1])) fig = plt.figure(figsize=figsize) if self._grid_type == "hexagonal": offsets = _hexplot( matrix[zoom[0][0]:zoom[0][1], zoom[1][0]:zoom[1][1]], fig, colormap) filtered_bmus = self.filter_array(self.bmus, zoom) filtered_bmus[:, 0] = filtered_bmus[:, 0] - zoom[1][0] filtered_bmus[:, 1] = filtered_bmus[:, 1] - zoom[0][0] bmu_coords = np.zeros(filtered_bmus.shape) for i, (row, col) in enumerate(filtered_bmus): bmu_coords[i] = offsets[col * zoom[1][1] + row] else: plt.imshow(matrix[zoom[0][0]:zoom[0][1], zoom[1][0]:zoom[1][1]], aspect='auto') plt.set_cmap(colormap) bmu_coords = self.filter_array(self.bmus, zoom) bmu_coords[:, 0] = bmu_coords[:, 0] - zoom[1][0] bmu_coords[:, 1] = bmu_coords[:, 1] - zoom[0][0] if colorbar: cmap = cm.ScalarMappable(cmap=colormap) cmap.set_array(matrix) plt.colorbar(cmap, orientation='horizontal', shrink=0.5) if bestmatches: if bestmatchcolors is None: if self.clusters is None: colors = "white" else: colors = [] for bm in self.bmus: colors.append(self.clusters[bm[1], bm[0]]) colors = self.filter_array(colors, zoom) else: colors = self.filter_array(bestmatchcolors, zoom) plt.scatter(bmu_coords[:, 0], bmu_coords[:, 1], c=colors) if labels is not None: for label, col, row in zip(self.filter_array(labels, zoom), bmu_coords[:, 0], bmu_coords[:, 1]): if label is not None: plt.annotate(label, xy=(col, row), xytext=(10, -5), textcoords='offset points', ha='left', va='bottom', bbox=dict(boxstyle='round,pad=0.3', fc='white', alpha=0.8)) plt.axis('off') if filename is not None: plt.savefig(filename) else: plt.show() return plt
f['t'] = cum l = { key: [item[key] for item in d] for key in list( reduce(lambda x, y: x.union(y), (set(dicts.keys()) for dicts in d))) } print("Lap length = %s m" % str(round(l['dist'][-1], 2))) print("Lap time = %s s" % str(round(l['t'][-1], 4))) print("Max velocity = %s m/s" % str(round(max(l['vel']), 3))) print("Max lateral accel = %s g" % str(round(max(l['A_lat']) / G, 3))) print("Max longitudinal accel = %s g" % str(round(max(l['A_long']) / G, 3))) print("Min longitudinal accel = %s g" % str(round(min(l['A_long']) / G, 3))) if plot_mode == "track": plt.set_cmap('cool') plt.scatter(l['x'], l['y'], c=[min(max(d, -30), 30) for i, d in enumerate(l['vel'])], s=1) plt.axis('equal') plt.colorbar() plt.show() elif plot_mode == "time": plt.scatter([x for i, x in enumerate(l['t'])][:2000], [d for i, d in enumerate(l['vel'])][:2000], label="vel") plt.legend(loc='best') plt.show()
# Plot the decision boundary. For that, we will asign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - .5, X[:, 0].max( ) + .5 #Defines min and max on the x-axis y_min, y_max = X[:, 1].min() - .5, X[:, 1].max( ) + .5 #Defines min and max on the y-axis h = (x_max - x_min) / 300 # step size in the mesh to plot entire areas xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) #Defines meshgrid Z = vector.predict(np.c_[xx.ravel(), yy.ravel( )]) #Uses the calibrated model knn and running on "fake" data in meshgrid # Put the result into a color plot Z = Z.reshape(xx.shape) #Reshape for matplotlib plt.figure(1) #create one figure plt.set_cmap(plt.cm.Paired) #Picks color for plt.pcolormesh(xx, yy, Z) #Plot for the data # Plot also the training points colormap = np.array( ['white', 'black']) #BGive two colors based on values of 0 and 1 from HW6_Data plt.scatter( X[:, 0], X[:, 1], c=colormap[Y] ) #Plot the data as a scatter plot, note that the color changes with Y. plt.xlabel("X1") #Adding axis labels plt.ylabel("X2") plt.xlim(xx.min(), xx.max()) #Setting limits of axes plt.ylim(yy.min(), yy.max()) plt.xticks(()) #Removing tick marks
def display_data(X, example_width=None): # DISPLAYDATA Display 2D data in a nice grid # [h, display_array] = DISPLAYDATA(X, example_width) displays 2D data # stored in X in a nice grid. It returns the figure handle h and the # displayed array if requested. # closes previously opened figure. preventing a # warning after opening too many figures plt.close() # creates new figure plt.figure() # turns 1D X array into 2D if X.ndim == 1: X = np.reshape(X, (-1, X.shape[0])) # Set example_width automatically if not passed in if not example_width or not 'example_width' in locals(): example_width = int(round(math.sqrt(X.shape[1]))) # Gray Image plt.set_cmap("gray") # Compute rows, cols m, n = X.shape example_height = int(n / example_width) # Compute number of items to display display_rows = int(math.floor(math.sqrt(m))) display_cols = int(math.ceil(m / display_rows)) # Between images padding pad = 1 # Setup blank display len1 = int(pad + display_rows * (example_height + pad)) len2 = pad + display_cols * (example_width + pad) display_array = -np.ones((len1, len2)) # Copy each example into a patch on the display array curr_ex = 1 for j in range(1, display_rows + 1): for i in range(1, display_cols + 1): if curr_ex > m: break # Copy the patch # Get the max value of the patch to normalize all examples max_val = max(abs(X[curr_ex - 1, :])) rows = pad + (j - 1) * (example_height + pad) + np.array( range(example_height)) cols = pad + (i - 1) * (example_width + pad) + np.array( range(example_width)) # Basic (vs. advanced) indexing/slicing is necessary so that we look can assign # values directly to display_array and not to a copy of its subarray. # from stackoverflow.com/a/7960811/583834 and # bytes.com/topic/python/answers/759181-help-slicing-replacing-matrix-sections # Also notice the order="F" parameter on the reshape call - this is because python's # default reshape function uses "C-like index order, with the last axis index # changing fastest, back to the first axis index changing slowest" i.e. # it first fills out the first row/the first index, then the second row, etc. # matlab uses "Fortran-like index order, with the first index changing fastest, # and the last index changing slowest" i.e. it first fills out the first column, # then the second column, etc. This latter behaviour is what we want. # Alternatively, we can keep the deault order="C" and then transpose the result # from the reshape call. display_array[rows[0]:rows[-1] + 1, cols[0]:cols[-1] + 1] = np.reshape(X[curr_ex - 1, :], (example_height, example_width), order="F") / max_val curr_ex += 1 if curr_ex > m: break # Display Image h = plt.imshow(display_array, vmin=-1, vmax=1) # Do not show axis plt.axis('off') plt.show() return h, display_array
import matplotlib.pyplot as plt import matplotlib import pandas as pd from mpl_toolkits.mplot3d import Axes3D import numpy as np import math as mth from itertools import product, combinations from matplotlib import rc # activate latex text rendering rc('text', usetex=True) #set rc parameters for plotting matplotlib.rcParams.update({'font.size': 60}) matplotlib.rcParams['axes.labelpad'] = 70 plt.rcParams["font.family"] = "Times New Roman" plt.set_cmap("jet") #import data to be plotted data = pd.read_csv(r'C:\Users\Theo\PartIII\FINAL_LatticeSpinsT05.csv') Lattice = pd.DataFrame(data, columns=['i', 'j', 'k', 'Spin']) data = pd.read_csv(r'C:\Users\Theo\PartIII\FINAL_LatticeT05.csv') LatticeSize = pd.DataFrame(data, columns=['i', 'j', 'k', 'Spin Flips']) data = pd.read_csv(r'C:\Users\Theo\PartIII\FINAL_NearestNeighbourT05.csv') LatticeNeighbours = pd.DataFrame(data, columns=['i', 'j', 'k', 'Neighbours']) #assign gif and ax for full lattice plot fig = plt.figure() ax = plt.axes(projection="3d") #convert lattice indexing to cartesian coordinates x_coord = (Lattice['i'] + Lattice['j'])
def train(self, plotmode=False): pbar = tqdm(total=self.max_iter) pbar.update(self.global_iter) out = False running_loss_terminal_display = 0.0 # running loss for the trainstats (gathered and pickeled) running_loss_trainstats = 0.0 # running loss for the trainstats (gathered and pickeled) """ /begin of non-generic part (might need to be adapted for different models / data)""" running_recon_loss_trainstats = 0.0 running_pred_loss_trainstats = 0.0 plot_total_loss = [] plot_recon_loss = [] plot_pred_loss = [] while not out: for [ samples, latents ] in self.train_loader: # not sure how long the train_loader spits out data (possibly infinite?) self.global_iter += 1 if not plotmode: pbar.update(1) self.net.zero_grad() # get current batch and push to device img_batch, _ = samples.to(self.device), latents.to(self.device) # in VAE, input = output/target if self.modeltype == 'inertiaAE': input_batch = img_batch output_batch = img_batch predicted_batch, mu, mu_enc, mu_pred = self.net(input_batch) recon_loss = self.reconstruction_loss(x=output_batch, x_recon=predicted_batch) pred_loss = self.prediction_loss(mu, mu_pred) actLoss = self.loss(recon_loss=recon_loss) actLoss.backward() self.optim.step() running_loss_terminal_display += actLoss.item() running_loss_trainstats += actLoss.item() running_recon_loss_trainstats += recon_loss.item() running_pred_loss_trainstats += pred_loss.item() # update gather object with training information if self.global_iter % self.trainstats_gather_step == 0: running_loss_trainstats = running_loss_trainstats / self.trainstats_gather_step running_recon_loss_trainstats = running_recon_loss_trainstats / self.trainstats_gather_step running_pred_loss_trainstats = running_pred_loss_trainstats / self.trainstats_gather_step self.gather.insert( iter=self.global_iter, total_loss=running_loss_trainstats, target=output_batch[0].detach().cpu().numpy(), reconstructed=predicted_batch[0].detach().cpu().numpy( ), recon_loss=running_recon_loss_trainstats, pred_loss=running_pred_loss_trainstats, ) running_loss_trainstats = 0.0 running_recon_loss_trainstats = 0.0 running_pred_loss_trainstats = 0.0 if plotmode: # plot mini-batches plot_total_loss.append(actLoss.item()) plot_recon_loss.append(recon_loss.item()) plot_pred_loss.append(pred_loss.item()) # PLOT! clear_output(wait=True) fig = plt.figure(figsize=(10, 8)) plt.subplot(4, 3, 1) plt.plot(plot_total_loss) plt.xlabel('minibatches') plt.title('Total loss') plt.subplot(4, 3, 2) plt.plot(plot_recon_loss) plt.xlabel('minibatches') plt.title('Reconstruction training loss') plt.subplot(4, 3, 3) plt.plot(plot_pred_loss) plt.xlabel('minibatches') plt.title('Prediction training loss') # import ipdb; ipdb.set_trace() plt.subplot(4, 3, 4) plt.imshow(input_batch[0][1][0].detach().cpu().numpy()) plt.set_cmap('gray') plt.subplot(4, 3, 5) plt.imshow(input_batch[0][4][0].detach().cpu().numpy()) plt.set_cmap('gray') plt.subplot(4, 3, 6) plt.imshow(input_batch[0][7][0].detach().cpu().numpy()) plt.set_cmap('gray') plt.subplot(4, 3, 7) plt.imshow( predicted_batch[0][1][0].detach().cpu().numpy()) plt.set_cmap('gray') plt.subplot(4, 3, 8) plt.imshow( predicted_batch[0][4][0].detach().cpu().numpy()) plt.set_cmap('gray') plt.subplot(4, 3, 9) plt.imshow( predicted_batch[0][7][0].detach().cpu().numpy()) plt.set_cmap('gray') plt.subplot(4, 3, 10) img = plt.imshow( (input_batch[0][1][0] - predicted_batch[0][1][0]).detach().cpu().numpy()) plt.set_cmap('bwr') colorAxisNormalize(fig.colorbar(img)) plt.subplot(4, 3, 11) img = plt.imshow( (input_batch[0][4][0] - predicted_batch[0][4][0]).detach().cpu().numpy()) plt.set_cmap('bwr') colorAxisNormalize(fig.colorbar(img)) plt.subplot(4, 3, 12) img = plt.imshow( (input_batch[0][7][0] - predicted_batch[0][7][0]).detach().cpu().numpy()) plt.set_cmap('bwr') colorAxisNormalize(fig.colorbar(img)) plt.tight_layout() plt.show() """ /end of non-generic part""" if not plotmode and self.global_iter % self.display_step == 0: pbar.write('iter:{}, loss:{:.3e}'.format( self.global_iter, running_loss_terminal_display / self.display_step)) running_loss_terminal_display = 0.0 if self.global_iter % self.save_step == 0: self.save_checkpoint(self.ckpt_name) pbar.write('Saved checkpoint(iter:{})'.format( self.global_iter)) self.gather.save_data_dict() if self.global_iter >= self.max_iter: out = True break pbar.write("[Training Finished]") pbar.close()