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 main(base_dir): BASE_DIR = base_dir # Load the set of pictures ic = io.ImageCollection(BASE_DIR + '*.JPG') # Select points on the first picture f, ax = plt.subplots(1,1) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.autoscale(enable=True, axis='both', tight=True); plt.tight_layout(pad=0.4, w_pad=0.0, h_pad=0.0) ax.imshow(ic[0]) coords = [plt.ginput(8, timeout=0)] plt.close() # Load first picture side-by side with second, select points. # Scroll through images one-by-one for i, img in enumerate(ic[1:]): ax1 = plt.subplot2grid((6,10),(0,1), rowspan=6, colspan=9) ax0 = plt.subplot2grid((6,10),(0,0)) for ax in [ax0, ax1]: ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.tight_layout(pad=0.4, w_pad=0.0, h_pad=0.0) #f, (ax0,ax1) = plt.subplots(1,2) ax0.imshow(ic[i]) for coord in coords[i]: ax0.scatter(coord[0],coord[1]) ax1.imshow(img) coords.append(plt.ginput(8, timeout=0)) plt.close() # Use a similarity transformation to transform each one. if not os.path.exists(BASE_DIR + 'corrected'): os.mkdir(BASE_DIR + 'corrected') np.save(BASE_DIR + 'corrected/coords.npy', coords) io.imsave(BASE_DIR + 'corrected/0.jpg', ic[0]) for i, img in enumerate(ic[1:]): tf = transform.estimate_transform('similarity', np.array(coords[0]), np.array(coords[i+1])) # Use a translation transformation to center both images for display purposes img_warped = transform.warp(img, inverse_map=tf, output_shape=(1728,3072)) print BASE_DIR + 'corrected/%d.jpg' %(i+1) print img_warped io.imsave(BASE_DIR + 'corrected/%d.jpg' %(i+1), img_warped)
def selectStartGoalPoints(ax, img): print 'Select a starting point' ax.set_xlabel('Select a starting point') occupied = True while(occupied): point = ppl.ginput(1, timeout=-1, show_clicks=False, mouse_pop=2) start = [ round(point[0][0]), round(point[0][1]) ] if(img[int(start[1])][int(start[0])][0] == 255): occupied = False ax.plot(start[0], start[1], '.r') else: print 'Cannot place a starting point there' ax.set_xlabel('Cannot place a starting point there, choose another point') print 'Select a goal point' ax.set_xlabel('Select a goal point') occupied = True while(occupied): point = ppl.ginput(1, timeout=-1, show_clicks=False, mouse_pop=2) goal = [ round(point[0][0]), round(point[0][1]) ] if(img[int(goal[1])][int(goal[0])][0] == 255): occupied = False ax.plot(goal[0], goal[1], '.b') else: print 'Cannot place a goal point there' ax.set_xlabel('Cannot place a goal point there, choose another point') ppl.draw() return start, goal
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')
def manual_sync_pick(flow, gyro_ts, gyro_data): # First pick good points in flow plt.clf() plt.plot(flow) plt.title('Select two points') selected_frames = [int(round(x[0])) for x in plt.ginput(2)] # Now pick good points in gyro plt.clf() plt.subplot(211) plt.plot(flow) plt.plot(selected_frames, flow[selected_frames], 'ro') plt.subplot(212) plt.plot(gyro_ts, gyro_data.T) plt.title('Select corresponding sequence in gyro data') plt.draw() selected = plt.ginput(2) #[int(round(x[0])) for x in plt.ginput(2)] gyro_idxs = [(gyro_ts >= x[0]).nonzero()[0][0] for x in selected] plt.plot(gyro_ts[gyro_idxs], gyro_data[:, gyro_idxs].T, 'ro') plt.title('Ok, click to continue to next') plt.draw() plt.waitforbuttonpress(timeout=10.0) plt.close() return (tuple(selected_frames), gyro_idxs)
def trainZone(self,event): if str(event.keysym) == 'space': flag, frame = self.cap.read() if flag == True: #~ grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) plt.imshow(frame) #~ self.mask = np.zeros(frame.shape[:2],dtype = 'uint8') pnt1 = np.int32(plt.ginput(n=0, timeout=-1, show_clicks=True)) self.pnt1 = pnt1.reshape((-1,1,2)) xMax = max(self.pnt1[:,:,0])[0] yMax = max(self.pnt1[:,:,1])[0] xMin = min(self.pnt1[:,:,0])[0] yMin = min(self.pnt1[:,:,1])[0] cv2.polylines(frame,[self.pnt1],True,(0,255,255),thickness=3) plt.imshow(frame) pnt2 = np.int32(plt.ginput(n=0, timeout=-1, show_clicks=True)) self.pnt2 = pnt2.reshape((-1,1,2)) xMax = max(self.pnt2[:,:,0])[0] yMax = max(self.pnt2[:,:,1])[0] xMin = min(self.pnt2[:,:,0])[0] yMin = min(self.pnt2[:,:,1])[0] cv2.polylines(frame,[self.pnt2],True,(0,255,255),thickness=3) plt.imshow(frame)
def solver(N): for i in range(N): for j in range(N): vic, tab = maneja_reinas(reinas, 'Agregar reina', i, j) img_reinas.set_data(tab) plt.draw() plt.ginput() if vic: fig.text( 0.5, 0.5, 'Felicitaciones!', color='orange', size='xx-large', family='humor sans', ha='center', va='center', alpha=0.5, bbox=dict(facecolor='ivory', edgecolor='orange', boxstyle='round') ) plt.draw() plt.ginput() if tab[i][j]==4: if i in range(N) and j in range(N): vic, tab = maneja_reinas(reinas, 'Agregar reina', i, j) j=j+1 print ("{}{}".format(i,j))
def get_point(im1, im2): plt.imshow(im1) im1_pt = plt.ginput()[0] plt.close() plt.imshow(im2) im2_pt = plt.ginput()[0] plt.close() return im1_pt,im2_pt
def get_points(im1, im2): print('Please select 2 points in each image for alignment.') plt.imshow(im1) p1, p2 = plt.ginput(2) plt.close() plt.imshow(im2) p3, p4 = plt.ginput(2) plt.close() return (p1, p2, p3, p4)
def tps_rpm(x_nd, y_md, n_iter = 5, reg_init = .1, reg_final = .001, rad_init = .2, rad_final = .001, plotting = False, verbose=True, f_init = None): n,d = x_nd.shape regs = loglinspace(reg_init, reg_final, n_iter) rads = loglinspace(rad_init, rad_final, n_iter) f = ThinPlateSpline.identity(d) for i in xrange(n_iter): if f.d==2 and i%plotting==0: import matplotlib.pyplot as plt plt.clf() if i==0 and f_init is not None: xwarped_nd = f_init(x_nd) print xwarped_nd.max(axis=0) else: xwarped_nd = f.transform_points(x_nd) # targ_nd = find_targets(x_nd, y_md, corr_opts = dict(r = rads[i], p = .1)) corr_nm = calc_correspondence_matrix(xwarped_nd, y_md, r=rads[i], p=.2) wt_n = corr_nm.sum(axis=1) targ_nd = np.dot(corr_nm/wt_n[:,None], y_md) # if plotting: # plot_correspondence(x_nd, targ_nd) f.fit(x_nd, targ_nd, regs[i], wt_n = wt_n, angular_spring = regs[i]*200, verbose=verbose) if plotting and i%plotting==0: if f.d==2: plt.plot(x_nd[:,1], x_nd[:,0],'r.') plt.plot(y_md[:,1], y_md[:,0], 'b.') pred = f.transform_points(x_nd) if f.d==2: plt.plot(pred[:,1], pred[:,0], 'g.') if f.d == 2: plot_warped_grid_2d(f.transform_points, x_nd.min(axis=0), x_nd.max(axis=0)) plt.ginput() elif f.d == 3: from lfd import warping from brett2.ros_utils import Marker from utils import conversions Globals.setup() mins = x_nd.min(axis=0) maxes = x_nd.max(axis=0) mins[2] -= .1 maxes[2] += .1 Globals.handles = warping.draw_grid(Globals.rviz, f.transform_points, mins, maxes, 'base_footprint', xres=.1, yres=.1) orig_pose_array = conversions.array_to_pose_array(x_nd, "base_footprint") target_pose_array = conversions.array_to_pose_array(y_md, "base_footprint") warped_pose_array = conversions.array_to_pose_array(f.transform_points(x_nd), 'base_footprint') Globals.handles.append(Globals.rviz.draw_curve(orig_pose_array,rgba=(1,0,0,1),type=Marker.CUBE_LIST)) Globals.handles.append(Globals.rviz.draw_curve(target_pose_array,rgba=(0,0,1,1),type=Marker.CUBE_LIST)) Globals.handles.append(Globals.rviz.draw_curve(warped_pose_array,rgba=(0,1,0,1),type=Marker.CUBE_LIST)) f.corr = corr_nm return f
def checkSignals(self): from matplotlib.pyplot import plot, figure, close, ginput for i in range(0, len(self.Signals)): print('Signal ' + str(i)) s = self.Signals[i] if not self.isGoodSignal(s, self.SamplingPeriod): figure() plot(s) ginput(timeout=0) close("all")
def plot_cost(grid): import matplotlib.pyplot as plt import scipy.stats as ss plt.clf() #plot_arr = ss.rankdata(grid.array).reshape(grid.array.shape) plot_arr = grid.array print grid.array.max(), grid.array.min() plt.imshow(plot_arr, extent = [grid.xticks[0], grid.xticks[-1], grid.yticks[0], grid.yticks[-1]]) plt.title("cost") print "click on the plot to continue" plt.ginput()
def _ginput(*args, **kwargs): """ Hides the stupid default warnings when using ginput. There has to be a better way... """ if MatplotlibDeprecationWarning is None: return plt.ginput(*args, **kwargs) else: warnings.simplefilter('ignore', MatplotlibDeprecationWarning) out = plt.ginput(*args, **kwargs) warnings.warn('default', MatplotlibDeprecationWarning) return out
def pickloc(ax=None, zoom=10): """ :INPUTS: ax : (axes instance) -- axes in which to pick a location zoom : int -- zoom radius for target confirmation : 2-tuple -- (x,y) radii for zoom confirmation. """ # 2011-04-29 19:26 IJC: # 2011-09-03 20:59 IJMC: Zoom can now be a tuple; x,y not cast as int. pickedloc = False if ax is None: ax = plt.gca() axlimits = ax.axis() if hasattr(zoom, '__iter__') and len(zoom)>1: xzoom, yzoom = zoom else: xzoom = zoom yzoom = zoom while not pickedloc: ax.set_title("click to select location") ax.axis(axlimits) x = None while x is None: selectevent = plt.ginput(n=1,show_clicks=False) if len(selectevent)>0: # Prevent user from cancelling out. x,y = selectevent[0] #x = x.astype(int) #y = y.astype(int) if zoom is not None: ax.axis([x-xzoom,x+xzoom,y-yzoom,y+yzoom]) ax.set_title("you selected xy=(%i,%i)\nclick again to confirm, or press Enter/Return to try again" %(x,y) ) plt.draw() confirmevent = plt.ginput(n=1,show_clicks=False) if len(confirmevent)>0: pickedloc = True loc = confirmevent[0] return loc
def get_all_linepoints_user_input(ImgName, DirToSave, NumPointVecs=45): # user input to select lines for enhanced measurement detection Img = cv2.imread(ImgName, 0) if not os.path.isfile(ImgName): raise Exception("Accumulated image not defined or not on right path", "raised in get_all_linepoints_user_input") cOrigImg = cv2.cvtColor(Img, cv2.COLOR_GRAY2BGR) if not os.path.isfile(DirToSave + "/LinePoints.p"): print "pick lines" plt.ion() Lines = [] for i in range(0, NumPointVecs / 3): while True: cImg = cOrigImg.copy() TryAgain = [] plt.title("Please click 3 lines") plt.imshow(cImg) RawLineUV = plt.ginput(6) LineUV = [RawLineUV[i:i + 2] for i in range(0, len(RawLineUV), 2)] if len(LineUV) == 3: # convert ot int for CurLineUV in LineUV: LineUVShow = [(int(x[0]), int(x[1])) for x in CurLineUV] cv2.line(cImg, LineUVShow[0], LineUVShow[1], (255, 0, 0), 2) plt.title("click on lower half of image to accept, on upper to neglect") plt.imshow(cImg) # click on image to do anew UV = plt.ginput(1) if not not UV and UV[0][1] > Img.shape[0] / 2: break Lines.extend(LineUV) cv2.line(cOrigImg, LineUVShow[0], LineUVShow[1], (255, 0, 0), 2) pickle.dump(Lines, open(DirToSave + "/LinePoints.p", "wb")) print "saved lines as " + DirToSave + "/LinePoints.p" else: print "!!!!!!!!!!!!!! loading lines !!!!!!!!!!!!!!!!!" Lines = pickle.load(open(DirToSave + "/LinePoints.p", "rb")) cImg = cOrigImg.copy() for Line in Lines: CurLine = [(int(x[0]), int(x[1])) for x in Line] cv2.line(cOrigImg, CurLine[0], CurLine[1], (255, 0, 0), 2) plt.imshow(cOrigImg) plt.ioff() print "please close the window" plt.show() # sort left and right return sorted(Lines, key=lambda x: x[0][0]), cImg
def findall(tree,all_files): for f in all_files: fsg=getHash3(f) d,ids=tree.query(fsg,k=10) plt.figure(1) for i,index in enumerate(ids): print "%03d dis: %.3f %s"%(index,d[i],all_files[index]) plt.subplot(2,5,i+1) plt.title("%03d dis: %.3f"%(index,d[i]),fontsize=10) im_icon=np.array(Image.open(all_files[index]).convert('L')) plt.imshow(im_icon) plt.axis('off') plt.set_cmap('gray') plt.show() plt.ginput(1)
def cut_bounds(self, data): def tellme(s): print s plt.title(s,fontsize=16) plt.draw() plt.clf() plt.plot(data) plt.setp(plt.gca(),autoscale_on=False) tellme('You will select start and end bounds. Click to continue') plt.waitforbuttonpress() happy = False while not happy: pts = [] while len(pts) < 2: tellme('Select 2 bounding points with mouse') pts = plt.ginput(2,timeout=-1) if len(pts) < 2: tellme('Too few points, starting over') time.sleep(1) # Wait a second plt.fill_between(x, y1, y2, alpha=0.5, facecolor='grey', interpolate=True) tellme('Happy? Key click for yes, mouse click for no') happy = plt.waitforbuttonpress() bounds = sorted([int(i[0]) for i in pts]) plt.clf() print bounds return data[bounds[0] if bounds[0] > .02*len(data) else 0:bounds[1] if bounds[1] < len(data)-1 else len(data)-1],bounds
def callback(self, img, depth): ## Get image as numpy array rgb = self.bridge.imgmsg_to_cv(img) img = np.asarray(rgb) self.marker_finder.findmarker(img) detections = self.marker_finder.detections() if len(detections) != 2: return vis = self.marker_finder.draw_detections(img) depth_16 = np.asarray( self.bridge.imgmsg_to_cv(depth, desired_encoding="passthrough")) depth = depth_16 / np.float32(1000.) lpt, rpt = [c.astype(np.int) for c, r, _ in detections] if np.max(depth_16) == 0: return lz = depth[lpt[1], lpt[0]] rz = depth[rpt[1], rpt[0]] if lz == 0 or rz == 0 or self.Kinv is None: return plt.clf() plt.imshow(vis) _, campt, _ = plt.ginput(3, timeout=-1) camz = depth[campt[0], campt[1]] print "Left marker", self.pt3d_from_imgpt(lpt, lz) print "Right marker", self.pt3d_from_imgpt(rpt, rz)
def GINPUT_ROUTINE(image, selected_pointsrow, selected_pointscolumn): '''INPUT: image = where points are supposed to be selected OUTPUT: image image with modified values ''' PLOT_IMAGE(image) print ("Please selected 2 points") pts = plt.ginput(n=2, timeout=10) pts = np.array(pts) c = int(pts[0][0]) r = int(pts[0][1]) c1 = int(pts[1][0]) r1 = int(pts[1][1]) selected_pointsrow.append(r) selected_pointsrow.append(r1) selected_pointscolumn.append(c) selected_pointscolumn.append(c1) modified_pixeel_value = image[int(r)][int(c)] for row in range(r, r1): for col in range(c, c1): image[row][col] = modified_pixeel_value # plt.show() return image, selected_pointsrow, selected_pointscolumn
def get_windows(image): """Display the given image and record user selected points. Parameters ---------- image : M,N,3 ndarray The image to be displayed. Returns ------- array : n_points,2 An array of coordinates in the image. Each row corresponds to the x, y coordinates of one point. If an odd number of points are specified, the last one will be discarded. """ plt.interactive(True) plt.imshow(image) plt.show() crop = plt.ginput(0) plt.close() plt.interactive(False) # remove last point if an odd number selected crop = crop[:-1] if np.mod(len(crop), 2) else crop return np.vstack(crop).astype('int')[:, [1, 0]]
def play(self): while True: pos = plt.ginput(1,timeout=-1)[0] node = self.which_clicked(pos) if node is None: continue elif node == self.position[0]: # clicking on self will undo last move if self.previous_positions != []: self.update( self.previous_positions.pop() ) self.switch_colors(antisense=True) self.draw() else: if node in self.next_pos: self.previous_positions.append(self.position) self.update( self.next_pos[node] ) self.switch_colors() self.draw() if self.position == self.states_graph.goal: break self.ax.set_title("Congrats, you win !") self.ax.figure.canvas.draw()
def getCorrespondence(imageA, imageB): getAuto = int(1); # num = 8; num = 20; if(getAuto == 0): # Display images, select matching points fig = plt.figure() figA = fig.add_subplot(1,2,1) figB = fig.add_subplot(1,2,2) # Display the image # lower use to flip the image figA.imshow(imageA)#,origin='lower') figB.imshow(imageB)#,origin='lower') plt.axis('image') # n = number of points to read pts = plt.ginput(n=num, timeout=0) print(pts); pts = np.reshape(pts, (2, num/2, 2)) print(pts); return pts # mountain pts = np.array([(290.99673461310101, 168.49247971502086), (351.77211557490591, 132.47743914506236), (381.03433603799715, 139.23025925192962), (455.31535721353646, 161.7396596081536), (471.07193746289317, 148.23401939441919), (511.58885810409652, 175.24529982188801), (507.08697803285168, 359.82238274292507), (403.54373639422113, 319.30546210172179), (390.03809618048672, 341.81486245794582), (290.99673461310101, 359.82238274292507), (5.9867999208391893, 139.23025925192951), (80.267821096378498, 109.96803878883827), (107.27910152384732, 121.22273896695026), (177.05824262814178, 161.73965960815349), (195.06576291312103, 148.23401939441908), (224.32798337621227, 175.2452998218879), (208.57140312685544, 353.06956263605764), (98.275341381357748, 303.54888185236484), (82.518761132000918, 326.05828220858882), (3.7358598852168825, 353.06956263605764)]) # tower 11_22 # pts = np.array([(749.08560430737248, 492.08751712086166), (576.71815519765732, 604.87115666178647), (774.62152269399712, 628.27908184952548), (908.68509422377565, 536.7753742974545), (294.87512870164869, 455.91163273981022), (107.61172719973592, 568.69527228073491), (311.89907429273171, 592.10319746847404), (445.96264582251024, 506.98346951305916)]) # tower 22_11 # pts = np.array([(295.82305294478812, 458.03962593869562), (104.30366504510459, 570.82326547962043), (310.71900533698573, 589.97520426958886), (451.16655646342036, 464.42360553535173), (746.0096868653477, 492.08751712086155), (575.77023095451796, 606.99914986067165), (773.67359845085775, 626.15108865063996), (911.99315637840664, 494.21551031974684)]) pts = np.reshape(pts, (2, num/2, 2)) return pts
def genData_interactive(numClasses,numClicks): ''' Generate a 2D data set interactively by letting the user click on the axes to distribute the points. Each click generates 20 points randomly sampled from an isotropic Gaussian. Multiple classes are possible. numClicks it the number of clicks per class. Data set array X is returned (numClasses*numClicks x 2) and Y Classes vector ''' kPer = 20 kSigma = [[0.3,0.0],[0.0,0.3]] plt.figure() plt.axis([-10,10,-10,10]) plt.show() X = np.zeros([kPer*numClicks*numClasses,2]) Y = np.zeros([kPer*numClicks*numClasses],dtype=np.int16) for c in range(numClasses): for i in range(numClicks): plt.title('Sampling Clicks For Class %d/%d, Click %d/%d'%(c,numClasses,i,numClicks)) x = np.squeeze(plt.ginput(1)) xsamples = genData_gaussian(x,kSigma,kPer) current = c*kPer*numClicks + i*kPer X[current:current+kPer,:] = xsamples Y[current:current+kPer ] = c*np.ones([kPer],dtype=np.int16) plt.plot(xsamples[:,0],xsamples[:,1],kDraw[c%len(kDraw)],hold=True) plt.title('Done Sampling Data') return (X,Y)
def mcmc_explore(self,niter=30,stepsize=0.5): """Explore the space of PSFs.""" current_pos = self.lle_proj[0] current_density = self.lle_density(current_pos) print("Computing overall background density for plotting...") density, extent = self.display_lle_space(return_density=True) for i in range(niter): plt.clf() plt.subplot(121) jump = np.random.normal(size=self.ndim)*stepsize*self.h_density trial = current_pos + jump new_density = self.lle_density(trial) if new_density/current_density > np.random.random(): current_density = new_density current_pos = trial psf = self.find_lle_psf(current_pos, return_image=True) plt.imshow(np.arcsinh(psf/np.max(psf)/0.01),interpolation='nearest', cmap=cm.cubehelix) plt.title("lnprob: {0:5.1f}".format(current_density)) plt.subplot(122) plt.imshow(density,extent=extent,cmap=cm.gray) plt.plot(self.tri.points[:,0],self.tri.points[:,1],'b.') plt.title("Pos: {0:5.2f} {1:5.2f}".format(current_pos[0], current_pos[1])) plt.plot(current_pos[0], current_pos[1], 'ro') plt.axis(extent) plt.draw() #!!! Problem: Current matplotlib does not draw here. !!! dummy = plt.ginput(1) return None
def decasteljau_interactive(n): """ Makes an interactive plot using a slider bar to show the Decasteljau algorithm at different times.""" ax = plt.subplot(1, 1, 1) plt.subplots_adjust(bottom=0.25) plt.axis([-1, 1, -1, 1]) axT = plt.axes([0.25, 0.1, 0.65, 0.03]) sT = wg.Slider(axT, 't', 0, 1, valinit=0) pts = plt.ginput(n, timeout=240) plt.subplot(1, 1, 1) pts = np.array(pts) plt.cla() T0=0 decasteljau_animated(pts, T0) plt.axis([-1, 1, -1, 1]) plt.draw() def update(val): T = sT.val ax.cla() plt.subplot(1, 1, 1) decasteljau_animated(pts,T) plt.xlim((-1, 1)) plt.ylim((-1,1)) plt.draw() sT.on_changed(update) plt.show()
def measure(self,line): h,w = line.shape smoothed = filters.gaussian_filter(line,(h*0.5,h*self.smoothness),mode='constant') smoothed += 0.001*filters.uniform_filter(smoothed,(h*0.5,w),mode='constant') self.shape = (h,w) a = np.argmax(smoothed,axis=0) a = filters.gaussian_filter(a,h*self.extra) self.center = np.array(a,'i') deltas = np.abs(np.arange(h)[:,np.newaxis]-self.center[np.newaxis,:]) self.mad = np.mean(deltas[line!=0]) self.r = int(1+self.range*self.mad) if self.debug: plt.figure("center") plt.imshow(line,cmap=plt.cm.gray) plt.plot(self.center) plt.ginput(1,1000)
def infernoise_interactive(deg=4,lmbda=0.): plt.axes() plt.xlim([-10,10]) plt.ylim([-10,10]) a = PolyRegressionInferNoise(w_0=zeros(deg+1),V_0=eye(deg+1),a_0=5,b_0=1.) t = np.linspace(-10,10,100) points = [] while True: newpoint = plt.ginput() if newpoint == []: return a points += newpoint x,y = points[-1] plt.cla() plt.plot([p[0] for p in points],[p[1] for p in points],'kx') a.condition_on(y,x) predictions, errors = a.predict(t) plt.plot(t,predictions,'b-') plt.plot(t,predictions+np.sqrt(errors),'b--') plt.plot(t,predictions-np.sqrt(errors),'b--') for i in range(3): predictions, _ = a.predict_sample(t) plt.plot(t,predictions,'r-',alpha=0.5) plt.xlim([-10,10]) plt.ylim([-10,10])
def normalize_spectrum(wl, net, kernel_size = 201): fig = pyplot.figure(figsize = [22, 7]) ax = fig.add_subplot(1,1,1) wl = wl.flatten() net = net.flatten() ax.plot(wl, net, 'b') background_wl = np.empty((0,)) background_net = np.empty((0,)) raw_input('Zoom in on spectrum and press enter to continue ') select_another_region = 'y' print 'Select background regions ' while select_another_region != 'n': pt1, pt2 = pyplot.ginput(n = 2, timeout = -1) x1, y1 = pt1 x2, y2 = pt2 background_indx = np.where((wl < max(x1, x2)) & (wl > min(x1, x2))) background_wl = np.append(background_wl, wl[background_indx]) background_net = np.append(background_net, net[background_indx]) pyplot.plot([wl[background_indx[0][0]], wl[background_indx[0][-1]]], [net[background_indx[0][0]], net[background_indx[0][-1]]], 'm--|', lw = 3) select_another_region = raw_input('Would you like to select another background regions? (y), n ') background_wl = background_wl.flatten() background_net = background_net.flatten() sort_indx = np.argsort(background_wl) background_wl = background_wl[sort_indx] background_net = background_net[sort_indx] poly_coeff = np.polyfit(background_wl, background_net, 3) continuum = np.polyval(poly_coeff, wl) ax.plot(wl, continuum, 'c', lw = 2) pyplot.draw() return wl, net/continuum, continuum
def get_shape(img, img_name, extension): shape_filename = "data/" + img_name + "_points" + extension if os.path.isfile(shape_filename): shape = np.loadtxt(shape_filename) else: img_plot = plt.imshow(img) prev_input, x_coor, y_coor = (0, 0), [], [] while True: x, y = plt.ginput(1)[0] x, y = int(x), int(y) if (x, y) == prev_input: break prev_input = (x, y) x_coor.append(x); y_coor.append(y); plt.plot(x_coor, y_coor, 'y') plt.draw() plt.close('all') coordinates = np.array((np.array(x_coor), np.array(y_coor))) shape = coordinates.T tlc, trc, blc, brc = [0, 0], [0, img.shape[0]], [img.shape[1], 0], [img.shape[1], img.shape[0]] shape = np.vstack([shape, np.array([tlc, trc, blc, brc])]) np.savetxt(shape_filename, shape) return shape
def select_points(img, img_name, folder, extension): shape_filename = "data/" + folder + img_name + "_points" + extension if os.path.isfile(shape_filename): shape = np.loadtxt(shape_filename) else: print ("Please select correspondence points for the image.") img_plot = plt.imshow(img) plt.suptitle('Please select points') points, x_coor, y_coor = (0, 0), [], [] plt.xlim(0, img.shape[1]) plt.ylim(img.shape[0], 0) while True: x, y = plt.ginput(n=1, timeout=0)[0] x, y = int(x), int(y) if points and (x, y) == points: break; points = (x, y) x_coor.append(x); y_coor.append(y); plt.plot(x_coor, y_coor, 'bs') plt.draw() plt.close('all') coordinates = np.array((np.array(x_coor), np.array(y_coor))) shape = coordinates.T np.savetxt(shape_filename, shape) return shape
from nilearn import plotting a = np.array(skimage.transform.resize(img.dataobj, (60, 90))) img_gray = a[:, :, 128] #normalizo la imagen, el rango irá a partir de ahora [0,1], así que ojo a la hora de meter rangos en region growing img_o = img_gray img_o = img_o / np.max(img_o) #%% #def RegionGrowingP2(img, rango_inferior, rango_superior): plt.imshow(img_o, cmap='gray') click_markers = plt.ginput(n=1, timeout=30) print(click_markers[0]) click_markers = list(click_markers[0]) print(click_markers) markers = [round(num) for num in click_markers] seed = [markers[1], markers[0]] print(seed) # [img_pad[i-1,j-1],img_pad[i-1,j],img_pad[i-1,j+1]], # [img_pad[i,j-1],img_pad[i,j],img_pad[i,j+1]], # [img_pad[i+1,j-1],img_pad[i+1,j],img_pad[i+1,j+1] #%% coords = np.array([(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)])
#plt.subplot(1,2,2) #plt.plot(y_axis,his1/his1.sum(), linewidth=3, alpha=0.5) #plt.xlabel(r'$\varphi \ (Degrees)$', fontsize=25) fig = plt.figure(figsize=(10, 8)) plt.contourf(-np.ma.log(his.T / his.sum()), 25, cmap='gnuplot', extent=model.extent) plt.xlabel(r'$X$') plt.ylabel(r'$Y$') plt.colorbar() fig.show() coords = [] #def onclick(event): # global ix, iy # ix, iy = event.xdata, event.ydata # print('x = %d, y = %d'%( # ix, iy)) # # global coords # coords.append((ix, iy)) # return coords #cid = fig.canvas.mpl_connect('button_press_event', onclick) coords = plt.ginput(-1, show_clicks=True) #plt.savefig("fes_"+str(mode)+".pdf") print(coords) np.savetxt(path + 'coords_' + str(mode) + '.dat', coords)
def getCorrespondence(image1, image2, numOfPoints_=8, manualSelection_=True): manualSelection = manualSelection_ numOfPoints = numOfPoints_ if (numOfPoints < 8): print("Error: Num of paris must be greater or equal 4") return if (manualSelection): # Display images, select matching points fig = plt.figure() fig1 = fig.add_subplot(1, 2, 1) fig2 = fig.add_subplot(1, 2, 2) # Display the image fig1.imshow(image1) fig2.imshow(image2) plt.axis('image') pts = plt.ginput(n=numOfPoints, timeout=0) pts = np.reshape(pts, (2, int(numOfPoints / 2), 2)) # print(pts); return pts else: """ automatic selection process """ numOfPoints = 20 img1 = cv2.imread('../images/mountain/image1.jpg', 0) img2 = cv2.imread('../images/mountain/image2.jpg', 0) # Initiate SIFT detector orb = cv2.ORB() # find the keypoints and descriptors with SIFT kp1, des1 = orb.detectAndCompute(img1, None) kp2, des2 = orb.detectAndCompute(img2, None) # create BFMatcher object bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) # Match descriptors. matches = bf.match(des1, des2) # Sort them in the order of their distance. matches = sorted(matches, key=lambda x: x.distance) print(matches) return matches # 10 to 10 mountain points pts = np.array([(290.99673461310101, 168.49247971502086), (351.77211557490591, 132.47743914506236), (381.03433603799715, 139.23025925192962), (455.31535721353646, 161.7396596081536), (471.07193746289317, 148.23401939441919), (511.58885810409652, 175.24529982188801), (507.08697803285168, 359.82238274292507), (403.54373639422113, 319.30546210172179), (390.03809618048672, 341.81486245794582), (290.99673461310101, 359.82238274292507), (5.9867999208391893, 139.23025925192951), (80.267821096378498, 109.96803878883827), (107.27910152384732, 121.22273896695026), (177.05824262814178, 161.73965960815349), (195.06576291312103, 148.23401939441908), (224.32798337621227, 175.2452998218879), (208.57140312685544, 353.06956263605764), (98.275341381357748, 303.54888185236484), (82.518761132000918, 326.05828220858882), (3.7358598852168825, 353.06956263605764)]) pts = np.reshape(pts, (2, int(numOfPoints / 2), 2)) return pts
def womgau(hop): """fit gaussian to line""" import numpy as np import logging import matplotlib.pyplot as plt from scipy.optimize import curve_fit from tmath.wombat.womwaverange import womwaverange from tmath.wombat.womget_element import womget_element from tmath.wombat.inputter import inputter from tmath.wombat.inputter_single import inputter_single from tmath.wombat.gauss import gauss from tmath.wombat.gauss_cont import gauss_cont from tmath.wombat.yesno import yesno print(' ') logging.info('Object is {}'.format(hop[0].obname)) print(' ') print('Spectrum runs from {} to {}'.format(hop[0].wave[0], hop[0].wave[-1])) print(' ') print('This routine expects the spectrum to be in flambda units.') print('It also expects a linear wavelength scale.') print(' ') print('Choose general region of spectrum\n') nwave, nflux, mode = womwaverange(hop[0].wave, hop[0].flux, 'none') print('\nNow pick the exact range for the fit') waveint, fluxint, mode = womwaverange(nwave, nflux, mode) indexblue = womget_element(nwave, waveint[0]) indexred = womget_element(nwave, waveint[-1]) if (mode == 'w'): done = False while (not done): print(' ') wavecenter = inputter('Enter approximate center of Gaussian : ', 'float', False) indexcenter = womget_element(waveint, wavecenter) if (indexcenter <= 0) or (wavecenter > waveint[-1]): print('Bad central wavelength, try again') else: done = True else: done = False while (not done): print('Mark the approximate center of the Gaussian') pickcent = plt.ginput(1, timeout=-1) indexcenter = womget_element(waveint, pickcent[0][0]) print('\nApproximate center at {}'.format(waveint[indexcenter])) print('\nIs this OK?') answer = yesno('y') if (answer == 'y'): done = True weights = np.sqrt(hop[0].var[indexblue:indexred + 1]) print(' ') continuum = inputter_single( 'Do you want to fit gaussian with (c)ontinuum, or (n)o continuum? ', 'cn') if (continuum == 'c'): p = [fluxint[indexcenter], waveint[indexcenter], 3.0, 1.0, waveint[0]] result = curve_fit(gauss_cont, waveint, fluxint, sigma=weights, p0=p, absolute_sigma=True, full_output=True) else: p = [fluxint[indexcenter], waveint[indexcenter], 3.0] result = curve_fit(gauss, waveint, fluxint, sigma=weights, p0=p, absolute_sigma=True, full_output=True) coefferr = np.sqrt(np.diag(result[1])) coeff = result[0] # make 'finer-grained' version of fit, 0.2A/pix for calculations wavecalc = np.arange(2 * 5 * 50 * abs( coeff[2])) * 0.2 + coeff[1] - 0.2 * 5 * 50 * abs(coeff[2]) calccenter = womget_element(wavecalc, coeff[1]) if (continuum == 'c'): fluxcalc = gauss_cont(wavecalc, *coeff) fluxcont = wavecalc * coeff[3] + coeff[4] fluxgaussian = fluxcalc - fluxcont linecont = fluxcont[calccenter] else: fluxcalc = gauss(wavecalc, *coeff) deltafit = wavecalc[1] - wavecalc[0] calcindexblue = womget_element(wavecalc, waveint[0]) calcindexred = womget_element(wavecalc, waveint[-1]) sumfluxcalc = np.sum(fluxcalc[calcindexblue:calcindexred + 1] * deltafit) sumallfluxcalc = np.sum(fluxcalc * deltafit) chi = (result[2]['fvec']**2).sum() redchi = chi / (len(waveint) - len(coeff)) if (continuum == 'c'): sumfluxgaussian = np.sum(fluxgaussian[calcindexblue:calcindexred + 1] * deltafit) sumallfluxgaussian = np.sum(fluxgaussian * deltafit) sumfluxcont = np.sum(fluxcont[calcindexblue:calcindexred + 1] * deltafit) sumallfluxcont = np.sum(fluxcont * deltafit) # propagate uncertainty (from old version) not sure this is correct height_pct = coefferr[0] / coeff[0] sigma_pct = coefferr[2] / coeff[2] flux_pct = np.sqrt(height_pct**2 + sigma_pct**2) sumfluxgaussiansig = sumfluxgaussian * flux_pct sumallfluxgaussiansig = sumallfluxgaussian * flux_pct plt.cla() plt.plot(nwave, nflux, drawstyle='steps-mid', color='k') plt.ylabel('Flux') plt.xlabel('Wavelength') xmin, xmax = plt.xlim() ymin, ymax = plt.ylim() plt.plot(wavecalc, fluxcalc, drawstyle='steps-mid', color='b') if (continuum == 'c'): plt.plot(wavecalc, fluxgaussian, drawstyle='steps-mid', color='r') plt.plot(wavecalc, fluxcont, drawstyle='steps-mid', color='g') plt.plot([waveint[0], waveint[0]], [ymin, ymax], color='k', linestyle='--') plt.plot([waveint[-1], waveint[-1]], [ymin, ymax], color='k', linestyle='--') plt.xlim([xmin, xmax]) plt.ylim([ymin, ymax]) logging.info('For object {} Gaussian fit'.format(hop[0].obname)) if (continuum == 'c'): print( '\nData = Black, Fit = Blue, Continuum = Green, Fit-Continuum = Red\n' ) else: print('\nData = Black, Fit = Blue\n') logging.info('Height {:16.8f}+/-{:16.8f}'.format( coeff[0], coefferr[0])) logging.info('Center {:16.8f}+/-{:16.8f}'.format( coeff[1], coefferr[1])) logging.info('Sigma {:16.8f}+/-{:16.8f}'.format( coeff[2], coefferr[2])) if (continuum == 'c'): logging.info('Slope {:16.8f}+/-{:16.8f}'.format( coeff[3], coefferr[3])) logging.info('Y-intercept {:16.8f}+/-{:16.8f}'.format( coeff[4], coefferr[4])) logging.info('FWHM {:16.8f}+/-{:16.8f}'.format( 2.35482 * np.abs(coeff[2]), 2.35482 * coefferr[2])) logging.info( 'Flux between dotted lines (Gaussian): {:16.8f}+/-{:16.8f}'.format( sumfluxgaussian, sumfluxgaussiansig)) logging.info('EW between dotted lines (Gaussian): {:16.8f}'.format( sumfluxgaussian / linecont)) logging.info('Flux for full (Gaussian): {:16.8f}+/-{:16.8f}'.format( sumallfluxgaussian, sumallfluxgaussiansig)) logging.info('EW for full (Gaussian): {:16.8f}'.format( sumallfluxgaussian / linecont)) logging.info( 'Continuum flux at line center: {:16.8f}'.format(linecont)) logging.info('Chi^2: {}'.format(chi)) logging.info('Reduced chi^2: {}'.format(redchi)) logging.info('All fluxes might need to be scaled by 1e-15') print(' ') return hop
def normalize(self, plot=True, norm_method='linear'): """ Normalize the region if the data are not already normalized. Choose from two methods: 1: define left and right continuum regions and fit a linear continuum. 2: define the continuum as a range of points and use spline interpolation to infer the continuum. """ if norm_method == 'linear': norm_num = 1 elif norm_method == 'spline': norm_num = 2 else: err_msg = "Invalid norm_method: %r" % norm_method raise ValueError(err_msg) plt.close('all') plt.figure() dx = 0.1 * (self.wl.max() - self.wl.min()) lines_title_string = ", ".join([line.tag for line in self.lines]) plt.xlim(self.wl.min() - dx, self.wl.max() + dx) plt.ylim(0.8 * self.flux.min(), 1.2 * self.flux.max()) plt.plot(self.wl, self.flux, color='k', drawstyle='steps-mid', label=lines_title_string) plt.xlabel("Wavelength [${\\rm \AA}$]") if norm_num == 1: # - Normalize by defining a left and right continuum region print "\n\n Mark left continuum region, left and right boundary." plt.title("Mark left continuum region, left and right boundary.") bounds = plt.ginput(2, -1) left_bound = min(bounds[0][0], bounds[1][0]) right_bound = max(bounds[0][0], bounds[1][0]) region1 = (self.wl >= left_bound) * (self.wl <= right_bound) fit_wl = self.wl[region1] fit_flux = self.flux[region1] lines_title_string = ", ".join([line.tag for line in self.lines]) plt.title(lines_title_string) print "\n Mark right continuum region, left and right boundary." plt.title("Mark right continuum region, left and right boundary.") bounds = plt.ginput(2) left_bound = min(bounds[0][0], bounds[1][0]) right_bound = max(bounds[0][0], bounds[1][0]) region2 = (self.wl >= left_bound) * (self.wl <= right_bound) fit_wl = np.concatenate([fit_wl, self.wl[region2]]) fit_flux = np.concatenate([fit_flux, self.flux[region2]]) popt, pcov = curve_fit(linfunc, fit_wl, fit_flux) continuum = linfunc(self.wl, *popt) e_continuum = np.std(fit_flux - linfunc(fit_wl, *popt)) elif norm_num == 2: # Normalize by drawing the continuum and perform spline # interpolation between the points print "\n\n Select a range of continuum spline points over the whole range" plt.title( " Select a range of continuum spline points over the whole range" ) points = plt.ginput(n=-1, timeout=-1) xk, yk = [], [] for x, y in points: xk.append(x) yk.append(y) xk = np.array(xk) yk = np.array(yk) region_wl = self.wl.copy() continuum = spline(xk, yk, region_wl, order=3) e_continuum = np.sqrt(np.mean(self.err**2)) if plot: new_flux = self.flux / continuum new_err = self.err / continuum plt.cla() plt.plot(self.wl, new_flux, color='k', drawstyle='steps-mid', label=lines_title_string) plt.xlabel("Wavelength [${\\rm \AA}$]") plt.title("Normalized") plt.axhline(1., ls='--', color='k') plt.axhline(1. + e_continuum / np.mean(continuum), ls=':', color='gray') plt.axhline(1. - e_continuum / np.mean(continuum), ls=':', color='gray') plt.show(block=False) plt.title("Go back to terminal...") prompt = raw_input(" Is normalization correct? (YES/no) ") if prompt.lower() in ['', 'y', 'yes']: self.flux = new_flux self.err = new_err self.cont_err = e_continuum / np.median(continuum) self.normalized = True return 1 else: return 0 else: self.flux = self.flux / continuum self.err = self.err / continuum self.cont_err = e_continuum / np.mean(continuum) self.normalized = True return 1
def run_align_atlas_gui_simple(img, atlas, fig_path): """ This is DEPRECATED code as of 20180709, replaced by run_align_atlas_gui. Potentially to be deleted eventually. To add: Simple scaling and translation, based on the original two keypoints (which set the orientation). With real time update/feedback. :param img: :param atlas: :param fig_path: :return: """ warning('run_align_atlas_gui_simple is DEPRECATED.') keypoint_positions = ['Anterior midline', 'Posterior midline'] # Load atlas. atlas, annotations, atlas_outline = load_atlas() do_manual_atlas_keypoint = False if do_manual_atlas_keypoint: atlas_coords = [] plt.figure(figsize=(30, 30)) plt.imshow(atlas_outline) for t in keypoint_positions: plt.title('Click on ' + t) c = plt.ginput(n=1) plt.plot(c[0][0], c[0][1], 'ro') atlas_coords.extend(c) else: atlas_coords = [(98, 227), (348, 227)] plt.figure(figsize=(30, 30)) plt.imshow(atlas_outline) for cc in atlas_coords: plt.plot(cc[0], cc[1], 'ro') # Convert selected keypoints to array. atlas_coords_array = np.zeros((len(atlas_coords), 2)) for ci, c in enumerate(atlas_coords): atlas_coords_array[ci, 0] = np.round(c[0]) atlas_coords_array[ci, 1] = np.round(c[1]) while 1: plt.figure() plt.imshow(img) img_coords = [] do_manual_patch_keypoint = True if do_manual_patch_keypoint: plt.figure(figsize=(30, 30)) plt.imshow(img) for t in keypoint_positions: plt.title('Click on ' + t) c = plt.ginput(n=1) plt.plot(c[0][0], c[0][1], 'ro') img_coords.extend(c) else: # These numbers are just for fast debugging. img_coords = [(26, 297), (430, 314)] plt.figure(figsize=(30, 30)) plt.imshow(img, cmap='Greys_r') for cc in img_coords: plt.plot(cc[0], cc[1], 'ro') plt.close('all') # Convert selected keypoints to array. img_coords_array = np.zeros((len(img_coords), 2)) for ci, c in enumerate(img_coords): img_coords_array[ci, 0] = np.round(c[0]) img_coords_array[ci, 1] = np.round(c[1]) aligned_atlas_outline, aligned_img, tform = align_atlas_to_image( atlas_outline, img, atlas_coords_array[0:2, :], img_coords_array[0:2, :], do_debug=False) # Overlay atlas on image for checking that things look good. overlay = overlay_atlas_outline(aligned_atlas_outline, img) plt.figure(figsize=(20, 20)) plt.imshow(overlay, cmap='Greys_r') plt.title( 'Check that things look good, and close this window manually.') plt.show() text = input('Look good? [y] or [n]') print(text) if text == 'y': break # # Save out selections # keypoints_dir = os.path.join(self._keypoints_file, name, \ # str(name) + '_source_extraction') # save_fname = os.path.join(keypoints_dir, 'keypoints.npz') # print('Saving keypoints and aligned atlas to: ' + save_fname) # np.savez(save_fname, # coords=img_coords_array, # atlas_coords=atlas_coords, # atlas=atlas, # img=aligned_img, # aligned_atlas_outline=aligned_atlas_outline) plt.figure() plt.imshow(img, cmap='Greys_r') for ci, c in enumerate(img_coords): print(c) plt.plot(c[0], c[1], 'ro') plt.savefig(fig_path + '_keypoints.png') plt.figure() plt.imshow(overlay, cmap='Greys_r') plt.savefig(fig_path + '_overlay.png') return (atlas_coords_array, img_coords_array, aligned_atlas_outline, atlas)
# Create sampling space #x = np.linspace(0, 100, 10) #y = np.linspace(0, 80, 10) #X, Y = np.meshgrid(x, y) #print(X.shape) #T_lst = [gate_lst[i].samplePoints(X, Y, object_lst) for i in range(len(gate_lst))] #ax.pcolormesh(X, Y, T_lst[0]+T_lst[1]+T_lst[2]) ax.set_title('City cross') ax.set_xlabel('x') ax.set_ylabel('y') plt.xlim([0, 100]) plt.ylim([0, 80]) sampled_pts = plt.ginput(200, timeout=0) sampled_pts = np.array([[p[0], p[1]] for p in sampled_pts]) samp_x = sampled_pts[:, 0] samp_y = sampled_pts[:, 1] T0 = np.array([gate_lst[0].samplePoint(sampled_pts[i,:], object_lst) for i in range(samp_x.shape[0])]) T1 = np.array([gate_lst[1].samplePoint(sampled_pts[i,:], object_lst) for i in range(samp_x.shape[0])]) T2 = np.array([gate_lst[2].samplePoint(sampled_pts[i,:], object_lst) for i in range(samp_x.shape[0])]) T = np.stack((T0, T1, T2), axis=1) T_color = T / 100. #T = normalize(T, axis=1) ax.scatter(samp_x, samp_y, c=T_color, edgecolor='none', s=np.max(T_color, axis=1)*150 ) plt.pause(0.1)
def select_keypoints(atlas_outline, img): """ Presents an interface for selecting two keypoints (along the midline) that define the initial position (and importantly, the rotation) of the aligned atlas. :param atlas_outline: Outline to overlay on atlas. :param img: Image to which the atlas will be aligned. :return: atlas_coords_array: the keypoints in atlas space img_coords_array: the corresponding keypoints in image space (which were user selected). """ keypoint_positions = ['Anterior midline', 'Posterior midline'] do_manual_atlas_keypoint = False if do_manual_atlas_keypoint: atlas_coords = [] plt.figure(figsize=(30, 30)) plt.imshow(atlas_outline) for t in keypoint_positions: plt.title('Click on ' + t) c = plt.ginput(n=1) plt.plot(c[0][0], c[0][1], 'ro') atlas_coords.extend(c) else: # These numbers were taken from an initial manual selection. atlas_coords = [(98, 227), (348, 227)] plt.figure(figsize=(30, 30)) plt.imshow(atlas_outline) for cc in atlas_coords: plt.plot(cc[0], cc[1], 'ro') # Convert selected keypoints to array. atlas_coords_array = np.zeros((len(atlas_coords), 2)) for ci, c in enumerate(atlas_coords): atlas_coords_array[ci, 0] = np.round(c[0]) atlas_coords_array[ci, 1] = np.round(c[1]) while 1: plt.figure() plt.imshow(img) img_coords = [] do_manual_patch_keypoint = True if do_manual_patch_keypoint: plt.figure(figsize=(30, 30)) plt.imshow(img) for t in keypoint_positions: plt.title('Click on ' + t) c = plt.ginput(n=1) plt.plot(c[0][0], c[0][1], 'ro') img_coords.extend(c) else: # These numbers are just for fast debugging. img_coords = [(26, 297), (430, 314)] # (26, 187), # (17, 420)] plt.figure(figsize=(30, 30)) plt.imshow(img, cmap='Greys_r') for cc in img_coords: plt.plot(cc[0], cc[1], 'ro') plt.close('all') # Convert selected keypoints to array. img_coords_array = np.zeros((len(img_coords), 2)) for ci, c in enumerate(img_coords): img_coords_array[ci, 0] = np.round(c[0]) img_coords_array[ci, 1] = np.round(c[1]) return atlas_coords_array, img_coords_array
# ************************************************* numCones = rick.load(open("numCones.pkl", "rb")) numNCones = rick.load(open("numNCones.pkl", "rb")) color_histogram = [] if ((getNewTrainingCones) or (getNewTrainingNCones)): plot.figure(plotIndex) plotIndex += 1 plot.clf() plot.imshow(im) if initializeNewLists: trainingImages = [] labels = [] if getNewTrainingCones: for index in range(newConesToAddToTrainingImage): p = plot.ginput(2) points = np.array([[p[0][0], p[0][1]], [p[1][0], p[1][1]]]) cone = cv2.resize( im[int(min(points[:, 1])):int(max(points[:, 1])), int(min(points[:, 0])):int(max(points[:, 0]))], (res, res)) trainingImages.append(cone) labels.append(1) numCones += 1 color_histogram.append( np.histogram(cone, 50)[0] ) # Color Histogram (Not actually used for anything because it gave trash results for me. My other methods worked better) plot.imsave(('ConeImages/coneImage' + str(numCones) + '.bmp'), cone) if getNewTrainingNCones: for index in range(newNConesToAddToTrainingImage): p = plot.ginput(2)
def define_mask(self, z=None, dataset=None, telluric=True): """ Use an interactive window to define the mask for the region. Parameters ---------- z : float [default = None] If a redshift is given, the lines in the region are shown as vertical lines at the given redshift. dataset : :class:`VoigtFit.DataSet` [default = None] A dataset with components defined for the lines in the region. If a dataset is passed, the components of the lines in the region are shown. telluric : bool [default = True] Show telluric absorption and sky emission line templates during the masking. """ plt.close('all') plt.xlim(self.wl.min(), self.wl.max()) # plt.ylim(max(0, 0.8*self.flux.min()), 1.2) lines_title = ", ".join([line.tag for line in self.lines]) plt.plot(self.wl, self.flux, color='k', drawstyle='steps-mid', lw=0.5, label=lines_title) plt.xlabel("Wavelength [${\\rm \AA}$]") plt.legend() if telluric: wl_T = telluric_data['wl'] cutout = (wl_T > self.wl.min()) * (wl_T < self.wl.max()) flux_T = telluric_data['em'][cutout] abs_T = telluric_data['abs'][cutout] wl_T = wl_T[cutout] if self.normalized: cont = 1. else: cont = np.median(self.flux) plt.plot(wl_T, abs_T * 1.2 * cont, color='crimson', alpha=0.7, lw=0.5) plt.plot(wl_T, (flux_T / flux_T.max() + 1.2) * cont, color='orange', alpha=0.7, lw=0.5) if z is not None: for line in self.lines: # Load line properties l0, f, gam = line.get_properties() if dataset is not None: ion = line.ion n_comp = len(dataset.components[ion]) ion = ion.replace('*', 'x') for n in range(n_comp): z = dataset.pars['z%i_%s' % (n, ion)].value plt.axvline(l0 * (z + 1), ls=':', color='r', lw=0.4) else: plt.axvline(l0 * (z + 1), ls=':', color='r', lw=0.4) plt.title("Mark regions to mask, left and right boundary.") print "\n\n Mark regions to mask, left and right boundary." plt.draw() ok = 0 mask_vlines = list() while ok >= 0: sel = plt.ginput(0, timeout=-1) if len(sel) > 0 and len(sel) % 2 == 0: mask = self.mask.copy() sel = np.array(sel) selections = np.column_stack([sel[::2, 0], sel[1::2, 0]]) for x1, x2 in selections: cutout = (self.wl >= x1) * (self.wl <= x2) mask[cutout] = False mask_vlines.append(plt.axvline(x1, color='r', ls='--')) mask_vlines.append(plt.axvline(x2, color='r', ls='--')) masked_spectrum = np.ma.masked_where(mask, self.flux) mask_line = plt.plot(self.wl, masked_spectrum, color='r', drawstyle='steps-mid') plt.draw() prompt = raw_input( "Are the masked regions correct? (YES/no/clear)") if prompt.lower() in ['', 'y', 'yes']: ok = -1 self.mask = mask self.new_mask = False elif prompt.lower() in ['c', 'clear']: ok = 0 self.mask = np.ones_like(mask, dtype=bool) for linesegment in mask_line: linesegment.remove() mask_line = list() for linesegment in mask_vlines: linesegment.remove() mask_vlines = list() else: self.mask = mask ok += 1 elif len(sel) == 0: print "\nNo masks were defined." prompt = raw_input("Continue? (yes/no)") if prompt.lower() in ['', 'y', 'yes']: ok = -1 self.new_mask = False else: ok += 1
slice_path = sub_all_tif[i - 1] slice_img = cv2.imread(slice_path, -1) # now get the slice image masked_image = add_mask(mask_centre, radius, slice_img) x_coordinate, y_coordinate = random_effective_area(masked_image) plt.imshow( masked_image[x_coordinate - show_length:x_coordinate + show_length, y_coordinate - show_length:y_coordinate + show_length], 'gray') plt.title( 'Please label any points for pore! ({:d}/{:d}) \n Current slice: {str}' .format((index + 1), num_slices, str=os.path.basename(slice_path)), color='red') coordinate = plt.ginput(n=num_points, timeout=0) # note that x, y from the ginput function is oppisite to our x and y, we need to transfer it transformed_coordinate = transform(coordinate, x_coordinate, y_coordinate, show_length) print(transformed_coordinate) with open(file_path, 'a') as f: f.writelines( [slice_path, ' ', str(transformed_coordinate), ' ', '0', '\n']) # '0' means pore print( 'Please label any points for non-pore (not artifact) in each picture!') # Then we label all non-pore
def normalize(self, plot=True, norm_method='linear', z_sys=None): """ Normalize the region if the data are not already normalized. Choose from two methods: 1: define left and right continuum regions and fit a linear continuum. 2: define the continuum as a range of points and use spline interpolation to infer the continuum. If `z_sys` is not `None`, show the region in velocity space using instead of wavelength space. """ if norm_method in ['linear', 'spline']: pass else: err_msg = "Invalid norm_method: %r" % norm_method raise ValueError(err_msg) plt.close('all') plt.figure() x = self.wl.copy() x_label = u"Wavelength [Å]" if z_sys is not None: # Calculate velocity: l0 = self.lines[0].l0 * (z_sys + 1.) x = (x - l0) / l0 * 299792.458 x_label = u"Rel. Velocity [${\\rm km\\ s^{-1}}$]" dx = 0.1 * (x.max() - x.min()) lines_title_string = ", ".join([line.tag for line in self.lines]) plt.xlim(x.min() - dx, x.max() + dx) plt.ylim(0.8 * self.flux.min(), 1.2 * self.flux.max()) plt.plot(x, self.flux, color='k', drawstyle='steps-mid', label=lines_title_string) plt.xlabel(x_label) if norm_method == 'linear': # - Normalize by defining a left and right continuum region print "\n\n Mark left continuum region, left and right boundary." plt.title("Mark left continuum region, left and right boundary.") bounds = plt.ginput(2, -1) left_bound = min(bounds[0][0], bounds[1][0]) right_bound = max(bounds[0][0], bounds[1][0]) region1 = (x >= left_bound) * (x <= right_bound) fit_wl = x[region1] fit_flux = self.flux[region1] lines_title_string = ", ".join([line.tag for line in self.lines]) plt.title(lines_title_string) print "\n Mark right continuum region, left and right boundary." plt.title("Mark right continuum region, left and right boundary.") bounds = plt.ginput(2) left_bound = min(bounds[0][0], bounds[1][0]) right_bound = max(bounds[0][0], bounds[1][0]) region2 = (x >= left_bound) * (x <= right_bound) fit_wl = np.concatenate([fit_wl, x[region2]]) fit_flux = np.concatenate([fit_flux, self.flux[region2]]) popt, pcov = curve_fit(linfunc, fit_wl, fit_flux) continuum = linfunc(x, *popt) e_continuum = np.std(fit_flux - linfunc(fit_wl, *popt)) elif norm_method == 'spline': # Normalize by drawing the continuum and perform spline # interpolation between the points print "\n\n Select a range of continuum spline points over the whole range" plt.title( " Select a range of continuum spline points over the whole range" ) points = plt.ginput(n=-1, timeout=-1) points = np.array(points) xk = points[:, 0] yk = points[:, 1] # region_wl = self.wl.copy() cont_spline = spline(xk, yk, s=0.) continuum = cont_spline(x) e_continuum = np.sqrt(np.mean(self.err**2)) if plot: new_flux = self.flux / continuum new_err = self.err / continuum plt.cla() plt.plot(x, new_flux, color='k', drawstyle='steps-mid', label=lines_title_string) plt.xlabel(x_label) plt.title("Normalized") plt.axhline(1., ls='--', color='k') plt.axhline(1. + e_continuum / np.mean(continuum), ls=':', color='gray') plt.axhline(1. - e_continuum / np.mean(continuum), ls=':', color='gray') plt.draw() plt.title("Go back to terminal...") prompt = raw_input(" Is normalization correct? (YES/no) ") if prompt.lower() in ['', 'y', 'yes']: self.flux = new_flux self.err = new_err self.cont_err = e_continuum / np.median(continuum) self.normalized = True return 1 else: return 0 else: self.flux = self.flux / continuum self.err = self.err / continuum self.cont_err = e_continuum / np.mean(continuum) self.normalized = True return 1
newedge.append((s, t)) edge = newedge print(i) if __name__ == '__main__': # img_path = 'rect-test-1000.jpg' img_path = 'maze.bmp' # first mine img0 = Image.open(img_path).convert('RGB') t1 = time.time() flood_fill_mine(img0, (1, 1), (0, 255, 0), None, 0) print(time.time() - t1) plt.imshow(img0) plt.ginput(1) plt.close() # first mine img0 = Image.open(img_path).convert('RGB') t1 = time.time() flood_fill_0(img0, (1, 1), (0, 255, 0), 0) print(time.time() - t1) plt.imshow(img0) plt.ginput(1) plt.close() # second original img1 = Image.open(img_path).convert('RGB') t1 = time.time() floodfill_o(img1, (1, 1), (0, 255, 0), None, 0)
conjunto_normalizado = normalizar(atributos) plt.scatter(conjunto_normalizado[:, 0], conjunto_normalizado[:, 1]) plt.show() # In[8] # column_stack para aderir las clases al conjunto conjunto_normalizado = np.column_stack((conjunto_normalizado, clases)) # Mostrar los valores pertenecientes for i in range(-1, 2): posicion, = np.where(conjunto_normalizado[:, 2] == i) pertenecientes = conjunto_normalizado[posicion, :] plt.scatter(pertenecientes[:, 0], pertenecientes[:, 1], 10) # In[9] # Obtener la nueva observacion para calcular sus vecinos mas cercanos nueva_obs = plt.ginput(1) observacion_array = np.tile(nueva_obs[0], (ren, 1)) plt.scatter(observacion_array[0, 0], observacion_array[0, 1], 30) distEuc = distanciaEuclidiana(conjunto_normalizado[:, :col - 1], observacion_array) posicion = np.argsort(distEuc[:, 0]) # In[10] # Plotear la nueva observacion con sus vecinos mas cercanos for i in range(0, K): plt.plot([observacion_array[i, 0], conjunto_normalizado[posicion[i], 0]], [observacion_array[i, 1], conjunto_normalizado[posicion[i], 1]]) plt.show()
def check_E(img1, file1, img2, file2, E, K1, K2): # input: # img1 - a h x w x 3 numpy ndarray (dtype = np.unit8) holding the color # image 1 (h, w being the height and width of the image) # file1 - the filename of the color image 1 # img2 - a h x w x 3 numpy ndarray (dtype = np.unit8) holding the color # image 2 (h, w being the height and width of the image) # filen2 - the filename of the color image 2 # E - a 3 x 3 numpy ndarray holding the essential matrix # K1 - a 3 x 3 numpy ndarray holding the K matrix of camera 1 # K2 - a 3 x 3 numpy ndarray holding the K matrix of camera 2 # form the fundamental matrix F = inv(K2.T) @ E @ inv(K1) plt.ion() # plot image 1 fig1 = plt.figure('Epipolar geometry - {}'.format(file1)) plt.imshow(img1) plt.autoscale(enable=False, axis='both') # plot image 2 fig2 = plt.figure('Epipolar geometry - {}'.format(file2)) plt.imshow(img2) plt.autoscale(enable=False, axis='both') plt.show() # ask user to pick points on image 1 print( 'please select points on {} using left-click, end with right-click...'. format(file1)) plt.figure(fig1.number) pt = plt.ginput(n=1, mouse_pop=2, mouse_stop=3, timeout=-1) while pt: pt = np.array(pt) plt.figure(fig1.number) plt.plot(pt[0, 0], pt[0, 1], 'rx') # form the epipolar line (a, b, c) = F @ np.array((pt[0, 0], pt[0, 1], 1)) (h, w, d) = img2.shape x = np.array([0, w - 1]) y = np.array([(a * x[0] + c) / (-b), (a * x[1] + c) / (-b)]) if y[0] < 0 or y[0] > h - 1 or y[1] < 0 or y[1] > h - 1: y = np.array([0, h - 1]) x = np.array([(b * y[0] + c) / (-a), (b * y[1] + c) / (-a)]) plt.figure(fig2.number) plt.plot(x, y, 'r-') plt.figure(fig1.number) pt = plt.ginput(n=1, mouse_pop=2, mouse_stop=3, timeout=-1) # ask user to pick points on image 1 print( 'please select points on {} using left-click, end with right-click...'. format(file2)) plt.figure(fig2.number) pt = plt.ginput(n=1, mouse_pop=2, mouse_stop=3, timeout=-1) while pt: pt = np.array(pt) plt.figure(fig2.number) plt.plot(pt[0, 0], pt[0, 1], 'bx') # form the epipolar line (a, b, c) = F.T @ np.array((pt[0, 0], pt[0, 1], 1)) (h, w, d) = img1.shape x = np.array([0, w - 1]) y = np.array([(a * x[0] + c) / (-b), (a * x[1] + c) / (-b)]) if y[0] < 0 or y[0] > h - 1 or y[1] < 0 or y[1] > h - 1: y = np.array([0, h - 1]) x = np.array([(b * y[0] + c) / (-a), (b * y[1] + c) / (-a)]) plt.figure(fig1.number) plt.plot(x, y, 'b-') plt.figure(fig2.number) pt = plt.ginput(n=1, mouse_pop=2, mouse_stop=3, timeout=-1) plt.close()
def run(self, image_filename_or_data, mask_color, opacity): plt.ion() plt.axis('off') if isinstance(image_filename_or_data, str): image_data = np.array(Image.open(image_filename_or_data)) elif isinstance(image_filename_or_data, list) or isinstance(image_filename_or_data, np.ndarray): image_data = image_filename_or_data else: print("image_filename_or_data is error") return plt.imshow(image_data) plt.title('Click one point of the object that you interested') try: while 1: object_point = np.array(plt.ginput(1, timeout=0)).astype(np.int)[0] where = [int(self.input_size[0] * object_point[1] / len(image_data)), int(self.input_size[1] * object_point[0] / len(image_data[0]))] print("point=[{},{}] where=[{},{}]".format(object_point[0], object_point[1], where[0], where[1])) final_batch_data, data_raw, gaussian_mask = Data.load_image(image_data, where=where, image_size=self.input_size) print("begin to run ...") # 运行 predict_output_r, pred_classes_r = self.sess.run([self.predict_output, self.pred_classes], feed_dict={self.img_placeholder: final_batch_data}) print("end run") # 类别 print("the class is {}({})".format(pred_classes_r[0], CategoryNames[pred_classes_r[0]])) # 分割 segment = np.squeeze(np.asarray(np.where(predict_output_r[0] == 1, 1, 0), dtype=np.uint8)) segment = np.asarray(Image.fromarray(segment).resize((len(image_data[0]), len(image_data)))) image_mask = np.ndarray(image_data.shape) image_mask[:, :, 0] = (1 - segment) * image_data[:, :, 0] + segment * ( opacity * mask_color[0] + (1 - opacity) * image_data[:, :, 0]) image_mask[:, :, 1] = (1 - segment) * image_data[:, :, 1] + segment * ( opacity * mask_color[1] + (1 - opacity) * image_data[:, :, 1]) image_mask[:, :, 2] = (1 - segment) * image_data[:, :, 2] + segment * ( opacity * mask_color[2] + (1 - opacity) * image_data[:, :, 2]) plt.clf() # clear image plt.text(len(image_data[0]) // 2 - 10, -6, CategoryNames[pred_classes_r[0]], fontsize=15) plt.imshow(image_mask.astype(np.uint8)) print("") pass except Exception: print("..................") print("...... close .....") print("..................") pass pass
coords = []; def tellme(s): print(s) plt.title(s, fontsize=16) plt.draw() #plt.waitforbuttonpress() if manually == 'no': fig = plt.figure(1);plt.plot(x,y);plt.yscale("log");plt.ylabel('EQE');plt.xlabel('energy [eV]')#;cid = fig.canvas.mpl_connect('button_press_event', onclick) while True: pts = [] while len(pts) < 2: tellme('Select two points for fit') pts = np.asarray(plt.ginput(2)) #if len(pts) < 2: # tellme('Too few points, starting over') # time.sleep(3) # Wait a second ph = plt.plot(pts[:, 0], pts[:, 1], '*r', lw=2) tellme('Happy? press (any) Key for yes,\n mouse click to start over') coords = pts if plt.waitforbuttonpress(): plt.close('all') break
else: t0 = at[t] print(t0) #--------------------------2--------------------------------------------- # map view, select boundaries of seismicity #------------------------------------------------------------------------ plt.figure(1) ax1 = plt.subplot(111) #:TODO plot wells #??? #:TODO plot seismicity #??? print("Please click %i times"%( dPar['nClicks'])) tCoord = plt.ginput( dPar['nClicks']) print("clicked", tCoord) plt.show() aLon = np.array( tCoord).T[0] aLat = np.array( tCoord).T[1] # project into equal area coordinate system lon_0, lat_0 = .5*( dPar['xmin']+dPar['xmax']), .5*( dPar['ymin']+dPar['ymax']) m = Basemap(llcrnrlon = dPar['xmin'], urcrnrlon=dPar['xmax'], llcrnrlat = dPar['ymin'], urcrnrlat=dPar['ymax'], projection=dPar['projection'], lon_0 = lon_0, lat_0 = lat_0) #TODO: project into equal area coordinate system #???
def on_key( event ): if event.key=="q" or event.key=="Q": check.lines[0][0].set_visible(True) check.lines[0][1].set_visible(True) check.lines[1][0].set_visible(False) check.lines[1][1].set_visible(False) check.lines[2][0].set_visible(False) check.lines[2][1].set_visible(False) check.lines[3][0].set_visible(False) check.lines[3][1].set_visible(False) check.labels[0].set_text('') check.labels[1].set_text('') check.labels[2].set_text('') check.labels[3].set_text('') #print "Can haz dblclikz???" x = plt.ginput(1) #print x difference_list = [] new_text = "" #new_text1 = "Other Nearby Peaks \n" current_peaks = cat_reader() for entry in current_peaks: inten = entry[1] freq = entry[0] qnum_up = entry[2] qnum_low = entry[3] if math.fabs(float(entry[0])-float(x[0][0]))<100.0 and math.fabs((10**float(entry[1])-float(x[0][1]))/(10**float(entry[1])))<0.2: difference_list.append((math.fabs(float(entry[0])-float(x[0][0])),freq,qnum_up,qnum_low,inten)) difference_list.sort() #print difference_list marker = 0 new_picked_list = [] try: for z in picked_list: if difference_list[0][2]==z[1] and difference_list[0][3]==z[2]: new_text+="\n removed: \n "+str(difference_list[0][2])+" | "+str(difference_list[0][3])+' | '+str(difference_list[0][1])+' | '+str(difference_list[0][4]) marker = 1 check.labels[0].set_text(str(difference_list[0][2])+" | "+str(difference_list[0][3])+' | '+str(difference_list[0][1])+' | '+str(difference_list[0][4])) check.labels[0].set_fontsize(8) if len(difference_list)>1: #new_text1+="\n"+str(difference_list[1][2])+' - '+str(difference_list[1][3])+" "+str(difference_list[1][1])+' '+str(difference_list[1][4]) check.labels[1].set_text(str(difference_list[1][2])+' | '+str(difference_list[1][3])+" | "+str(difference_list[1][1])+' | '+str(difference_list[1][4])) check.labels[1].set_fontsize(8) if len(difference_list)>2: #new_text1+="\n"+str(difference_list[2][2])+' - '+str(difference_list[2][3])+" "+str(difference_list[2][1])+' '+str(difference_list[2][4]) check.labels[2].set_text(str(difference_list[2][2])+' | '+str(difference_list[2][3])+" | "+str(difference_list[2][1])+' | '+str(difference_list[2][4])) check.labels[2].set_fontsize(8) if len(difference_list)>3: check.labels[3].set_text(str(difference_list[3][2])+' | '+str(difference_list[3][3])+" | "+str(difference_list[3][1])+' | '+str(difference_list[3][4])) check.labels[3].set_fontsize(8) #new_text1+="\n"+str(difference_list[3][2])+' - '+str(difference_list[3][3])+" "+str(difference_list[3][1])+' '+str(difference_list[3][4]) #if len(difference_list)>1: # if math.fabs(float(difference_list[0][1])-float(difference_list[1][1]))<0.50: # picked_list.append((difference_list[1][1],difference_list[1][2],difference_list[1][3],difference_list[1][4])) # new_text+="\n removed "+str(difference_list[0][2])+"-"+str(difference_list[0][3])+' '+str(difference_list[0][4]) #print "test1" else: new_picked_list.append(z) del picked_list global picked_list picked_list = new_picked_list if marker==0: check.labels[0].set_text(str(difference_list[0][2])+" | "+str(difference_list[0][3])+' | '+str(difference_list[0][1])+' | '+str(difference_list[0][4])) check.labels[0].set_fontsize(8) picked_list.append((difference_list[0][1],difference_list[0][2],difference_list[0][3],difference_list[0][4])) new_text+="\n added: \n "+str(difference_list[0][2])+" | "+str(difference_list[0][3])+' | '+str(difference_list[0][1])+' | '+str(difference_list[0][4]) if len(difference_list)>1: #new_text1+="\n"+str(difference_list[1][2])+' - '+str(difference_list[1][3])+" "+str(difference_list[1][1])+' '+str(difference_list[1][4]) check.labels[1].set_text(str(difference_list[1][2])+' | '+str(difference_list[1][3])+" | "+str(difference_list[1][1])+' | '+str(difference_list[1][4])) check.labels[1].set_fontsize(8) if len(difference_list)>2: #new_text1+="\n"+str(difference_list[2][2])+' - '+str(difference_list[2][3])+" "+str(difference_list[2][1])+' '+str(difference_list[2][4]) check.labels[2].set_text(str(difference_list[2][2])+' | '+str(difference_list[2][3])+" | "+str(difference_list[2][1])+' | '+str(difference_list[2][4])) check.labels[2].set_fontsize(8) if len(difference_list)>3: check.labels[3].set_text(str(difference_list[3][2])+' | '+str(difference_list[3][3])+" | "+str(difference_list[3][1])+' | '+str(difference_list[3][4])) check.labels[3].set_fontsize(8) #new_text1+="\n"+str(difference_list[3][2])+' - '+str(difference_list[3][3])+" "+str(difference_list[3][1])+' '+str(difference_list[3][4]) #if float(difference_list[0][1])-float(difference_list[1][1])<0.010 and difference_list[0][4]==difference_list[1][4]: # picked_list.append((difference_list[1][1],difference_list[1][2],difference_list[1][3],difference_list[1][4])) # new_text+="\n added "+str(difference_list[1][2])+"-"+str(difference_list[1][3])+' '+str(difference_list[1][4]) data = cat_reader() s_b = [] t_b = [] for x in data: #if x[2]==difference_list[0][2] and x[3]==difference_list[0][3] and marker==0: # s_b.append(0.0) # s_b.append(float(10**float(difference_list[0][4]))) # s_b.append(0.0) # t_b.append(float(difference_list[0][1])-0.0001) # t_b.append(difference_list[0][1]) # t_b.append(float(difference_list[0][1])+0.0001) for y in picked_list: if x[2]==y[1] and x[3]==y[2]: s_b.append(0.0) s_b.append(str(10**float(x[1]))) s_b.append(0.0) t_b.append(float(x[0])-0.0001) t_b.append(x[0]) t_b.append(float(x[0])+0.0001) picked_plt.set_data(t_b,s_b) text_box.set_text(new_text) text_box.set_fontsize(10) #text_box2.set_text(new_text1) #picked_plt.set_xlim([f_lower_g,f_upper_g]) #print new_text plt.draw() #print s_b,t_b except IndexError: pass
def drawPts(self, OBJECTIDs, plot_title=True): # check to see if pts are loaded try: type(self.pts) except AttributeError: raise RuntimeError('ERROR: pts not loaded yet') # if self.log: # self.logger.info('drawPts start...') user_vi = self.cfg.user_vi doy_limits = self.cfg.param_nita['doy_limits'] value_limits = self.cfg.param_nita['value_limits'] date_limits = self.cfg.param_nita['date_limits'] if OBJECTIDs == [9999]: OBJECTIDs = list(set(self.pts['OBJECTID'])) OBJECTIDs = OBJECTIDs[0:25] handdraw_trajs = [] for OBJECTID in OBJECTIDs: fig, ax = plt.subplots() plot_y = self.pts.loc[self.pts['OBJECTID'] == OBJECTID][user_vi].values plot_x = self.pts.loc[self.pts['OBJECTID'] == OBJECTID]['date_dist'].values plot_doy = self.pts.loc[self.pts['OBJECTID'] == OBJECTID]['doy'].values if plot_title: info_line = self.ref_pts.loc[self.ref_pts['OBJECTID'] == OBJECTID] title = ''.join([ str(item) + ' ' for item in list(info_line.values.flatten()) ]) else: title = '' plot_x, plot_y, plot_doy = nf.filterLimits(plot_x, plot_y, plot_doy, value_limits, date_limits, doy_limits) doy_limit = doy_limits[0] mappable = ax.scatter(plot_x, plot_y, c=plot_doy, vmin=doy_limit[0], vmax=doy_limit[1]) ax.set_xlim([plot_x.min(), plot_x.max()]) ax.set_ylim([plot_y.min(), plot_y.max()]) ax.set_title(title) plt.ylabel('VI Units') # xticks_lables = ax.get_xticks().tolist() xticks_lables = [ str(xticks_label)[0:4] for xticks_label in xticks_lables ] ax.set_xticklabels(xticks_lables) # fig.colorbar(mappable, label='Day of year') ginput_res = plt.ginput(n=-1, timeout=0) handdraw_traj = {'OBJECTID': OBJECTID, 'traj': ginput_res} handdraw_trajs.append(handdraw_traj) self.handdraw_trajs = handdraw_trajs plt.close('all') if self.log: self.logger.info('total {} OBJECTIDs drew: ' + str(OBJECTIDs).format(len(OBJECTIDs))) self.logger.info('drawPts end...')
from PIL import Image as Img from pylab import ginput, plot import homography import numpy as ny import scipy import matplotlib.pyplot as pplot faceImg = ny.asarray(Img.open('IMG_0519.png').convert('L')) billImg = ny.asarray(Img.open('billboard.png').convert('L')) pplot.figure(1) pplot.imshow(faceImg) facePts = ny.asarray(pplot.ginput(4)).T pplot.figure(2) pplot.imshow(billImg) billPts = ny.asarray(pplot.ginput(4)).T pplot.show() H = homography.H_from_from_point(facePts, billPts) print('Homography Matrix') print(H)
maxCount = countMost[i] mostEle = i return mostEle #baseline=mostFreNum(ys) # newYSS=[] # newS=[] # for i in ys: # newYSS.append(round(i, 6)) # print(mostFreNum(ys)) # print(mostFreNum(newYSS)) # baseline=mostFreNum(newYSS) #print(baseline) point = plt.ginput(1) yaxis = point[0][1] baseline = yaxis print(yaxis) #baseline=float(input("Base on the graph, please enter a y value to set up your baseline: ")) amplitudeBase = float( input( "please input minimum peak amplitude(the height from your input baseline): " )) for i in range(counter): yzero.append(baseline) for i in range(counter): yzero4Peak.append(xs[i] * 0 + baseline) for i in range(counter): yzero4Deep.append(xs[i] * 0 + baseline) plt.plot(xs, yzero, 'r--')
def calculate(data, percent): #计算距离 distlist = [] dist = np.zeros((len(data), len(data))) for i in range(len(data) - 1): for j in range(i + 1, len(data)): distance = np.sqrt(np.sum(np.square(data[i] - data[j]))) dist[i, j] = distance dist[j, i] = distance if (i != j): distlist.append(distance) # dc # for i in range(len(dist) - 1): # for j in range(len(dist) - 1): # if(dist[i,j] != 0): sortdist = sorted(distlist) position = round(len(distlist) * percent / 100) dc = sortdist[position] print('dc', dc) #计算局部密度 # 计算局部密度 rho (利用 Gaussian 核) rho = np.zeros(len(dist)) # Gaussian kernel for i in range(len(dist) - 1): for j in range(i + 1, len(dist)): rho[i] = rho[i] + np.exp(-(dist[i, j] / dc) * (dist[i, j] / dc)) rho[j] = rho[j] + np.exp(-(dist[i, j] / dc) * (dist[i, j] / dc)) rho = [item / max(rho) for item in rho] # 生成 delta 和 nneigh 数组 # delta 距离数组 # nneigh 比本身密度大的最近的点 # 记录 rho 值更大的数据点中与 ordrho(ii) 距离最近的点的编号 ordrho(jj) # 将 rho 按降序排列,ordrho 保持序 ordrho = np.flipud(np.argsort(rho)) delta = np.zeros(len(dist)) nneigh = np.zeros(len(dist), dtype=int) delta[ordrho[0]] = -1. nneigh[ordrho[0]] = 0 # 求最大距离 maxd = max(dist.flatten()) for ii in range(1, len(dist)): delta[ordrho[ii]] = maxd for jj in range(ii): if dist[ordrho[ii], ordrho[jj]] < delta[ordrho[ii]]: delta[ordrho[ii]] = dist[ordrho[ii], ordrho[jj]] nneigh[ordrho[ii]] = ordrho[jj] delta[ordrho[0]] = max(delta) # delta = [item/max(delta) for item in delta] gamma = [rho[i] * delta[i] for i in range(len(dist))] plt.figure(1) for index in range(len(dist)): plt.plot(rho[index], delta[index], 'ko') pos = plt.ginput(1) rhomin = pos[0][0] deltamin = pos[0][1] cl = -1 * np.ones(len(dist), dtype=int) icl = [] NCLUST = 1 for i in range(len(dist)): if rho[i] > rhomin and delta[i] > deltamin: cl[i] = NCLUST #第 i 号数据点属于第 NCLUST 个 cluster icl.append(i) # 逆映射,第 NCLUST 个 cluster 的中心为第 i 号数据点 NCLUST += 1 for i in range(len(dist)): if cl[ordrho[i]] == -1: cl[ordrho[i]] = cl[nneigh[ordrho[i]]] print(cl) color = ['bo', 'co', 'go', 'ko', 'mo', 'ro', 'wo', 'yo'] s = random.sample(color, NCLUST - 1) plt.close() for i in range(len(data)): plt.plot(data[i][0], data[i][1], s[cl[i] - 1]) plt.show()
plt.clf() plt.axis([-1., 1., -1., 1.]) plt.setp(plt.gca(), autoscale_on=False) tellme('You will define a triangle, click to begin') plt.waitforbuttonpress() happy = False while not happy: pts = [] while len(pts) < 3: tellme('Select 3 corners with mouse') pts = np.asarray(plt.ginput(3, timeout=-1)) if len(pts) < 3: tellme('Too few points, starting over') time.sleep(1) # Wait a second ph = plt.fill(pts[:, 0], pts[:, 1], 'r', lw=2) tellme('Happy? Key click for yes, mouse click for no') happy = plt.waitforbuttonpress() # Get rid of fill if not happy: for p in ph: p.remove()
3)[:, :, :2] imNp = imrgbn data_marca = imNp[np.where(np.all(np.equal(markImg, (255, 0, 0)), 2))] data_fondo = imNp[np.where(np.all(np.equal(markImg, (0, 255, 0)), 2))] data_linea = imNp[np.where(np.all(np.equal(markImg, (0, 0, 255)), 2))] plt.figure() plt.plot(data_marca[:, 0], data_marca[:, 1], 'r.', label='marca') plt.plot(data_fondo[:, 0], data_fondo[:, 1], 'g.', label='fondo') plt.plot(data_linea[:, 0], data_linea[:, 1], 'b.', label='linea') plt.title('Espacio RGB normalizado') plt.show() # Primera linea p12 = plt.ginput(2, timeout=-1, show_clicks=True, mouse_pop=2, mouse_stop=3) p1 = np.array(p12[0] + (1, )) p2 = np.array(p12[1] + (1, )) p = np.array(p12) l1 = np.cross(p1, p2) plt.plot(p[:, 0], p[:, 1], 'r-') # segunda linea p12 = plt.ginput(2, timeout=-1, show_clicks=True, mouse_pop=2, mouse_stop=3) p1 = np.array(p12[0] + (1, )) p2 = np.array(p12[1] + (1, )) l2 = np.cross(p1, p2) p = np.array(p12) plt.plot(p[:, 0], p[:, 1], 'g-')
parser = argparse.ArgumentParser(description='Image for process.') parser.add_argument('path', metavar='im', type=str, help='Path to image to use in the adjust process') args = parser.parse_args() im1 = np.array(Image.open(os.path.abspath(args.path)).\ convert('L')) plt.figure('Imagen 1') plt.axis('off'), plt.imshow(im1, cmap='gray') x1 = np.array(plt.ginput(4, mouse_add=3, mouse_pop=1, mouse_stop=2)).T plt.close() h, w = 400, 300 x2 = np.array([[0, w, 0, w], [0, 0, h, h]]) xh1 = make_homog(x1) xh2 = make_homog(x2) H = H_from_points(xh2, xh1) im_out = Htransform(im1, H, (h, w)) plt.figure() plt.subplot(121), plt.imshow(im1, cmap='gray'), plt.axis('off') plt.plot(x1[0], x1[1], 'r.', markersize=6) plt.subplot(122), plt.imshow(im_out, cmap='gray'), plt.axis('off') plt.show()
def womcat(hop): """concatenate data with overlapping wavelength regions""" import numpy as np import logging import matplotlib.pyplot as plt from tmath.wombat.inputter import inputter from tmath.wombat.inputter_single import inputter_single from tmath.wombat.womget_element import womget_element from tmath.wombat.yesno import yesno from tmath.wombat.get_screen_size import get_screen_size from tmath.wombat.womwaverange2 import womwaverange2 from tmath.wombat import HOPSIZE from matplotlib.widgets import Cursor plt.ion() screen_width, screen_height = get_screen_size() screenpos = '+{}+{}'.format(int(screen_width * 0.2), int(screen_height * 0.05)) fig = plt.figure() ax = fig.add_subplot(111) cursor = Cursor(ax, useblit=True, color='k', linewidth=1) fig.canvas.manager.window.wm_geometry(screenpos) fig.canvas.set_window_title('Cat') fig.set_size_inches(9, 6) # turns off key stroke interaction fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id) print("\nThis will combine blue and red pieces from two hoppers\n") hopnum1 = 0 hopnum2 = 0 while (hopnum1 < 1) or (hopnum1 > HOPSIZE): hopnum1 = inputter('Enter first hopper: ', 'int', False) while (hopnum2 < 1) or (hopnum2 > HOPSIZE): hopnum2 = inputter('Enter second hopper: ', 'int', False) if (hop[hopnum1].wave[0] > hop[hopnum2].wave[0]): hopnum1, hopnum2 = hopnum2, hopnum1 wdelt1 = hop[hopnum1].wave[1] - hop[hopnum1].wave[0] wdelt2 = hop[hopnum2].wave[1] - hop[hopnum2].wave[0] # check if wavelength dispersion same if (abs(wdelt1 - wdelt2) > 0.00001): print('Spectra do not have same Angstrom/pixel') print('Blue side: {}'.format(wdelt1)) print('Red side: {}'.format(wdelt2)) return hop if hop[hopnum1].wave[-1] < hop[hopnum2].wave[0]: print('Spectra do not overlap\n') return hop print("\nOverlap range is {} to {}".format(hop[hopnum2].wave[0], hop[hopnum1].wave[-1])) print("\nPlotting blue side as blue, red side as red\n") waveblue = hop[hopnum1].wave.copy() fluxblue = hop[hopnum1].flux.copy() varblue = hop[hopnum1].var.copy() wavered = hop[hopnum2].wave.copy() fluxred = hop[hopnum2].flux.copy() varred = hop[hopnum2].var.copy() indexblue = womget_element(waveblue, wavered[0]) indexred = womget_element(wavered, waveblue[-1]) fluxcor = 1.0 blue_mean = np.mean(fluxblue[indexblue:]) red_mean = np.mean(fluxred[0:indexred + 1]) if (blue_mean / red_mean < 0.8) or (blue_mean / red_mean > 1.2): fluxcor = blue_mean / red_mean print("Averages very different, scaling red to blue for plot") print("Red multiplied by {}".format(fluxcor)) plt.cla() plt.plot(waveblue[indexblue:], fluxblue[indexblue:], drawstyle='steps-mid', color='b') plt.plot(wavered[0:indexred], fluxred[0:indexred] * fluxcor, drawstyle='steps-mid', color='r') plt.xlabel('Wavelength') plt.ylabel('Flux') plt.pause(0.01) print('Change scale?') answer = yesno('n') if (answer == 'y'): xmin_old, xmax_old = plt.xlim() ymin_old, ymax_old = plt.ylim() done = False while (not done): plt.xlim([xmin_old, xmax_old]) plt.ylim([ymin_old, ymax_old]) print('Click corners of box to change plot scale') newlims = plt.ginput(2, timeout=-1) xmin = newlims[0][0] ymin = newlims[0][1] xmax = newlims[1][0] ymax = newlims[1][1] plt.xlim([xmin, xmax]) plt.ylim([ymin, ymax]) print('Is this OK?') loopanswer = yesno('y') if (loopanswer == 'y'): done = True print('\nEnter method to select wavelength ranges\n') mode = inputter_single( 'Enter (w)avelengths or mark with the (m)ouse? (w/m) ', 'wm') print('\nChoose end points of region to compute average\n') waveb, waver, mode = womwaverange2(waveblue[indexblue:], fluxblue[indexblue:], wavered[0:indexred], fluxred[0:indexred] * fluxcor, mode) indexblueb = womget_element(waveblue, waveb) indexbluer = womget_element(waveblue, waver) indexredb = womget_element(wavered, waveb) indexredr = womget_element(wavered, waver) mean_blue = np.mean(fluxblue[indexblueb:indexbluer + 1]) mean_red = np.mean(fluxred[indexredb:indexredr + 1]) print("\nAverage for {}:{}".format(waveb, waver)) print("Blue side: {}".format(mean_blue)) print("Red side: {}\n".format(mean_red)) brscale = inputter_single('Scale to blue or red (b/r)? ', 'br') if (brscale == 'b'): brscalefac = mean_blue / mean_red logging.info('Cat scaling to blue by {}'.format(brscalefac)) fluxred = fluxred * brscalefac varred = varred * brscalefac**2 else: brscalefac = mean_red / mean_blue logging.info('Cat scaling to red by {}'.format(brscalefac)) fluxblue = fluxblue * brscalefac varblue = varblue * brscalefac**2 # print("\nPlotting blue side as blue, red side as red\n") # plt.cla() # plt.plot(waveblue[indexblueb:indexbluer+1],fluxblue[indexblueb:indexbluer+1],drawstyle='steps-mid',color='b') # plt.plot(wavered[indexredb:indexredr+1],fluxred[indexredb:indexredr+1],drawstyle='steps-mid',color='r') # plt.xlabel('Wavelength') # plt.ylabel('Flux') # plt.pause(0.01) # print('Change scale?') # answer=yesno('n') # if (answer == 'y'): # xmin_old,xmax_old=plt.xlim() # ymin_old,ymax_old=plt.ylim() # done=False # while (not done): # plt.xlim([xmin_old,xmax_old]) # plt.ylim([ymin_old,ymax_old]) # print('Click corners of box to change plot scale') # newlims=plt.ginput(2,timeout=-1) # xmin=newlims[0][0] # ymin=newlims[0][1] # xmax=newlims[1][0] # ymax=newlims[1][1] # plt.xlim([xmin,xmax]) # plt.ylim([ymin,ymax]) # print('Is this OK?') # loopanswer=yesno('y') # if (loopanswer == 'y'): # done=True # print('\nChoose end points of region to compute average\n') # waveb,waver,mode=womwaverange2(waveblue[indexblueb:indexbluer+1], # fluxblue[indexblueb:indexbluer+1], # wavered[indexredb:indexredr+1], # fluxred[indexredb:indexredr+1],mode) # indexblueb=womget_element(waveblue,waveb) # indexbluer=womget_element(waveblue,waver) # indexredb=womget_element(wavered,waveb) # indexredr=womget_element(wavered,waver) # ewadd=inputter_single('Add overlap region (e)qually or with (w)eights (e/w)?','ew') # if (ewadd == 'e'): # overflux=(fluxblue[indexblueb:indexbluer+1]+fluxred[indexredb:indexredr+1])/2. # overvar=(varblue[indexblueb:indexbluer+1]+varred[indexredb:indexredr+1]) #replacing with inverse variance weighted average delta = (indexbluer - indexblueb) - (indexredr - indexredb) if delta != 0: indexredr = indexredr + delta overflux = np.average([ fluxblue[indexblueb:indexbluer + 1], fluxred[indexredb:indexredr + 1] ], weights=[ 1. / varblue[indexblueb:indexbluer + 1], 1. / varred[indexredb:indexredr + 1] ], axis=0) overvar = np.sum( [varblue[indexblueb:indexbluer + 1], varred[indexredb:indexredr + 1]], axis=0) logging.info('Cat combined sides with inverse variance weighted average') # else: # wei_done = False # while (not wei_done): # weiblue=inputter('Enter fractional weight for blue side: ','float',False) # weired=inputter('Enter fractional weight for red side: ','float',False) # if (np.abs((weiblue+weired)-1.0) > 0.000001): # print('Weights do not add to 1.0') # else: # wei_done = True # overflux=(fluxblue[indexblueb:indexbluer+1]*weiblue+ # fluxred[indexredb:indexredr+1]*weired) # overvar=(varblue[indexblueb:indexbluer+1]*weiblue**2+ # varred[indexredb:indexredr+1]*weired**2) # logging.info('Cat adds blue side with weight {} and red side with weight {}'.format(weiblue, weired)) newbluewave = waveblue[:indexblueb] newblueflux = fluxblue[:indexblueb] newbluevar = varblue[:indexblueb] overwave = waveblue[indexblueb:indexbluer + 1] newredwave = wavered[indexredr + 1:] newredflux = fluxred[indexredr + 1:] newredvar = varred[indexredr + 1:] newwave = np.concatenate([newbluewave, overwave, newredwave]) newflux = np.concatenate([newblueflux, overflux, newredflux]) newvar = np.concatenate([newbluevar, overvar, newredvar]) logging.info('File {} and'.format(hop[hopnum1].obname)) logging.info('File {} concatenated'.format(hop[hopnum2].obname)) logging.info('over wavelength range {} to {}'.format( waveblue[indexblueb], waveblue[indexbluer])) plt.clf() axarr = fig.subplots(2) axarr[0].plot(overwave, overflux, drawstyle='steps-mid', color='k') axarr[0].plot(waveblue[indexblueb:indexbluer + 1], fluxblue[indexblueb:indexbluer + 1], drawstyle='steps-mid', color='b') axarr[0].plot(wavered[indexredb:indexredr + 1], fluxred[indexredb:indexredr + 1], drawstyle='steps-mid', color='r') axarr[0].set_title('Overlap region, with inputs and combination') axarr[1].set_ylabel('Flux') axarr[1].plot(newwave, newflux, drawstyle='steps-mid', color='k') axarr[1].plot(newwave[indexblueb:indexbluer + 1], newflux[indexblueb:indexbluer + 1], drawstyle='steps-mid', color='r') plt.pause(0.01) hopout = 0 while (hopout < 1) or (hopout > HOPSIZE): hopout = inputter('Enter hopper to store combined spectrum: ', 'int', False) hop[hopout].wave = newwave hop[hopout].flux = newflux hop[hopout].var = newvar hop[hopout].obname = hop[hopnum1].obname hop[hopout].header = hop[hopnum1].header plt.close() #fig.clf() #plt.cla() return hop
# -*- coding: utf-8 -*- # CLAB3 import numpy as np from PIL import Image import matplotlib.pyplot as plt import time import cv2 I = Image.open('stereo2012a.jpg') plt.imshow(I) uv = plt.ginput(12) # Graphical user interface to get 6 points #xyz coordinates (world coordinates) xyz = np.asarray([[7, 7, 0], [14, 7, 0], [21, 7, 0], [21, 14, 0], [0, 7, 7], [0, 14, 7], [0, 21, 7], [0, 21, 14], [7, 0, 7], [7, 0, 14], [7, 0, 21], [14, 0, 21]]) ''' %% TASK 1: CALIBRATE % % Function to perform camera calibration % % Usage: calibrate(image, XYZ, uv) % return C % Where: image - is the image of the calibration target. % XYZ - is a N x 3 array of XYZ coordinates % of the calibration target points. % uv - is a N x 2 array of the image coordinates % of the calibration target points. % K - is the 3 x 4 camera calibration matrix. % The variable N should be an integer greater than or equal to 6. %
def rmshadows(humfile, sonpath, win=31, shadowmask=0, doplot=1): ''' Remove dark shadows in scans caused by shallows, shorelines, and attenuation of acoustics with distance Manual or automated processing options available Works on the radiometrically corrected outputs of the correct module Syntax ---------- [] = PyHum.rmshadows(humfile, sonpath, win, shadowmask, doplot) Parameters ---------- humfile : str path to the .DAT file sonpath : str path where the *.SON files are win : int, *optional* [Default=100] window size (pixels) for the automated shadow removal algorithm shadowmask : int, *optional* [Default=0] 1 = do manual shadow masking, otherwise do automatic shadow masking doplot : int, *optional* [Default=1] 1 = make plots, otherwise do not Returns ------- sonpath+base+'_data_star_la.dat': memory-mapped file contains the starboard scan with water column removed and radiometrically corrected, and shadows removed sonpath+base+'_data_port_la.dat': memory-mapped file contains the portside scan with water column removed and radiometrically corrected, and shadows removed ''' # prompt user to supply file if no input file given if not humfile: print 'An input file is required!!!!!!' Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing humfile = askopenfilename(filetypes=[("DAT files", "*.DAT")]) # prompt user to supply directory if no input sonpath is given if not sonpath: print 'A *.SON directory is required!!!!!!' Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing sonpath = askdirectory() # print given arguments to screen and convert data type where necessary if humfile: print 'Input file is %s' % (humfile) if sonpath: print 'Sonar file path is %s' % (sonpath) if win: win = np.asarray(win, int) print 'Window is %s square pixels' % (str(win)) if shadowmask: shadowmask = np.asarray(shadowmask, int) if shadowmask == 1: print 'Shadow masking is manual' else: print 'Shadow masking is auto' if doplot: doplot = int(doplot) if doplot == 0: print "Plots will not be made" # start timer if os.name == 'posix': # true if linux/mac or cygwin on windows start = time.time() else: # windows start = time.clock() # if son path name supplied has no separator at end, put one on if sonpath[-1] != os.sep: sonpath = sonpath + os.sep base = humfile.split('.DAT') # get base of file name for output base = base[0].split(os.sep)[-1] base = humutils.strip_base(base) meta = loadmat(os.path.normpath(os.path.join(sonpath, base + 'meta.mat'))) # load memory mapped scans shape_port = np.squeeze(meta['shape_port']) if shape_port != '': #port_fp = np.memmap(sonpath+base+'_data_port_la.dat', dtype='float32', mode='r', shape=tuple(shape_port)) with open( os.path.normpath( os.path.join(sonpath, base + '_data_port_la.dat')), 'r') as ff: port_fp = np.memmap(ff, dtype='float32', mode='r', shape=tuple(shape_port)) shape_star = np.squeeze(meta['shape_star']) if shape_star != '': #star_fp = np.memmap(sonpath+base+'_data_star_la.dat', dtype='float32', mode='r', shape=tuple(shape_star)) with open( os.path.normpath( os.path.join(sonpath, base + '_data_star_la.dat')), 'r') as ff: star_fp = np.memmap(ff, dtype='float32', mode='r', shape=tuple(shape_star)) dist_m = np.squeeze(meta['dist_m']) ft = 1 / (meta['pix_m']) extent = shape_star[1] if shadowmask == 1: #manual Zt = [] if len(np.shape(star_fp)) > 2: for p in xrange(len(star_fp)): raw_input( "Shore picking (starboard), are you ready? 30 seconds. Press Enter to continue..." ) shoreline_star = {} fig = plt.figure() ax = plt.gca() ax.imshow(star_fp[p], cmap='gray') #, origin = 'upper') #im = plt.axis('normal') plt.axis('tight') pts1 = plt.ginput( n=300, timeout=30) # it will wait for 200 clicks or 30 seconds x1 = map(lambda x: x[0], pts1) # map applies the function passed as y1 = map(lambda x: x[1], pts1) # first parameter to each element of pts shoreline_star = np.interp(np.r_[:np.shape(star_fp[p])[1]], x1, y1) plt.close() del fig star_mg = star_fp[p].copy() shoreline_star = np.asarray(shoreline_star, 'int') # shift proportionally depending on where the bed is for k in xrange(np.shape(star_mg)[1]): star_mg[shoreline_star[k]:, k] = np.nan del shoreline_star Zt.append(star_mg) else: raw_input( "Shore picking (starboard), are you ready? 30 seconds. Press Enter to continue..." ) shoreline_star = {} fig = plt.figure() ax = plt.gca() ax.imshow(star_fp, cmap='gray') #, origin = 'upper') #im = plt.axis('normal') plt.axis('tight') pts1 = plt.ginput( n=300, timeout=30) # it will wait for 200 clicks or 30 seconds x1 = map(lambda x: x[0], pts1) # map applies the function passed as y1 = map(lambda x: x[1], pts1) # first parameter to each element of pts shoreline_star = np.interp(np.r_[:np.shape(star_fp)[1]], x1, y1) plt.close() del fig star_mg = star_fp.copy() shoreline_star = np.asarray(shoreline_star, 'int') # shift proportionally depending on where the bed is for k in xrange(np.shape(star_mg)[1]): star_mg[shoreline_star[k]:, k] = np.nan del shoreline_star Zt.append(star_mg) ## create memory mapped file for Z #p = np.memmap(sonpath+base+'_data_star_la.dat', dtype='float32', mode='w+', shape=np.shape(Zt)) #fp[:] = Zt[:] #del fp Zt = np.squeeze(Zt) # create memory mapped file for Zs #fp = np.memmap(sonpath+base+'_data_star_lar.dat', dtype='float32', mode='w+', shape=np.shape(Zs)) with open( os.path.normpath( os.path.join(sonpath, base + '_data_star_lar.dat')), 'w+') as ff: fp = np.memmap(ff, dtype='float32', mode='w+', shape=np.shape(Zt)) fp[:] = Zt[:] del fp del Zt #shutil.move(os.path.normpath(os.path.join(sonpath,base+'_data_star_lar.dat')), os.path.normpath(os.path.join(sonpath,base+'_data_star_la.dat'))) Zt = [] if len(np.shape(star_fp)) > 2: for p in xrange(len(port_fp)): raw_input( "Shore picking (port), are you ready? 30 seconds. Press Enter to continue..." ) shoreline_port = {} fig = plt.figure() ax = plt.gca() ax.imshow(port_fp[p], cmap='gray') #, origin = 'upper') #im = plt.axis('normal') plt.axis('tight') pts1 = plt.ginput( n=300, timeout=30) # it will wait for 200 clicks or 30 seconds x1 = map(lambda x: x[0], pts1) # map applies the function passed as y1 = map(lambda x: x[1], pts1) # first parameter to each element of pts shoreline_port = np.interp(np.r_[:np.shape(port_fp[p])[1]], x1, y1) plt.close() del fig port_mg = port_fp[p].copy() shoreline_port = np.asarray(shoreline_port, 'int') # shift proportionally depending on where the bed is for k in xrange(np.shape(port_mg)[1]): port_mg[shoreline_port[k]:, k] = np.nan del shoreline_port Zt.append(port_mg) else: raw_input( "Shore picking (port), are you ready? 30 seconds. Press Enter to continue..." ) shoreline_port = {} fig = plt.figure() ax = plt.gca() ax.imshow(port_fp, cmap='gray') #, origin = 'upper') #im = plt.axis('normal') plt.axis('tight') pts1 = plt.ginput( n=300, timeout=30) # it will wait for 200 clicks or 30 seconds x1 = map(lambda x: x[0], pts1) # map applies the function passed as y1 = map(lambda x: x[1], pts1) # first parameter to each element of pts shoreline_port = np.interp(np.r_[:np.shape(port_fp)[1]], x1, y1) plt.close() del fig port_mg = port_fp.copy() shoreline_port = np.asarray(shoreline_port, 'int') # shift proportionally depending on where the bed is for k in xrange(np.shape(port_mg)[1]): port_mg[shoreline_port[k]:, k] = np.nan del shoreline_port Zt.append(port_mg) Zt = np.squeeze(Zt) ## create memory mapped file for Z #fp = np.memmap(sonpath+base+'_data_port_la.dat', dtype='float32', mode='w+', shape=np.shape(Zt)) #fp[:] = Zt[:] #del fp # create memory mapped file for Zp #fp = np.memmap(sonpath+base+'_data_port_lar.dat', dtype='float32', mode='w+', shape=np.shape(Zp)) with open( os.path.normpath( os.path.join(sonpath, base + '_data_port_lar.dat')), 'w+') as ff: fp = np.memmap(ff, dtype='float32', mode='w+', shape=np.shape(Zt)) fp[:] = Zt[:] del fp del Zt #shutil.move(os.path.normpath(os.path.join(sonpath,base+'_data_port_lar.dat')), os.path.normpath(os.path.join(sonpath,base+'_data_port_la.dat'))) else: #auto #win = 31 Zs = [] Zp = [] if len(np.shape(star_fp)) > 2: for p in xrange(len(star_fp)): merge = np.vstack((np.flipud(port_fp[p]), star_fp[p])) merge = np.asarray(merge, 'float64') merge_mask = np.vstack((np.flipud(port_fp[p]), star_fp[p])) merge[merge_mask == 0] = 0 del merge_mask mask = np.asarray(merge != 0, 'int8') # only 8bit precision needed merge[np.isnan(merge)] = 0 #Z,ind = humutils.sliding_window(merge,(win,win),(win/2,win/2)) Z, ind = humutils.sliding_window(merge, (win, win), (win, win)) #zmean = np.reshape(zmean, ( ind[0], ind[1] ) ) Ny, Nx = np.shape(merge) #zmean[np.isnan(zmean)] = 0 try: #parallel processing with all available cores w = Parallel(n_jobs=-1, verbose=0)(delayed(parallel_me)(Z[k]) for k in xrange(len(Z))) except: #fall back to serial w = Parallel(n_jobs=1, verbose=0)(delayed(parallel_me)(Z[k]) for k in xrange(len(Z))) zmean = np.reshape(w, (ind[0], ind[1])) del w M = humutils.im_resize(zmean, Nx, Ny) M[mask == 0] = 0 del zmean bw = M > 0.5 del M # erode and dilate to remove splotches of no data bw2 = binary_dilation(binary_erosion(bw, structure=np.ones( (3, 3))), structure=np.ones((13, 13))) #bw2 = binary_dilation(binary_erosion(bw,structure=np.ones((win/4,win/4))), structure=np.ones((win/4,win/4))) ##bw2 = binary_erosion(bw,structure=np.ones((win*2,win*2))) ## fill holes bw2 = binary_fill_holes(bw2, structure=np.ones( (win, win))).astype(int) merge2 = grey_erosion(merge, structure=np.ones((win, win))) #del bw #bw2 = np.asarray(bw2!=0,'int8') # we only need 8 bit precision bw2 = np.asarray(bw != 0, 'int8') # we only need 8 bit precision del bw merge[bw2 == 1] = 0 #blank out bad data merge[merge2 == np.min(merge2)] = 0 #blank out bad data del merge2 ## do plots of merged scans if doplot == 1: Zdist = dist_m[shape_port[-1] * p:shape_port[-1] * (p + 1)] fig = plt.figure() plt.imshow(merge, cmap='gray', extent=[ min(Zdist), max(Zdist), -extent * (1 / ft), extent * (1 / ft) ]) plt.ylabel('Range (m)'), plt.xlabel( 'Distance along track (m)') plt.axis('normal') plt.axis('tight') custom_save(sonpath, 'merge_corrected_rmshadow_scan' + str(p)) del fig Zp.append(np.flipud(merge[:shape_port[1], :])) Zs.append(merge[shape_port[1]:, :]) del merge, bw2 else: merge = np.vstack((np.flipud(port_fp), star_fp)) merge = np.asarray(merge, 'float64') merge_mask = np.vstack((np.flipud(port_fp), star_fp)) merge[merge_mask == 0] = 0 del merge_mask mask = np.asarray(merge != 0, 'int8') # only 8bit precision needed merge[np.isnan(merge)] = 0 #Z,ind = humutils.sliding_window(merge,(win,win),(win/2,win/2)) Z, ind = humutils.sliding_window(merge, (win, win), (win, win)) #zmean = np.reshape(zmean, ( ind[0], ind[1] ) ) Ny, Nx = np.shape(merge) #zmean[np.isnan(zmean)] = 0 try: #parallel processing with all available cores w = Parallel(n_jobs=-1, verbose=0)(delayed(parallel_me)(Z[k]) for k in xrange(len(Z))) except: #fall back to serial w = Parallel(n_jobs=1, verbose=0)(delayed(parallel_me)(Z[k]) for k in xrange(len(Z))) zmean = np.reshape(w, (ind[0], ind[1])) del w M = humutils.im_resize(zmean, Nx, Ny) M[mask == 0] = 0 del zmean bw = M > 0.5 del M # erode and dilate to remove splotches of no data bw2 = binary_dilation(binary_erosion(bw, structure=np.ones( (3, 3))), structure=np.ones((13, 13))) #bw2 = binary_dilation(binary_erosion(bw,structure=np.ones((win/4,win/4))), structure=np.ones((win/4,win/4))) ##bw2 = binary_erosion(bw,structure=np.ones((win*2,win*2))) ## fill holes bw2 = binary_fill_holes(bw2, structure=np.ones( (win, win))).astype(int) merge2 = grey_erosion(merge, structure=np.ones((win, win))) #del bw #bw2 = np.asarray(bw2!=0,'int8') # we only need 8 bit precision bw2 = np.asarray(bw != 0, 'int8') # we only need 8 bit precision del bw merge[bw2 == 1] = 0 #blank out bad data merge[merge2 == np.min(merge2)] = 0 #blank out bad data del merge2 # erode and dilate to remove splotches of no data #bw2 = binary_dilation(binary_erosion(bw,structure=np.ones((3,3))), structure=np.ones((13,13))) #bw2 = binary_dilation(binary_erosion(bw,structure=np.ones((win,win))), structure=np.ones((win*2,win*2))) #bw2 = binary_erosion(bw,structure=np.ones((win,win))) # fill holes #bw2 = binary_fill_holes(bw2, structure=np.ones((3,3))).astype(int) #del bw #bw2 = np.asarray(bw2!=0,'int8') # we only need 8 bit precision #merge[bw2==1] = 0 #blank out bad data ## do plots of merged scans if doplot == 1: Zdist = dist_m fig = plt.figure() plt.imshow(merge, cmap='gray', extent=[ min(Zdist), max(Zdist), -extent * (1 / ft), extent * (1 / ft) ]) plt.ylabel('Range (m)'), plt.xlabel('Distance along track (m)') plt.axis('normal') plt.axis('tight') custom_save(sonpath, 'merge_corrected_rmshadow_scan' + str(0)) del fig Zp.append(np.flipud(merge[:shape_port[0], :])) Zs.append(merge[shape_port[0]:, :]) del merge, bw2 Zp = np.squeeze(Zp) Zs = np.squeeze(Zs) # create memory mapped file for Zp #fp = np.memmap(sonpath+base+'_data_port_lar.dat', dtype='float32', mode='w+', shape=np.shape(Zp)) #with open(sonpath+base+'_data_port_lar.dat', 'w+') as f: with open( os.path.normpath( os.path.join(sonpath, base + '_data_port_lar.dat')), 'w+') as ff: fp = np.memmap(ff, dtype='float32', mode='w+', shape=np.shape(Zp)) fp[:] = Zp[:] del fp del Zp #shutil.move(sonpath+base+'_data_port_lar.dat', sonpath+base+'_data_port_la.dat') #shutil.move(os.path.normpath(os.path.join(sonpath,base+'_data_port_lar.dat')), os.path.normpath(os.path.join(sonpath,base+'_data_port_la.dat'))) # create memory mapped file for Zs #fp = np.memmap(sonpath+base+'_data_star_lar.dat', dtype='float32', mode='w+', shape=np.shape(Zs)) #with open(sonpath+base+'_data_star_lar.dat', 'w+') as f: with open( os.path.normpath( os.path.join(sonpath, base + '_data_star_lar.dat')), 'w+') as ff: fp = np.memmap(ff, dtype='float32', mode='w+', shape=np.shape(Zs)) fp[:] = Zs[:] del fp del Zs #shutil.move(sonpath+base+'_data_star_lar.dat', sonpath+base+'_data_star_la.dat') #shutil.move(os.path.normpath(os.path.join(sonpath,base+'_data_star_lar.dat')), os.path.normpath(os.path.join(sonpath,base+'_data_star_la.dat'))) if os.name == 'posix': # true if linux/mac elapsed = (time.time() - start) else: # windows elapsed = (time.clock() - start) print "Processing took ", elapsed, "seconds to analyse" print "Done!"
def ppicker(eventdir, pname, sname, get, args): """ Function ppicker is a ginput based arrival picker allowing for 3 time picks which are saved in SAC data headers""" pf = os.path.join(eventdir, pname) sf = os.path.join(eventdir, sname) pt = read(pf)[0] st = read(sf)[0] p, s = (pt.data, st.data) dt = pt.stats.delta N = len(pt.data) b = pt.stats.sac['b'] depth = pt.stats.sac['evdp'] t0 = (pt.stats.sac['t0'] - b) / dt t4 = (pt.stats.sac['t4'] - b) / dt t7 = (pt.stats.sac['t7'] - b) / dt # Skip if T1 and T3 are greater than zero. The default is a large negative number if args.unpicked: if float(pt.stats.sac['t1']) > 0 and float(pt.stats.sac['t3']) > 0: return 's' left = round(t0 - 15 / dt) right = round(t0 + 140 / dt) t = np.around(np.arange(-t0 * dt, (N - t0) * dt, dt)) # Time axis nn = np.arange(0, N) plt.figure(num=None, figsize=(22, 6)) plt.plot(p, label='Pcomp') plt.xticks(nn[::round(5 / dt)], t[::round(5 / dt)]) # Changed from 200 plt.title('{} \n P-trace, source depth = {}'.format(eventdir, depth)) plt.axvline(x=t0, color='y', label='gett P') plt.axvline(x=t4, color='g', label='gett pP') if t7 < right: plt.axvline(x=t7, color='r', label='gett PP') plt.xlim(left, right) plt.xlabel('Time \n P arrival is zero seconds') plt.legend() print "Keep trace? 'n' for no, 'r' for redo, 'p' for previous, 's' for skip and any other for yes: " if args.sort: plt.show(block=False) inp = get() plt.close() return inp else: x = plt.ginput(n=2, timeout=0, show_clicks=True) try: T1 = x[0][0] * dt + b T3 = x[1][0] * dt + b except IndexError: print "Not all picks made in", eventdir print "Please retry the picks" return 'r' plt.close() inp = get() if inp not in ['n', 'r', 'p', 's']: # Assume yes and save pt.stats.sac['t1'] = T1 pt.stats.sac['t3'] = T3 pt.write(pf, format='SAC') st.stats.sac['t1'] = T1 st.stats.sac['t3'] = T3 st.write(sf, format='SAC') return inp