def main(): parser = argparse.ArgumentParser() parser_io = parser.add_argument_group(description = "==== I/O parameters ====") parser_io.add_argument("-i","--infile",required=True) parser_io.add_argument("-o","--baseoutfilename",default="out") parser_io.add_argument("-v","--verbose",action="store_true",default=False) parser_io.add_argument("-S","--OutputSinglestrainNullclines",action="store_true",default=False) parser = gc.AddLatticeParameters(parser) parser = gc.AddDilutionParameters(parser) args=parser.parse_args() g = gc.LoadGM(**vars(args)) dlist = gc.getDilutionList(**vars(args)) # get new axes, which depends on parameters above (in lattice parameter group) axis1,axis2 = gc.getInoculumAxes(**vars(args)) # either (n,x) or [ (n1,n2) if args.AbsoluteCoordinates == True ] shape = (len(axis1),len(axis2)) # loaded from pickle file m1,m2 = g.growthmatrixgrid gm1 = g.growthmatrix[:,:,0] gm2 = g.growthmatrix[:,:,1] # matrices to store averages g1 = np.zeros(shape,dtype=np.float64) # avg'd growth strain 1 g2 = np.zeros(shape,dtype=np.float64) # avg'd growth strain 2 rr1 = np.zeros(shape,dtype=np.float64) # avg'd ratio of strains at end r1 = np.zeros(shape,dtype=np.float64) # avg'd ratio of strains at beginning sn1 = np.zeros(shape,dtype=np.float64) # number of cells of strain 1 in new matrix shape sn2 = np.zeros(shape,dtype=np.float64) # number of cells of strain 1 in new matrix shape # get all averages and store them in the appropriate matrices for i,a1 in enumerate(axis1): for j,a2 in enumerate(axis2): sn1[i,j],sn2[i,j] = gc.TransformInoculum([a1,a2],inabs = args.AbsoluteCoordinates, outabs = True) g1[i,j] = gc.SeedingAverage(gm1, [sn1[i,j],sn2[i,j]]) g2[i,j] = gc.SeedingAverage(gm2, [sn1[i,j],sn2[i,j]]) rr1[g1+g2>0] = (g1[g1+g2>0])/((g1+g2)[g1+g2>0]) r1[sn1+sn2>0] = (sn1[sn1+sn2>0])/((sn1+sn2)[sn1+sn2>0]) # output if args.verbose: sys.stdout.write('\n computing nullcline for fraction of strains\n') cont_xx = measure.find_contours(rr1 - r1,0) write_contours_to_file(cont_xx,args.baseoutfilename + '_X',axis1,axis2) for dilution in dlist: if args.verbose: sys.stdout.write(' computing nullclines for dilution D = {:.4e}\n'.format(dilution)) cont_nn = measure.find_contours((g1 + g2) * dilution - sn1 - sn2,0) write_contours_to_file(cont_nn,args.baseoutfilename + '_N_D{:.3e}'.format(dilution),axis1,axis2) if args.OutputSinglestrainNullclines: cont_n1 = measure.find_contours(g1 * dilution - sn1,0) cont_n2 = measure.find_contours(g2 * dilution - sn2,0) write_contours_to_file(cont_n1,args.baseoutfilename + '_1_D{:.3e}'.format(dilution),axis1,axis2) write_contours_to_file(cont_n2,args.baseoutfilename + '_2_D{:.3e}'.format(dilution),axis1,axis2)
def find_contours(path, low=0.1, high=0.8): """Find contours in an image at path """ img = imread(path, flatten=True) # Find contours at a constant value of 0.1 and 0.8 dark = measure.find_contours(img, low) light = measure.find_contours(img, high) return img, dark, light
def find_roi_edge(mask): ''' Finds the outline of a mask, using the find_contour function from skimage.measure. Parameters ---------- mask : array_like the mask, a binary array Returns ------- Array with coordinates of pixels in the outline of the mask ''' # Ensure array_like input is a numpy.ndarray mask = np.asarray(mask) # Pad with 0s to make sure that edge ROIs are properly estimated mask_shape = np.shape(mask) padded_shape = (mask_shape[0] + 2, mask_shape[1] + 2) padded_mask = np.zeros(padded_shape) padded_mask[1:-1, 1:-1] = mask # detect contours outline = find_contours(padded_mask, level=0.5) # update coordinates to take into account padding and set so that the # coordinates are defined from the corners (as in the mask2poly function # in SIMA https://github.com/losonczylab/sima/blob/master/sima/ROI.py) for i in range(len(outline)): outline[i] -= 0.5 return outline
def get_image_words(image): # 删除包含的区域,返回正确的区域 def remove_range(cells): # b in a def range_include(a, b): return b.up >= a.up and b.down <= a.down and b.left >= a.left and b.right <= a.right def range_cmp(range_data_a, range_data_b): return -1 if range_data_a.down - range_data_a.up < range_data_b.down - range_data_b.up else 1 cells.sort(range_cmp) n = len(cells) ok = [True] * n for i in xrange(1, n): for j in xrange(i): if ok[j] and range_include(cells[i], cells[j]): ok[j] = False new_cells = [cells[i] for i in xrange(n) if ok[i]] return new_cells # 单词排序 def mycmp(range_data_a, range_data_b): return -1 if range_data_a.left < range_data_b.left else 1 contours = measure.find_contours(image, 0.8) cells = [] for contour in contours: up, down, left, right = min(contour[:, 0]), max(contour[:, 0]), min(contour[:, 1]), max(contour[:, 1]) if down - up >= wordSpace or right - left >= wordSpace: cells.append(RangeData(up, down, left, right)) cells = remove_range(cells) cells.sort(mycmp) return cells
def main(): Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing image_path = askopenfilename() # show an "Open" dialog box and return the path to the selected file #read image and convert to matrix image = Image.open(image_path) image_array = image.getdata() image_array = numpy.array(image_array).astype(numpy.uint8).reshape((image.size[0],image.size[1])) #Threshold the image to binary thresh = threshold_otsu(image_array) image_array = image > thresh image_array = ~image_array #Extract the longest contour in the image contours = measure.find_contours(image_array, 0.9) contours_main = max(contours, key=len) # Display the image and plot the main contour found fig, ax = plt.subplots() ax.imshow(image_array, cmap=plt.cm.gray) ax.plot(contours_main[:, 1], contours_main[:, 0], linewidth=2) # Extract freeman code from contour freeman_code = encode_freeman(contours_main) print freeman_code, len(freeman_code) plt.show()
def load_scenes(filename): zipped_scenes = [] print 'Working on: ' + filename img = data.imread('scenes/' + filename, as_grey=True) tmp = img tmp = filter.canny(tmp, sigma=2.0) tmp = ndimage.binary_fill_holes(tmp) #tmp = morphology.dilation(tmp, morphology.disk(2)) tmp = morphology.remove_small_objects(tmp, 2000) contours = measure.find_contours(tmp, 0.8) ymin, xmin = contours[0].min(axis=0) ymax, xmax = contours[0].max(axis=0) if xmax - xmin > ymax - ymin: xdest = 1000 ydest = 670 else: xdest = 670 ydest = 1000 src = np.array(((0, 0), (0, ydest), (xdest, ydest), (xdest, 0))) dst = np.array(((xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin))) tform3 = tf.ProjectiveTransform() tform3.estimate(src, dst) warped = tf.warp(img, tform3, output_shape=(ydest, xdest)) tmp = filter.canny(warped, sigma=2.0) tmp = morphology.dilation(tmp, morphology.disk(2)) descriptor_extractor.detect_and_extract(tmp) obj_key = descriptor_extractor.keypoints scen_desc = descriptor_extractor.descriptors zipped_scenes.append([warped, scen_desc, obj_key, filename]) return zipped_scenes
def edge_detect(im, hdr): w = WCS(hdr) ra = [] dec = [] exclude_RA = np.NaN exclude_DEC = np.NaN contours = measure.find_contours(im,0.5,fully_connected='high') x_pix = contours[0][:,0] y_pix = im.shape[1] - contours[0][:,1] - 1 exclude_reg = np.array(contours).shape[0] - 1 if exclude_reg > 0: i = 1 exclude_RA = [] exclude_DEC = [] while i <= exclude_reg: x_excl = contours[i][:,0] y_excl = im.shape[1] - contours[i][:,1] - 1 tmp_RA = [] tmp_DEC = [] for j in np.arange(len(x_excl)): x, y = w.wcs_pix2world(y_excl[j], x_excl[j], 0) tmp_RA.append(x.tolist()) tmp_DEC.append(y.tolist()) exclude_RA.append(tmp_RA) exclude_DEC.append(tmp_DEC) i += 1 for i in np.arange(len(x_pix)): x, y = w.wcs_pix2world(y_pix[i], x_pix[i], 0) ra.append(x.tolist()) dec.append(y.tolist()) return ra, dec, exclude_RA, exclude_DEC
def __call__(self, level, minDensity, keepSourceWindow=False): self.start(keepSourceWindow) if self.tif.dtype == np.float16: g.alert("Adaptive Threshold does not support float16 type arrays") return for roi in self.ROIs: roi.cancel() self.ROIs = [] im = g.win.image if g.win.image.ndim == 2 else g.win.image[g.win.currentIndex] im = scipy.ndimage.morphology.binary_closing(im) if np.any(im < 0) or np.any(im > 1): raise Exception("The current image is not a binary image. Threshold first") thresholded_image = np.squeeze(im) labelled=measure.label(thresholded_image) ROIs = [] for i in range(1, np.max(labelled)+1): if np.sum(labelled == i) >= minDensity: im = scipy.ndimage.morphology.binary_dilation(scipy.ndimage.morphology.binary_closing(labelled == i)) outline_coords = measure.find_contours(im, level) if len(outline_coords) == 0: continue outline_coords = outline_coords[0] new_roi = makeROI("freehand", outline_coords) ROIs.append(new_roi)
def compute_contours(self): graph = self.graph if graph is None or not self.x2_variable: return for plot in self._contour_plots: self.graph.remove_plot(plot) plots = self._contour_plots = [] data = np.clip(self._yvals, self.y_start, self.y_end) xscale = (self.end - self.start) / self.num_points x2scale = (self.x2_end - self.x2_start) / self.num_points color = next(self.colors) for val in np.linspace(self.y_start, self.y_end, self.num_contours): contours = measure.find_contours(data, val) for contour in contours: contour[:, 0] *= xscale contour[:, 0] += self.start contour[:, 1] *= x2scale contour[:, 1] += self.x2_start plot = MeshLinePlot(color=color) plots.append(plot) graph.add_plot(plot) plot.points = contour
def tracestackedslab(infile,depthinc=5,llinc=((6371*np.pi)/360),cval=0.5): ''' Takes a netcdf file containing a stacked, normed profiles and attempts to contour what might be a slab - can use this to estimate dip, profile etc The values of depthinc and llinc are defaults from the Ritsema code, which creates slices over angles of 180 degrees and with a depth increment of 5 km This produces a map showing the slice and contours in stacked velocity perturbation at a chosen level (typically 0.5) ''' Mantlebase = 2895 infile = Dataset(infile, model='r') filevariables = infile.variables.keys() #Get data from the netCDF file depths = infile.variables['y'][:] lengths = infile.variables['x'][:] data = infile.variables['z'][:][:] infile.close() #print np.shape(data) #print np.shape(lengths) #print np.shape(depths) #Use image processing suite to find contours contours = measure.find_contours(data,cval) #Various plotting commands to produce the figure fig, ax = plt.subplots() thousandkm = int((Mantlebase-1000)/depthinc) sixsixtykm = int((Mantlebase-660)/depthinc) plt.set_cmap('jet_r') ax.imshow(data, interpolation='linear',aspect='auto') ax.plot([0,len(lengths)],[thousandkm,thousandkm],'k--',label='1000km') ax.plot([0,len(lengths)],[sixsixtykm,sixsixtykm],'k-',label='660km') for n, contour in enumerate(contours): if n == 0: ax.plot(contour[:, 1], contour[:, 0], 'r-', linewidth=2,label='contour at %g' %cval) else: ax.plot(contour[:, 1], contour[:, 0], 'r-', linewidth=2) ax.set_ylim([0,len(depths)]) ax.set_xlim([len(lengths),0]) ax.set_title('Stacked slab image from netCDF') plt.xlabel('Cross section x increment') plt.ylabel('Cross section depth increment') plt.legend(loc='best') #plt.gca().invert_yaxis() #plt.gca().invert_xaxis() plt.show(block=False)
def contours(data): """Get zero contours from x, y, z data Args: data: dictionary with (x, y, z, dx) keys Returns: a list of (N, 2) numpy arrays representing the contours """ def linspace_(arr, spacing): """Calcuate the linspace based on a spacing """ return pipe( arr, juxt(min, max), tlam(lambda x_, y_: np.linspace(x_, y_, (y_ - x_) / spacing)) ) return pipe( data, lambda x: dict(xi=linspace_(x['x'], x['dx']), yi=linspace_(x['y'], x['dx']), **x), lambda x: griddata((x['y'], x['x']), x['z'], (x['yi'][None, :], x['xi'][:, None]), method='cubic'), lambda x: measure.find_contours(x, 0.0), map(lambda x: float(data['dx']) * x) )
def loadmydata(): alla, allb, allc, alll = [], [], [], [] indd=1 for k in labels: for j in dataset[k]: im = imread(j) im = leaf_image_preprocess(im) img_filt = extract_leaf_stem(im) contours = measure.find_contours(img_filt, 0.8) a,b,c=parametrize(get_largest(contours)) alla.append(a) allb.append(b) allc.append(c) alll.append(k) # fig = plt.figure() # ax = fig.add_subplot(111) # cwtmatr = signal.cwt(signal.decimate(a,4),signal.ricker, np.linspace(0.0001,1,200)) #toplt=[] #for x in cwtmatr: #if any(x[x>2]): #toplt.append(np.mean(x[x>2])) #else: #toplt.append(0) #ax.set_xlim([0,160]) #ax.set_ylim([-3,7]) print j return alla, allb, allc, alll
def edge_curvature_feature(binary, cbins=15): contours = measure.find_contours(binary, level=0.5) c = cal_edge_curvature(binary, contours, cbins=cbins) return normalize(c[0])
def main(): imgs = MultiImage(data_dir + '/multipage.tif') for a, i in zip(range(0, 4), [1, 9, 7, 8]): fig = plt.figure() ax = fig.add_axes([-0.1, -0.1, 1.2, 1.2]) # ax.set_axis_off() im = data.imread('samolot0' + str(i) + '.jpg', as_grey = True) im = invert(im) im = process(im) out = np.ones_like(im) io.imshow(out) contours = measure.find_contours(im, 0.9) for n, contour in enumerate(contours): plt.plot(contour[:, 1], contour[:, 0], linewidth=2, color = 'white') plt.savefig(str(a) + '.jpg', bbox_inches = 0, frameon = False) fig = plt.figure() grid = AxesGrid(fig, rect = (1, 1, 1), nrows_ncols = (2, 2), axes_pad = 0.1) for i in range(0, 4): frame = data.imread(str(i) + '.jpg') grid[i].imshow(frame) grid[i].set_xticks([]) grid[i].set_yticks([]) plt.savefig('na3.jpg')
def cont(imagen, depth=2**16, gaussian=3, screenpercent=0.7,t=0): imagen = gaussian_filter(imagen, gaussian) if t==0: otsu = threshold_otsu(imagen, depth) elif t==1: otsu = filters.threshold_isodata(imagen, depth) else: otsu = filters.threshold_li(imagen) imagen = binarizar(imagen, otsu) imagen = gaussian_filter(imagen, gaussian) contours = measure.find_contours(imagen, 1) centro = np.asanyarray([1280*0.5, 960*0.5]) while len(contours) > 1: if sum(np.abs(centro - contours[1].mean(axis=0)) < [1280*screenpercent*0.5, 960*screenpercent*0.5]) != 2: del contours[1] elif sum(np.abs(centro - contours[0].mean(axis=0)) < [1280*screenpercent*0.5, 960*screenpercent*0.5]) != 2: del contours[0] else: if contours[1].size < contours[0].size: del contours[1] else: del contours[0] return imagen, contours[0]
def test_binary(): contours = find_contours(a, 0.5) assert len(contours) == 1 assert_array_equal(contours[0], [[ 6. , 1.5], [ 5. , 1.5], [ 4. , 1.5], [ 3. , 1.5], [ 2. , 1.5], [ 1.5, 2. ], [ 1.5, 3. ], [ 1.5, 4. ], [ 1.5, 5. ], [ 1.5, 6. ], [ 1. , 6.5], [ 0.5, 6. ], [ 0.5, 5. ], [ 0.5, 4. ], [ 0.5, 3. ], [ 0.5, 2. ], [ 0.5, 1. ], [ 1. , 0.5], [ 2. , 0.5], [ 3. , 0.5], [ 4. , 0.5], [ 5. , 0.5], [ 6. , 0.5], [ 6.5, 1. ], [ 6. , 1.5]])
def main(): plt.figure(figsize=(25, 24)) planes = ['samolot00.jpg', 'samolot01.jpg', 'samolot03.jpg', 'samolot04.jpg', 'samolot05.jpg','samolot07.jpg', 'samolot08.jpg', 'samolot09.jpg', 'samolot10.jpg', 'samolot11.jpg', 'samolot12.jpg', 'samolot13.jpg', 'samolot14.jpg', 'samolot15.jpg', 'samolot16.jpg', 'samolot17.jpg', 'samolot18.jpg', 'samolot20.jpg'] i = 1 for file in planes: img = data.imread(file, as_grey=True) img2 = data.imread(file) ax = plt.subplot(6, 3, i) ax.axis('off') img **= 0.4 img = filter.canny(img, sigma=3.0) img = morphology.dilation(img, morphology.disk(4)) img = ndimage.binary_fill_holes(img) img = morphology.remove_small_objects(img, 1000) contours = measure.find_contours(img, 0.8) ax.imshow(img2, aspect='auto') for n, contour in enumerate(contours): ax.plot(contour[:, 1], contour[:, 0], linewidth=1.5) center = (sum(contour[:, 1])/len(contour[:, 1]), sum(contour[:, 0])/len(contour[:, 0])) ax.scatter(center[0], center[1], color='white') i += 1 plt.savefig('zad2.pdf')
def integer_boundaries(mask, edges, level): ''' Return the non-interpolated contour boundaries. ''' all_pts = me.find_contours(mask, 0.5) int_pts = [] for pts in all_pts: new_int_pts = np.zeros_like(pts, dtype=int) for i, pt in enumerate(pts): y, x = pt ceil = (np.ceil(y).astype(int), np.ceil(x).astype(int)) floor = (np.floor(y).astype(int), np.floor(x).astype(int)) if edges[ceil]: new_int_pts[i] = np.array(ceil) elif edges[floor]: new_int_pts[i] = np.array(floor) else: raise IndexError("Cannot find pixel in mask for " + str(pt)) int_pts.append(new_int_pts) return int_pts
def test_binary(): ref = [[6. , 1.5], [5. , 1.5], [4. , 1.5], [3. , 1.5], [2. , 1.5], [1.5, 2. ], [1.5, 3. ], [1.5, 4. ], [1.5, 5. ], [1.5, 6. ], [1. , 6.5], [0.5, 6. ], [0.5, 5. ], [0.5, 4. ], [0.5, 3. ], [0.5, 2. ], [0.5, 1. ], [1. , 0.5], [2. , 0.5], [3. , 0.5], [4. , 0.5], [5. , 0.5], [6. , 0.5], [6.5, 1. ], [6. , 1.5]] contours = find_contours(a, 0.5, positive_orientation='high') assert len(contours) == 1 assert_array_equal(contours[0][::-1], ref)
def getGeneralStatistics(self): area = np.sum(self.image) perimeterArray = [len(x) for x in measure.find_contours(self.image, 0.5)] perimeter = max(perimeterArray) if len(perimeterArray) != 0 else 0 roundness = 4 * area * pi / (perimeter * perimeter) if perimeter != 0 else 0 finalStatistics = [area, perimeter, roundness, len(self.getCenters())] return finalStatistics
def __transform(self): self.__img_gray = io.imread(self.__img_path, True) self.__otsu = filter.threshold_otsu(self.__img_gray) #Aplicar otsu para binarizar a imagem self.__img_gray = self.__img_gray < self.__otsu # Find contours at a constant value of 0.5 self.__contours = measure.find_contours(self.__img_gray, 0.5) self.__arclen = 0.0 for n, contour in enumerate(self.__contours): arclenTemp=0.0 for indice, valor in enumerate(contour): if indice > 0: d1 = math.fabs(round(valor[0]) - round(contour[indice-1,0])) d2 = math.fabs(round(valor[1]) - round(contour[indice-1,1])) if d1+d2>1.0: arclenTemp+=math.sqrt(2) elif d1+d2 == 1: arclenTemp+=1 if arclenTemp > self.__arclen: self.__arclen = arclenTemp self.__bestn = n #self.__bestn = 0 print self.__contours[0]
def get_contours(array, x, y, projection, level): ''' Find contours for a given level ''' # Find contours at a constant value contours = sorted(measure.find_contours(array, level), key=lambda x: len(x)) i = range(0, len(x)) j = range(0, len(y)) lon = [] lat = [] contour_points = [] for k in range(0, len(contours)): contour = contours[k] contour_x = x[0] + contour[:, 1] * (x[-1] - x[0]) / (len(i) - 1) contour_y = y[0] + contour[:, 0] * (y[-1] - y[0]) / (len(j) - 1) # Convert to EPSG:4326 contour_lon, contour_lat = projection( contour_x, contour_y, inverse=True) lon.append(contour_lon) lat.append(contour_lat) points = [(contour_lon[k], contour_lat[k]) for k in range(len(contour_lat))] contour_points.append(points) # reverse direction, last entry (longest contour) first. contour_points.reverse() if single: contour_points = [contour_points[0]] return contour_points
def contour(): from skimage.filters import gaussian from skimage.segmentation import active_contour import scipy from skimage import measure from skimage import img_as_float image = io.imread(path + "bibme0.png") image = rgb2gray(image) #image = img_as_float(image) #print image ##### OPTION 1 contours = measure.find_contours(image,0.9) #print size(contours) #toprint(contours,'bibme0_contours.png') fig, ax = plt.subplots() #ax.imshow(contours, interpolation='nearest', cmap=plt.cm.gray) for n, contour in enumerate(contours): ax.plot(contour[:,0], contour[:,1], linewidth=0.5) #print len(contours) ax.axis('image') ax.set_xticks([]) ax.set_yticks([]) fig.savefig(out_path + 'bibme0_contours.png') #plt.show() rotate90()
def find_image_contours(image): """Find contours in image.""" # level = np.ptp(image) / 2 level = 1050 # TODO: Different contour levels for ADC and T2w. kwargs = dict(fully_connected='low', positive_orientation='low') # kwargs = dict(fully_connected='high', positive_orientation='high') return measure.find_contours(image, level, **kwargs)
def latt(k, lmean, lmd, wsize, show_plot=False): """Perform Local Adaptive Thresholding Technique of Binarization. k is bias controlling the level of adaptive threshold value is a float scalar in the range [0,1] (0.06 suggested) lmean is the local arithmetic mean of the pixels within the weight x weight window around each pixel is N x M float numpy array lmd is the local mean deviation (intensity minus lmean) is N x M float numpy array wsize is the window size (positive odd integer) Returns ------- tuple of binary mask and contours """ print "w=%d k=%g" % (wsize, k) thresh_image = lmean * (1 + k*(lmd/(1-lmd) - 1.0)) mask = scaled_img < thresh_image print mask contours = measure.find_contours(mask, 0.5, fully_connected='high') ccount = len(contours) if show_plot: plt.title("T.R. Singh et. al LATT $(w=%d, k=%g)$ contours=%d" % (wsize, k, ccount)) plt.imshow(mask, cmap='gray') plt.show() return mask, contours
def contour_features(im): """features 19- 24; contours of the image: number of contours in the image, mean of distance to background, and local maxima:pixel ratio""" contours=[] x_size=int(im.size[1]/float(10)) i=im.resize((x_size,int((im.size[0]/float(im.size[1])*x_size)))) x=i.getdata() z=np.array(x) if z.size/(len(z))==1: if z.size%3 !=0: z= z[0:len(z)-len(z)%3] z= z.reshape(-1,3) #print z.resize(z.size/float(3),3) #print z #contour mapping contour_array=measure.find_contours(z,0.5) len_contours=contours.__len__() contours.append(len_contours) # 19-21: distance features: use ndimage.distance to compute "distance" to background of each pixel. Then find mean among x, y, and z values (r,g,b) distance=ndimage.distance_transform_edt(z) yvaluemean= sum(distance[:,0])/len(distance[:,0]) xvaluemean= sum(distance[:,1])/len(distance[:,1]) zvaluemean= sum(distance[:,2])/len(distance[:,2]) contours.append(yvaluemean) contours.append(xvaluemean) contours.append(zvaluemean) #22-24: local_max features: find number of local maxima among x,y,z values (rgb) compared to the number of pixels local_max=is_local_maximum(distance,z,np.ones((3,3))) xmaxsum, ymaxsum, zmaxsum = [0,0,0] for a in (local_max[:,0]): if a ==False: xmaxsum+=1 contours.append(xmaxsum/float(len(local_max[:,0]))) for a in (local_max[:,1]): if a ==False: ymaxsum+=1 contours.append(ymaxsum/float(len(local_max[:,0]))) for a in (local_max[:,2]): if a ==False: zmaxsum+=1 contours.append(zmaxsum/float(len(local_max[:,0]))) ###25: object count filt_img=ndimage.gaussian_filter(z,10) T=70 labeled,nr_objects=ndimage.label(filt_img>T) contours.append(nr_objects) return contours
def snake_skimage(): # to mitigate the problem of holes in building footprints, we could use # snake. We initialise the snale wioth the contour of axis, then # make the snake balloon # the idea is to work on small street segment one by one # we couls also use a more sophisticated method to compute # all snake at the same time, for instance from PIL import Image import numpy as np import matplotlib.pyplot as plt from skimage.color import rgb2gray from skimage import data from skimage.filters import gaussian from skimage.segmentation import active_contour from skimage import measure from skimage.transform import rotate rotated_image = rotate(axis, 180, resize=True) plt.imshow(rotated_image) np.max(axis); np.min(axis) contours = measure.find_contours(axis*1.0, 0) fig, ax = plt.subplots() ax.imshow(jac, interpolation='nearest', cmap=plt.cm.gray) for n, contour in enumerate(contours): contour[:,[0, 1]] = contour[:,[1, 0]] ax.plot(contour[:, 0], contour[:, 1], linewidth=2) print(n,contour[0,:] ) for n, contour in enumerate(contours): print(n, len(contour)) test_contour = contours[88] snake = active_contour(jac, test_contour , alpha= -1 , beta=10 , gamma=0.001 , max_iterations=50 , bc='periodic' , w_line = -1) fig = plt.figure(figsize=(7, 7)) ax = fig.add_subplot(111) plt.gray() ax.imshow(jac) ax.plot(test_contour[:, 0], test_contour[:, 1], '--r', lw=3) #for n, contour in enumerate(contours): # ax.plot(contours[n][:, 1], contours[n][:, 0], '--r', lw=3) ax.plot(snake[:, 0], snake[:, 1], '-b', lw=3) ax.set_xticks([]), ax.set_yticks([]) ax.axis([0, jac.shape[0], jac.shape[1], 0])
def getImageWords(image): # 删除包含的区域,返回正确的区域 def removeRange(cells): # b in a def rangeInclude(a, b): return b.up >= a.up and b.down <= a.down and b.left >= a.left and b.right <= a.right def rangeCmp(rangeDataA, rangeDataB): return -1 if rangeDataA.down - rangeDataA.up < rangeDataB.down - rangeDataB.up else 1 cells.sort(rangeCmp) n = len(cells) ok = [True] * n for i in xrange(1, n): for j in xrange(i): if ok[j] and rangeInclude(cells[i], cells[j]): ok[j] = False newCells = [cells[i] for i in xrange(n) if ok[i]] return newCells # 零散的字母转为一个单词 def charaterToWord(cells): def theSameLine(rangeDataA, rangeDataB): return abs(rangeDataA.up - rangeDataB.up) < lineSpace and abs(rangeDataA.down - rangeDataB.down) < lineSpace def mycmp(rangeDataA, rangeDataB): if theSameLine(rangeDataA, rangeDataB): return -1 if rangeDataA.left < rangeDataB.left else 1 return -1 if rangeDataA.up < rangeDataB.up else 1 cells.sort(mycmp) lines , wordCnt , lineCnt = [] , 0 , 0 for i , c in enumerate(cells): if not i: lines.append([[]]) elif theSameLine(c, lines[lineCnt][wordCnt][-1]): if c.left - lines[lineCnt][wordCnt][-1].right >= wordSpace: wordCnt += 1 lines[lineCnt].append([]) else: lineCnt += 1 wordCnt = 0 lines.append([[]]) lines[lineCnt][wordCnt].append(c) return lines contours = measure.find_contours(image, 0.8) cells = [] for contour in contours: up, down, left, right = min(contour[:, 0]), max(contour[:, 0]), min(contour[:, 1]), max(contour[:, 1]) if down - up >= wordSpace or right - left >= wordSpace: cells.append(rangeData(up, down, left, right)) cells = removeRange(cells) lines = charaterToWord(cells) print len(cells) totWords = sum(len(line) for line in lines) print totWords return lines
def render_to_surface(self, surface): cx = cairo.Context(surface.surface) grid = np.zeros((self.xsamples, self.ysamples)) for x in range(self.xsamples): for y in range(self.ysamples): grid[x,y] = self.height_func.z([x,y]) # Now window it to 0 Xv, Yv = np.meshgrid(np.linspace(0,1,self.xsamples), np.linspace(0,1,self.ysamples)) #window = 0.5*(1 - np.cos(Xv*2*np.pi)) * 0.5*(1 - np.cos(Yv*2*np.pi)) window = 0.5*np.cos(np.pi*Xv - np.pi/2)**self.alpha * 0.5*np.cos(np.pi*Yv - np.pi/2)**self.alpha grid = grid*window gridmin = np.min(grid.flat) gridmax = np.max(grid.flat) levels = np.linspace(gridmin, gridmax, self.levels+2) np.random.seed(0) contour_levels = [measure.find_contours(grid, level, positive_orientation="low") for level in levels[1:-1]] # Scale everything appropriately for contours in contour_levels: for contour in contours: contour[:,0] = contour[:,0]/self.xsamples*surface.width contour[:,1] = contour[:,1]/self.ysamples*surface.height for level in range(len(contour_levels)-1): col = list(np.random.rand(3,1)) for contour in contour_levels[level]: summed = 0 cx.move_to(contour[0,0], contour[0,1]) for i in range(1,contour.shape[0]): #summed += (contour[i,0] - contour[i-1,0])*(contour[i,1] + contour[i-1,1]) cx.line_to(contour[i,0], contour[i,1]) #if (summed < 0): # counter-clockwise. We need to put an outer square #cx.move_to(0,0) #cx.line_to(0,surface.height) #cx.line_to(surface.width,surface.height) #cx.line_to(surface.width,0) cx.set_source_rgb(0, 0, 0) #cx.stroke_preserve() for contour in contour_levels[level+1]: cx.move_to(contour[0,0], contour[0,1]) for i in range(-1, -contour.shape[0], -1): #summed += (contour[i,0] - contour[i-1,0])*(contour[i,1] + contour[i-1,1]) cx.line_to(contour[i,0], contour[i,1]) #cx.stroke() cx.set_source_rgb(col[0], col[1], col[2]) cx.fill() for contours in contour_levels: for contour in contours: cx.move_to(contour[0,0], contour[0,1]) for i in range(1,contour.shape[0]): #summed += (contour[i,0] - contour[i-1,0])*(contour[i,1] + contour[i-1,1]) cx.line_to(contour[i,0], contour[i,1]) cx.set_source_rgb(0,0,0) cx.stroke()
def test_float(): contours = find_contours(r, 0.5) assert len(contours) == 1 assert_array_equal(contours[0], [[ 2., 3.], [ 1., 2.], [ 2., 1.], [ 3., 2.], [ 2., 3.]])
def hpix_contours(m, levels=[0.9], nest=True): """ Compute iso-lines for a healpix map Parameters: ----------- m: 1D numpy array The input healpix map. levels: list of floats The values for which to compute the iso-lines. Default: [0.5,0.9] nest: boolean If True, nested ordering is assumed for the healpix map. Return: ------- contours: a list of masked numpy arrays Each element in the list is a 2D numpy array containing the contour lines corresponding to a given level. Each contour c in the list has shape (2,N): c[0] represents the RA and c[1] the Dec coordinates of the points constituting the contour. """ nside = hp.npix2nside(len(m)) # define a grid over which to evaluate the density lat = np.linspace(-np.pi / 2., np.pi / 2., 300) lon = np.linspace(0., 2. * np.pi, 300) # evaluate the map and keep track of both coordinates and indices where # the evaluation is done values = np.zeros([300 * 300, 2]) points = np.zeros([300 * 300, 2]) MAP = np.zeros([300, 300]) k = 0 for i in range(300): for j in range(300): p = hp.ang2pix(nside, np.pi / 2. - lat[j], lon[i], nest=nest) MAP[i, j] = m[p] values[k] = np.array([lon[i], lat[j]]) points[k, 0] = i points[k, 1] = j k = k + 1 #construct a linear interpolator to get interpolated #coordinates from fractional indices lint = LinearNDInterpolator(points, values) #use skimage find_contours method to find fractional indices #defining the contours, then compute corresponding coordinates #by using the linear interpolator contours = [] for l in levels: contour_components = measure.find_contours(MAP, l) #the find_contours function above returns a list of the #connected components of the contour. We unpack it, #compute the interpolated coordinates for each, and #store them in one array, separating them with nans whole_contour = np.array([[np.nan, np.nan]]) for contour in contour_components: cont_coords = lint(contour) whole_contour = np.concatenate((whole_contour, cont_coords), axis=0) whole_contour = np.concatenate((whole_contour, [[np.nan, np.nan]]), axis=0) #then we mask the nans C = whole_contour.transpose() contours.append(np.ma.masked_invalid(C)) return contours
def masks_to_polygon(img_mask, label=None, simplify_tol=0, plot_simplify=False, save_name=None): ''' Find contours with skimage, simplify them (optional), store as geojson: 1. Loops over each detected object, creates a mask and finds it contour 2. Contour can be simplified (reduce the number of points) - uses shapely: https://shapely.readthedocs.io/en/stable/manual.html#object.simplify - will be performed if tolernace simplify_tol is != 0 3. Polygons will be saved in geojson format, which can be read by ImJoys' AnnotationTool. Annotations for one image are stored as one feature collection each annotation is one feature: "type": "Feature", "geometry": {"type": "Polygon","coordinates": [[]]} "properties": null Args: img_mask (2D numpy array): image wiht segmentation masks. Background is 0, each object has a unique pixel value. simplify_tol (float): tolerance for simplification (All points in the simplified object will be within the tolerance distance of the original geometry) No simplification will be performed when set to 0. plot_simplify (Boolean): plot results of simplifcation. Plot will be shown for EACH mask. Use better for debuggin only. save_name (string): full file-name to save GeoJson file. Not file will be saved when None. Returns: contours (List): contains polygon of each object stored as a numpy array. feature_collection : GeoJson feature collection ''' # Prepare list to store polygon coordinates and geojson features features = [] contours = [] # Get all object ids, remove 0 since this is background ind_objs = np.unique(img_mask) ind_objs = np.delete(ind_objs, np.where(ind_objs == 0)) # Loop over all masks for obj_int in np.nditer(ind_objs): # Create binary mask for current object and find contour img_mask_loop = np.zeros((img_mask.shape[0], img_mask.shape[1])) img_mask_loop[img_mask == obj_int] = 1 contour = measure.find_contours(img_mask_loop, 0.5) # Proceeed only if one contour was found if len(contour) == 1: contour_asNumpy = contour[0][:, np.argsort([1, 0])] contour_asNumpy[:, 1] = np.array( [img_mask.shape[0] - h[0] for h in contour[0]]) contour_asList = contour_asNumpy.tolist() # Simplify polygon if tolerance is set to any value except 0 if simplify_tol != 0: poly_shapely = shapely_polygon(contour_asList) poly_shapely_simple = poly_shapely.simplify( simplify_tol, preserve_topology=False) contour_asList = list(poly_shapely_simple.exterior.coords) contour_asNumpy = np.asarray(contour_asList) if plot_simplify: plot_polygons(poly_shapely, poly_shapely_simple, obj_int) # Append to polygon list contours.append(contour_asNumpy) # Create and append feature for geojson pol_loop = geojson_polygon([contour_asList]) features.append( Feature(geometry=pol_loop, properties={"label": label})) #elif len(contour) == 0: # print(f'No contour found for object {obj_int}') #else: # print(f'More than one contour found for object {obj_int}') # Save to json file if save_name: feature_collection = FeatureCollection( features, bbox=[0, 0, img_mask.shape[1] - 1, img_mask.shape[0] - 1]) with open(save_name, 'w') as f: dump(feature_collection, f) f.close() return features, contours
new_labels = col_label_list_source.copy() new_label_map = [] for i,label in enumerate(np.unique(new_labels)): new_labels[new_labels == label] = \ i+1 new_label_map.append(label) label_grid=map_to_regular_grid(new_labels, voxel_coords_source).squeeze() label_grid[label_grid==0]=np.nan label_grid_2d=mode(label_grid, axis=int_axis)[0].squeeze() label_grid_2d[label_grid_2d==0]=np.nan label_unique=np.unique(new_labels) label_grid_2d=rearrange_2d(label_grid_2d) ## Compute some region contours and setup helper functions contours = find_contours(label_grid_2d, 385.5) # this threshold just happens # to work ok for visual areas def plot_region_contours(): ''' Convenience function that plots some region boundaries ''' for n, contour in enumerate(contours): ax.plot(contour[:, 1], contour[:, 0], linewidth=1, c='gray') def draw_region_labels(): ''' Convenience function that draws region labels '''
#plt.savefig('/home/nel/NEL-LAB Dropbox/NEL/Papers/VolPy/Figures/plos/original_files/figure3/IVQ32_S2_FOV1_temporal.pdf') #plt.savefig('/home/nel/NEL-LAB Dropbox/NEL/Papers/VolPy/Figures/plos/original_files/figure3/06152017_FIsh1-2_temporal.pdf') plt.savefig('/home/nel/NEL-LAB Dropbox/NEL/Papers/VolPy/Figures/plos/original_files/figure3/FOV4_50um_temporal.pdf') #%% Cn = mov[0] vmax = np.percentile(Cn, 99) vmin = np.percentile(Cn, 5) plt.figure() plt.imshow(Cn, interpolation='None', vmax=vmax, vmin=vmin, cmap=plt.cm.gray) plt.title('Neurons location') d1, d2 = Cn.shape #cm1 = com(mask.copy().reshape((N,-1), order='F').transpose(), d1, d2) colors='yellow' for n, idx in enumerate(idx_volpy): contours = measure.find_contours(mask[idx], 0.5)[0] plt.plot(contours[:, 1], contours[:, 0], linewidth=1, color=colorsets[np.mod(n,9)]) #plt.savefig('/home/nel/NEL-LAB Dropbox/NEL/Papers/VolPy_online/picture/Figures/multiple_neurons/FOV4_50um_footprints.pdf') #plt.savefig('/home/nel/NEL-LAB Dropbox/NEL/Papers/VolPy_online/picture/Figures/multiple_neurons/06152017Fish1-2_footprints.pdf') #plt.savefig('/home/nel/NEL-LAB Dropbox/NEL/Papers/VolPy_online/picture/Figures/multiple_neurons/IVQ32_S2_FOV1_footprints.pdf') #plt.savefig('/home/nel/NEL-LAB Dropbox/NEL/Papers/VolPy/Figures/plos/original_files/figure3/IVQ32_S2_FOV1_spatial.pdf') #plt.savefig('/home/nel/NEL-LAB Dropbox/NEL/Papers/VolPy/Figures/plos/original_files/figure3/06152017_FIsh1-2_spatial.pdf') plt.savefig('/home/nel/NEL-LAB Dropbox/NEL/Papers/VolPy/Figures/plos/original_files/figure3/FOV4_50um_spatial.pdf') #%% idx = 0 plt.figure();plt.plot(signal_filter(caiman_estimates.C, freq=15, fr=400)[idx]) plt.figure();plt.imshow(caiman_estimates.A[:,idx].toarray().reshape((512, 128), order='F'))
int_gamma_prime = io.imread(img_path + n + '/DGP.png', as_grey=True) crop_gamma_prime = int_gamma_prime[170:1277, 433:1539] gamma_prime = cv2.resize(crop_gamma_prime, (1384, 1384)) int_double_prime = io.imread(img_path + n + '/GDP.png', as_grey=True) crop_double_prime = int_double_prime[170:1280, 433:1550] double_prime = cv2.resize(crop_double_prime, (1384, 1384)) gamma_prime_rest = gamma_prime - double_prime gamma_prime = gamma_prime_rest > 0 gamma_prime = morphology.remove_small_objects(gamma_prime, min_size=36, connectivity=2) gamma_prime = clear_border(gamma_prime) contours = measure.find_contours(gamma_prime, 0) list_circle_dia = [] for i in range(0, len(contours)): area_cnt = area(contours[i]) area_cnt = math.sqrt(math.pow(area_cnt, 2)) r_sqr = area_cnt / math.pi r = math.sqrt(r_sqr) list_circle_dia.append(r) list_circle_dia = np.trim_zeros(list_circle_dia) list_circle_dia = filter(lambda a: a != 0.0, list_circle_dia) list_circle_dia = np.array(list_circle_dia) np.savetxt(res_path + 'list_circle' + n + '.csv', list_circle_dia)
def display_instances(image, boxes, masks, class_ids, class_names, scores=None, title="", figsize=(16, 16), ax=None, show_mask=True, show_bbox=True, colors=None, captions=None): """ boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates. masks: [height, width, num_instances] class_ids: [num_instances] class_names: list of class names of the dataset scores: (optional) confidence scores for each box title: (optional) Figure title show_mask, show_bbox: To show masks and bounding boxes or not figsize: (optional) the size of the image colors: (optional) An array or colors to use with each object captions: (optional) A list of strings to use as captions for each object """ # Number of instances N = boxes.shape[0] if not N: print("\n*** No instances to display *** \n") else: assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0] # If no axis is passed, create one and automatically call show() auto_show = False if not ax: _, ax = plt.subplots(1, figsize=figsize) auto_show = True # Generate random colors colors = colors or random_colors(N) # Show area outside image boundaries. height, width = image.shape[:2] ax.set_ylim(height + 10, -10) ax.set_xlim(-10, width + 10) ax.axis('off') ax.set_title(title) masked_image = image.astype(np.uint32).copy() for i in range(N): color = colors[i] # Bounding box if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in image cropping. continue y1, x1, y2, x2 = boxes[i] if show_bbox: p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, alpha=0.7, linestyle="dashed", edgecolor=color, facecolor='none') ax.add_patch(p) # Label if not captions: class_id = class_ids[i] score = scores[i] if scores is not None else None label = class_names[class_id] caption = "{} {:.3f}".format(label, score) if score else label else: caption = captions[i] ax.text(x1, y1 + 8, caption, color='w', size=11, backgroundcolor="none") # Mask mask = masks[:, :, i] if show_mask: masked_image = apply_mask(masked_image, mask, color) # Mask Polygon # Pad to ensure proper polygons for masks that touch image edges. padded_mask = np.zeros( (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 p = Polygon(verts, facecolor="none", edgecolor=color) ax.add_patch(p) ax.imshow(masked_image.astype(np.uint8)) if auto_show: plt.show()
def draw_boxes(image, boxes=None, refined_boxes=None, masks=None, captions=None, visibilities=None, title="", ax=None): """Draw bounding boxes and segmentation masks with different customizations. boxes: [N, (y1, x1, y2, x2, class_id)] in image coordinates. refined_boxes: Like boxes, but draw with solid lines to show that they're the result of refining 'boxes'. masks: [N, height, width] captions: List of N titles to display on each box visibilities: (optional) List of values of 0, 1, or 2. Determine how prominent each bounding box should be. title: An optional title to show over the image ax: (optional) Matplotlib axis to draw on. """ # Number of boxes assert boxes is not None or refined_boxes is not None N = boxes.shape[0] if boxes is not None else refined_boxes.shape[0] # Matplotlib Axis if not ax: _, ax = plt.subplots(1, figsize=(12, 12)) # Generate random colors colors = random_colors(N) # Show area outside image boundaries. margin = image.shape[0] // 10 ax.set_ylim(image.shape[0] + margin, -margin) ax.set_xlim(-margin, image.shape[1] + margin) ax.axis('off') ax.set_title(title) masked_image = image.astype(np.uint32).copy() for i in range(N): # Box visibility visibility = visibilities[i] if visibilities is not None else 1 if visibility == 0: color = "gray" style = "dotted" alpha = 0.5 elif visibility == 1: color = colors[i] style = "dotted" alpha = 1 elif visibility == 2: color = colors[i] style = "solid" alpha = 1 # Boxes if boxes is not None: if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in cropping. continue y1, x1, y2, x2 = boxes[i] p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, alpha=alpha, linestyle=style, edgecolor=color, facecolor='none') ax.add_patch(p) # Refined boxes if refined_boxes is not None and visibility > 0: ry1, rx1, ry2, rx2 = refined_boxes[i].astype(np.int32) p = patches.Rectangle((rx1, ry1), rx2 - rx1, ry2 - ry1, linewidth=2, edgecolor=color, facecolor='none') ax.add_patch(p) # Connect the top-left corners of the anchor and proposal if boxes is not None: ax.add_line(lines.Line2D([x1, rx1], [y1, ry1], color=color)) # Captions if captions is not None: caption = captions[i] # If there are refined boxes, display captions on them if refined_boxes is not None: y1, x1, y2, x2 = ry1, rx1, ry2, rx2 ax.text(x1, y1, caption, size=11, verticalalignment='top', color='w', backgroundcolor="none", bbox={'facecolor': color, 'alpha': 0.5, 'pad': 2, 'edgecolor': 'none'}) # Masks if masks is not None: mask = masks[:, :, i] masked_image = apply_mask(masked_image, mask, color) # Mask Polygon # Pad to ensure proper polygons for masks that touch image edges. padded_mask = np.zeros( (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 p = Polygon(verts, facecolor="none", edgecolor=color) ax.add_patch(p) ax.imshow(masked_image.astype(np.uint8))
def save_images(path, image, boxes, masks, class_ids, class_names, scores=None, title="", figsize=(16, 16), ax=None, show_mask=True, show_bbox=True, colors=None, captions=None): # mpl.rcParams["savefig.directory"] = pathsave # Number of instances N = boxes.shape[0] if not N: print("\n*** No instances to display *** \n") else: assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0] # If no axis is passed, create one and automatically call show() auto_show = False if not ax: _, ax = plt.subplots(1, figsize=figsize) auto_show = True # Generate random colors colors = colors or random_colors(N) # Show area outside image boundaries. height, width = image.shape[:2] ax.set_ylim(height + 10, -10) ax.set_xlim(-10, width + 10) ax.axis('off') ax.set_title(title) masked_image = image.astype(np.uint32).copy() for i in range(N): color = colors[i] # Bounding box if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in image cropping. continue y1, x1, y2, x2 = boxes[i] if show_bbox: p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, alpha=0.7, linestyle="dashed", edgecolor=color, facecolor='none') ax.add_patch(p) # Label if not captions: class_id = class_ids[i] score = scores[i] if scores is not None else None label = class_names[class_id] caption = "{} {:.3f}".format(label, score) if score else label else: caption = captions[i] ax.text(x1, y1 + 8, caption, color='w', size=11, backgroundcolor="none") # Mask mask = masks[:, :, i] if show_mask: masked_image = apply_mask(masked_image, mask, color) # Mask Polygon # Pad to ensure proper polygons for masks that touch image edges. padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 p = Polygon(verts, facecolor="none", edgecolor=color) ax.add_patch(p) ax.imshow(masked_image.astype(np.uint8)) if auto_show: fig = plt.gcf() #fig.show() fig.savefig(path) #file_name = "predection_{:%Y%m%dT%H%M%S}.png".format(datetime.datetime.now()) #skimage.io.imsave(file_name, path) print("saving images in dataset/results")
def plot_countours(mfill, name, display=True, mm=np.array([False]), save=False, filled=False, rotate='style'): #gets list of overalys, and plts and saves them. low_val = int(np.floor(mfill.min()) + 1) high_val = int(np.floor(mfill.max()) - 1) percentiles = [] if (high_val - low_val) > 0: # plt.cla() levels = [] num = high_val - low_val #cyle linestyles lines = ["-.", ":", "-", "--"] linecycler = cycle(lines) #cyle colors color = ['o', 'm', 'b', "y"] colorcycler = cycle(color) #print("low:" + str(low_val)) #print("high:" + str(high_val)) for percentile in [.3 * high_val, .5 * high_val, .7 * high_val]: # find each contour for one image #print("lvl") contours = find_contours(mfill, level=percentile) levels.append(contours) if mm.any(): # imshow min_max outlines #print("mm") plt.imshow(mm) elif filled: #imshow filled shapes plt.imshow(mfill) else: # imshow nothing (no background) plt.imshow(np.zeros_like(mfill)) for level in levels: # for each contour of this value for n, contour in enumerate( level): # plot each conout of that value #find shape of conoutrs and save them percent = find_array(contour, mfill.shape) percentiles.append(percent) if rotate == 'style': plt.plot(contour[:, 1], contour[:, 0], next(linecycler), linewidth=.5, color='w') # cycle line styles elif rotate == 'color': #print("color") plt.plot(contour[:, 1], contour[:, 0], next(colorcycler), linewidth=.5, markersize=.5) # cycle line styles else: print('Invalide selction for "rotate"') plt.axis('off') if display: plt.title(name) plt.tight_layout() if save: plt.savefig(name + "_contours.png", dpi=600) if display: plt.show() return percentiles else: print("no intermediate contours") return
def marchingSquareBinaryData(data,threshold=0.5): starttime = datetime.datetime.now() contours = measure.find_contours(data, threshold) endtime = datetime.datetime.now() print(endtime - starttime) return contours
def display_instances(image,config,filename,boxes, masks, class_ids, class_names, scores=None, title="", figsize=(16, 16), ax=None): """ boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates. masks: [height, width, num_instances] class_ids: [num_instances] class_names: list of class names of the dataset scores: (optional) confidence scores for each box figsize: (optional) the size of the image. """ # Number of instances N = boxes.shape[0] if not N: print("\n*** No instances to display *** \n") else: assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0] if not ax: _, ax = plt.subplots(1, figsize=figsize) plt.subplots_adjust(top=1,bottom=0,left=0,right=1,hspace=0,wspace=0) # Generate random colors colors = random_colors(N) # Show area outside image boundaries. height, width = image.shape[:2] ax.set_ylim(height , 0) ax.set_xlim(0, width ) ax.axis('off') ax.set_title(title) masked_image = image.astype(np.uint32).copy() for i in range(N): color = colors[i] # Bounding box if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in image cropping. continue y1, x1, y2, x2 = boxes[i] p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, alpha=0.7, linestyle="dashed", edgecolor=color, facecolor='none') ax.add_patch(p) # Label class_id = class_ids[i] score = scores[i] if scores is not None else None label = class_names[class_id] x = random.randint(x1, (x1 + x2) // 2) caption = "{} {:.3f}".format(label, score) if score else label ax.text(x1, y1 + 8, caption, color='w', size=11, backgroundcolor="none") # Mask mask = masks[:, :, i] masked_image = apply_mask(masked_image, mask, color) distance,angle=apply_distance(mask,filename,config) distance=int(distance)*1.0/1000 show_information=str(distance)+' m'+' '+str(int(angle))+'°' ax.text(x1, y2, show_information, color='w', size=11, backgroundcolor="none") # Mask Polygon # Pad to ensure proper polygons for masks that touch image edges. padded_mask = np.zeros( (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 p = Polygon(verts, facecolor="none", edgecolor=color) ax.add_patch(p) name=filename.split('/')[-1].split('-')[0] with open(config.test_image_dir+'/result/'+name+'.txt',"a") as f: f.write(label) f.write('##') f.write(str(distance)) f.write('##') f.write(str(int(angle))) f.write('\n') ax.imshow(masked_image.astype(np.uint8)) plt.savefig(config.test_image_dir+'/result/'+name+'.jpg') plt.clf()
def plot_gaia_sources_on_tpf( tpf, target_gaiaid, gaia_sources=None, sap_mask="pipeline", depth=None, kmax=1, dmag_limit=8, fov_rad=None, cmap="viridis", figsize=None, ax=None, invert_xaxis=False, invert_yaxis=False, pix_scale=TESS_pix_scale, verbose=True, **mask_kwargs, ): """ plot gaia sources brighter than dmag_limit; only annotated with starids are those that are bright enough to cause reproduce the transit depth; starids are in increasing separation dmag_limit : float maximum delta mag to consider; computed based on depth if None TODO: correct for proper motion difference between survey image and gaia DR2 positions """ if verbose: print("Plotting nearby gaia sources on tpf.") assert target_gaiaid is not None img = np.nanmedian(tpf.flux, axis=0) # make aperture mask mask = parse_aperture_mask(tpf, sap_mask=sap_mask, **mask_kwargs) ax = plot_aperture_outline(img, mask=mask, imgwcs=tpf.wcs, figsize=figsize, cmap=cmap, ax=ax) if fov_rad is None: nx, ny = tpf.shape[1:] diag = np.sqrt(nx**2 + ny**2) fov_rad = (0.4 * diag * pix_scale).to(u.arcmin).round(0) if gaia_sources is None: print( "Querying Gaia sometimes hangs. Provide `gaia_sources` if you can." ) target_coord = SkyCoord(ra=tpf.header["RA_OBJ"], dec=tpf.header["DEC_OBJ"], unit="deg") gaia_sources = Catalogs.query_region(target_coord, radius=fov_rad, catalog="Gaia", version=2).to_pandas() assert len(gaia_sources) > 1, "gaia_sources contains single entry" # find sources within mask # target is assumed to be the first row idx = gaia_sources["source_id"].astype(int).isin([target_gaiaid]) target_gmag = gaia_sources.loc[idx, "phot_g_mean_mag"].values[0] # sources_inside_aperture = [] if depth is not None: # compute delta mag limit given transit depth dmag_limit = (np.log10(kmax / depth - 1) if dmag_limit is None else dmag_limit) # get min_gmag inside mask ra, dec = gaia_sources[["ra", "dec"]].values.T pix_coords = tpf.wcs.all_world2pix(np.c_[ra, dec], 0) contour_points = measure.find_contours(mask, level=0.1)[0] isinside = [ is_point_inside_mask(contour_points, pix) for pix in pix_coords ] # sources_inside_aperture.append(isinside) min_gmag = gaia_sources.loc[isinside, "phot_g_mean_mag"].min() if (target_gmag - min_gmag) != 0: print( f"target Gmag={target_gmag:.2f} is not the brightest within aperture (Gmag={min_gmag:.2f})" ) else: min_gmag = gaia_sources.phot_g_mean_mag.min() # brightest dmag_limit = (gaia_sources.phot_g_mean_mag.max() if dmag_limit is None else dmag_limit) base_ms = 128.0 # base marker size starid = 1 # if very crowded, plot only top N gmags = gaia_sources.phot_g_mean_mag dmags = gmags - target_gmag rank = np.argsort(dmags.values) for index, row in gaia_sources.iterrows(): # FIXME: why some indexes are missing? ra, dec, gmag, id = row[["ra", "dec", "phot_g_mean_mag", "source_id"]] dmag = gmag - target_gmag pix = tpf.wcs.all_world2pix(np.c_[ra, dec], 0)[0] contour_points = measure.find_contours(mask, level=0.1)[0] color, alpha = "red", 1.0 # change marker color and transparency depending on the location and dmag if is_point_inside_mask(contour_points, pix): if int(id) == int(target_gaiaid): # plot x on target ax.plot( pix[1], pix[0], marker="x", ms=base_ms / 16, c="k", zorder=3, ) if depth is not None: # compute flux ratio with respect to brightest star gamma = 1 + 10**(0.4 * (min_gmag - gmag)) if depth > kmax / gamma: # orange if flux is insignificant color = "C1" else: # outside aperture color, alpha = "C1", 0.5 ax.scatter( pix[1], pix[0], s=base_ms / 2**dmag, # fainter -> smaller c=color, alpha=alpha, zorder=2, edgecolor=None, ) # choose which star to annotate if len(gmags) < 20: # sparse: annotate all ax.text(pix[1], pix[0], str(starid), color="white", zorder=100) elif len(gmags) > 50: # crowded: annotate only 15 smallest dmag ones if rank[starid - 1] < 15: ax.text(pix[1], pix[0], str(starid), color="white", zorder=100) elif (color == "red") & (dmag < dmag_limit): # plot if within aperture and significant source of dilution ax.text(pix[1], pix[0], str(starid), color="white", zorder=100) elif color == "red": # neither sparse nor crowded # annotate if inside aperture ax.text(pix[1], pix[0], str(starid), color="white", zorder=100) starid += 1 # Make legend with 4 sizes representative of delta mags dmags = dmags[dmags < dmag_limit] _, dmags = pd.cut(dmags, 3, retbins=True) for dmag in dmags: size = base_ms / 2**dmag # -1, -1 is outside the fov # dmag = 0 if float(dmag)==0 else 0 ax.scatter( -1, -1, s=size, c="red", alpha=0.6, edgecolor=None, zorder=10, clip_on=True, label=r"$\Delta m= $" + f"{dmag:.1f}", ) ax.legend(fancybox=True, framealpha=0.5) # set img limits xdeg = (nx * pix_scale).to(u.arcmin) ydeg = (ny * pix_scale).to(u.arcmin) # orient such that north is up; east is left if invert_yaxis: # ax.invert_yaxis() # increasing upward raise NotImplementedError() if invert_xaxis: # ax.invert_xaxis() #decresing rightward raise NotImplementedError() if hasattr(ax, "coords"): ax.coords[0].set_major_formatter("dd:mm") ax.coords[1].set_major_formatter("dd:mm") pl.setp(ax, xlim=(0, nx), ylim=(0, ny), xlabel=f"({xdeg:.2f} x {ydeg:.2f})") return ax
def create_json(output_file_name, ref_json, cam5_list, cam6_list): # read json template with open('instances_val2017_template.json') as json_data: d = json.load(json_data) with open(ref_json) as ref: d_ref = json.load(ref) json_copy = copy.deepcopy(d) json_copy['images'] = [] json_copy['annotations'] = [] kaggle_to_coco = { 36: 1, #person 35: 2, #bicycle 33: 3, #car 34: 4, #motorcycle 39: 6, #bus 38: 8, #truck 40: 2 #tricycle => bicycle } annotation_counter = 0 counter = 0 missing_counter = 0 for clip in d_ref['images']: clip_images = get_clip_images( clip['file_name'].split('.')[0] + '_instanceIds.png', cam5_list, cam6_list) if clip_images is None: missing_counter += 1 continue for i, single_image in enumerate(clip_images): if counter % 50 == 0: print("{} images so far".format(counter)) image_name = single_image file_name = image_name.replace('_instanceIds', '') file_name = file_name.replace('.png', '.jpg') json_single_image = copy.deepcopy(d['images'][0]) json_single_image['file_name'] = file_name json_single_image['id'] = counter json_copy['images'].append(json_single_image) #print(json_copy['images']) filepath = pwd + '/train_label/' + image_name img = cv2.imread(filepath, -1) instance_label = np.unique(img) instance_label = instance_label[instance_label != 255].tolist() instance_label = [ item for item in instance_label if item // 1000 in kaggle_to_coco ] id_list = list( map(lambda x: kaggle_to_coco[x // 1000], instance_label)) mask_list = [] for val in instance_label: mask_list.append(np.uint8(1) * (img == val)) # print(mask_list) for j, mask_i in enumerate(mask_list): ground_truth_binary_mask = mask_i mask_sum = np.sum(mask_i) fortran_ground_truth_binary_mask = np.asfortranarray( ground_truth_binary_mask) encoded_ground_truth = mask.encode( fortran_ground_truth_binary_mask) ground_truth_area = mask.area(encoded_ground_truth) ground_truth_bounding_box = mask.toBbox(encoded_ground_truth) contours = measure.find_contours(ground_truth_binary_mask, 0.5) annotation = { "segmentation": [], "area": ground_truth_area.tolist(), "iscrowd": 0, "image_id": counter, "bbox": ground_truth_bounding_box.tolist(), "category_id": id_list[j], "id": annotation_counter } annotation_counter += 1 for contour in contours: contour = np.flip(contour, axis=1) segmentation = contour.ravel().tolist() annotation["segmentation"].append(segmentation) json_copy['annotations'].append(annotation) #print(json.dumps(annotation, indent=4)) #print(mask_sum) counter += 1 with open(output_file_name + '.json', 'w') as f: json.dump(json_copy, f, ensure_ascii=False) print("missing counter is {}".format(missing_counter))
def generate_slice(slice_num, image_slice, segmentation_slice, out_path, aspect=1.0, color='gray', extra=None): contour_width = 1.8 # Start with the ablated region if there is one part_contours = measure.find_contours( segmentation_slice.data.squeeze().cpu().numpy(), 0.5) if extra is not None: extra_contours = measure.find_contours( extra.data.squeeze().cpu().numpy(), 0.5) # Plot the original image plt.figure() plt.imshow(image_slice, cmap='gray', aspect=1.0 / aspect, interpolation='nearest') plt.axis('off') plt.show() # plt.gca().invert_yaxis() # plt.savefig(f'{out_path}/Images/{slice_num:03d}_image.png', dpi=600, bbox_inches='tight', pad_inches=0) # plt.gca().invert_yaxis() if extra is not None: from matplotlib.colors import LinearSegmentedColormap colors = [(0.0, 0.0, 0.0), (0.8901960784313725, 0.4666666666666667, 0.7607843137254902)] cm = LinearSegmentedColormap.from_list('hist_color', colors, N=1) masked = np.ma.masked_where(extra.squeeze() == 0, extra.squeeze()) plt.imshow(masked, cmap=cm, aspect=1.0 / aspect, alpha=0.7) # plt.axis('off') # plt.gca().invert_yaxis() # plt.gca().patch.set_facecolor([0, 0, 0, 0]) # try: # for contour in extra_contours: # plt.plot(contour[:, 1], contour[:, 0], color=matplotlib._cm._tab10_data[6], linewidth=contour_width) # except IndexError: # pass try: for contour in part_contours: plt.plot(contour[:, 1], contour[:, 0], color=color, linewidth=contour_width) except IndexError: pass plt.pause(1.0) plt.gca().invert_yaxis() plt.savefig(f'{out_path}/Shaded/im_{slice_num:03d}_shaded.png', dpi=600, bbox_inches='tight', pad_inches=0) plt.close('all')
def show_fig2(): contours = measure.find_contours(phi, 0) ax2 = fig2.add_subplot(111) ax2.imshow(img, interpolation='nearest', cmap=plt.cm.gray) for n, contour in enumerate(contours): ax2.plot(contour[:, 1], contour[:, 0], linewidth=2)
def extract_coastlines( nc_file, nc_vars, region_box, z_contour=0, n_longest=10, point_list=None, # {{{ plot_option=False, plot_box=[], call=None): print("Extract coastlines") print("------------------") # Open NetCDF file and read cooordintes nc_fid = Dataset(nc_file, "r") lon = nc_fid.variables[nc_vars[0]][:] lat = nc_fid.variables[nc_vars[1]][:] bathy_data = nc_fid.variables[nc_vars[2]] # Get coastlines for refined region coastline_list = [] for i, box in enumerate(region_box["include"]): # Find coordinates and data inside bounding box xb, rect = get_convex_hull_coordinates(box) lon_region, lat_region, z_region = get_data_inside_box( lon, lat, bathy_data, xb) z_data = np.zeros(z_region.shape) z_data.fill(np.nan) idx = get_indices_inside_quad(lon_region, lat_region, box) z_data[idx] = z_region[idx] print(" Regional bathymetry data shape:", z_region.shape) # Find coastline contours print(" Extracting coastline " + str(i + 1) + "/" + str(len(region_box["include"]))) contours = measure.find_contours(z_data, z_contour) # Keep only n_longest coastlines and those not within exclude areas contours.sort(key=len, reverse=True) for c in contours[:n_longest]: # Convert from pixel to lon,lat c[:, 0] = (xb[3] - xb[2]) / float(len(lat_region)) * c[:, 0] + xb[2] c[:, 1] = (xb[1] - xb[0]) / float(len(lon_region)) * c[:, 1] + xb[0] c = np.fliplr(c) exclude = False for area in region_box["exclude"]: # Determine coastline coordinates in exclude area idx = get_indices_inside_quad(c[:, 0], c[:, 1], area, grid=False) # Exlude coastlines that are entirely contained in exclude area if idx.size == c.shape[0]: exclude = True break elif idx.size != 0: c = np.delete(c, idx, axis=0) # Keep coastlines not entirely contained in exclude areas if not exclude: cpad = np.vstack((c, [np.nan, np.nan])) coastline_list.append(cpad) print(" Done") # Add in user-specified points if point_list: for i, points in enumerate(point_list): cpad = np.vstack((points, [np.nan, np.nan])) coastline_list.append(cpad) # Combine coastlines coastlines = np.concatenate(coastline_list) if plot_option: print(" Plotting coastlines") # Find coordinates and data inside plotting box lon_plot, lat_plot, z_plot = get_data_inside_box( lon, lat, bathy_data, plot_box) # Plot bathymetry data, coastlines and region boxes fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) levels = np.linspace(np.amin(z_plot), np.amax(z_plot), 100) ds = 100 # Downsample dsx = np.arange(0, lon_plot.size, ds) # bathy data dsy = np.arange(0, lat_plot.size, ds) # to speed up dsxy = np.ix_(dsy, dsx) # plotting plt.contourf(lon_plot[dsx], lat_plot[dsy], z_plot[dsxy], levels=levels, transform=ccrs.PlateCarree()) plot_coarse_coast(ax, plot_box) plt.plot(coastlines[:, 0], coastlines[:, 1], color='white') for box in region_box["include"]: plot_region_box(box, 'b') for box in region_box["exclude"]: plot_region_box(box, 'r') plt.colorbar() plt.axis('equal') plt.savefig('bathy_coastlines' + str(call) + '.png', bbox_inches='tight') plt.close() print(" Done") return coastlines # }}}
res = scansize/slen res_difference = 2e-9 if (deadlayer): Ms = material_params['Ms2'] thickness = material_params['t2'] else: Ms = material_params['Ms'] thickness = material_params['t'] Keff = material_params['Keff'] dlen = len(domains) dres = 2.0e-9 contours = measure.find_contours(domains, 0.0) num_contours = len(contours) total_wall_length = 0 smoothed_contours = np.zeros_like(contours) contour_length = 0 for i in range(0, len(contours)): contour_length, smoothed_contour = get_interpolated_contour(contours[i]) smoothed_contours[i] = np.transpose(smoothed_contour) total_wall_length += res*contour_length print('total_wall_length = ' + str(total_wall_length)) total_wall_length_norm = total_wall_length/( (res*(dlen-2))**2 )
import time import numpy as np from skimage import io from skimage.morphology import dilation from skimage.filters import gaussian from skimage.measure import find_contours from skimage.segmentation import active_contour step = 2 init_num = 256 print('Initiliaze') img_init = io.imread('./init%d_2.png'%(init_num), as_grey=True) img_init = dilation(img_init) init = find_contours(img_init, 0.5) init = init[0][::50] init = init[::-1,::-1] init = init[init[:,0].argsort()] #init_int = np.array(init, dtype=np.int32) #img_init = np.zeros_like(img_init) #color = 1 #for i in [-1,0,1]: # for j in [-1,0,1]: # img_init[init_int[:,1]+i,init_int[:,0]+j] = color #io.imsave('img_init.bmp', img_init) print(init) print(np.shape(init)) for i in range(init_num-step,init_num-20*step,-step): print('Load image', i) img = io.imread('./../OCT_image/1026_with_glass_bead_before_irradiation/Filename_%04d.png'%(i)) img_org = np.sum(img[:,:,:3], axis=2)/3 img_org = gaussian(img, 3)
def showlabel(self, smallest_size, theMask, original_intensity, threshold, i, j, cell_properties): # remove artifacts connected to image border self.Labelmask = theMask self.OriginImag = original_intensity self.row_num = i self.column_num = j self.threshold = threshold cleared = self.Labelmask.copy() clear_border(cleared) # label image regions label_image = label(cleared) #image_label_overlay = label2rgb(label_image, image=image) self.fig_showlabel, self.ax_showlabel = plt.subplots(ncols=1, nrows=1, figsize=(6, 6)) #plt.figure(self.row_num+self.column_num) self.ax_showlabel.imshow(label_image) loopmun1 = 0 for region in regionprops(label_image, intensity_image=self.OriginImag): # skip small images if region.area > smallest_size: # draw rectangle around segmented coins minr, minc, maxr, maxc = region.bbox rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='red', linewidth=2) self.ax_showlabel.add_patch(rect) filledimg = region.filled_image #Binary region image with filled holes which has the same size as bounding box. #filledperimeter = perimeter(filledimg) #singlethresh = threshold_otsu(filledimg) #print(singlethresh) #print(filledperimeter) #print(region.perimeter) #print(region.filled_area) #print(str(minc)+', '+str(maxc)+', '+str(minr)+', '+str(maxr)) #s=imageanalysistoolbox() #contourimage = s.contour(filledimg, self.intensityimage, singlethresh) #contour_mask = s.inwarddilationmask(contourimage ,filledimg, 15) contours = find_contours( filledimg, 0.8 ) # Find iso-valued contours in a 2D array for a given level value. for n, contour in enumerate(contours): #print(contour[1,0]) #col = contour[:, 1] #row = contour[:, 0] #col1 = [int(round(i)) for i in col] #row1 = [int(round(i)) for i in row] #for m in range(len(col1)): #self.intensityimage[row1[m], col1[m]] = 5 #filledimg[contour[:, 0], contour[:, 1]] = 2 self.ax_showlabel.plot(contour[:, 1] + minc, contour[:, 0] + minr, linewidth=1, color='yellow') x1 = cell_properties['Change'][loopmun1] x2 = cell_properties['Mean intensity in contour'][loopmun1] x3 = cell_properties['Circularity'][loopmun1] #circularity = (4 * math.pi * region.filled_area) / (filledperimeter * filledperimeter) # region.perimeter will count in perimeters from the holes inside self.ax_showlabel.text( (maxc + minc) / 2, (maxr + minr) / 2, str(round(x1, 3)) + ', ' + str(round(x2, 3)) + ', ' + str(round(x3, 3)), fontsize=8, color='yellow', style='italic' ) #,bbox={'facecolor':'red', 'alpha':0.3, 'pad':8}) #ax.plot(contours[:, 1], contours[:, 0], linewidth=2) loopmun1 = loopmun1 + 1 #plt.show() self.ax_showlabel.set_axis_off()
v = np.median(filteredImg) print(v) #---- apply automatic Canny edge detection using the computed median---- sigma = 0.1 lower = max(0, (1.0 - sigma) * v) upper = min(1, (1.0 + sigma) * v) print(lower, upper) edgeImg = feature.canny( filteredImg) #, low_threshold = lower, high_threshold = upper) dilatedImg = dilation(edgeImg) for i in range(2): dilatedImg = dilation(dilatedImg) from skimage import measure contours = measure.find_contours(dilatedImg, 0.8) from functools import * kMin = lambda x, y: [min(x[0], y[0]), min(x[1], y[1])] kMax = lambda x, y: [max(x[0], y[0]), max(x[1], y[1])] diff = lambda x, y: [abs(x[0] - y[0]), abs(x[1] - y[1])] width, height = dilatedImg.shape def acceptable(x): [x0, y0], [x1, y1] = reduce(kMin, x), reduce(kMax, x) if x0 - 5 < 0 or y0 - 5 < 0 or x1 + 5 >= width or y1 + 5 >= height: return False diffHeight = diff([x0, y0], [x1, y1]) return ((diffHeight[0] > 50 or diffHeight[1] > 50) and not (diffHeight[0] > width * 4 / 5 and diffHeight[1] > height * 4 / 5))
def display_instance(image,boxes,masks,ids,names,scores): n_instance = boxes.shape[0] colors = random_colors1(n_instance) if not n_instance: print("no instance to display") else: assert boxes.shape[0] == masks.shape[-1] == ids.shape[0] #colors = random_colors(n_instance) leaf_num = 0 root_num = 0 root_green_num = 0 root_white_num = 0 leaf_yellow_num = 0 leaf_green_num = 0 total_leaf_length = 0 total_leaf_area = 0 total_leaf_width = 0 total_leafgreen_area = 0 total_leafyellow_area = 0 total_root_length = 0 total_rootgreen_length = 0 total_rootwhite_length = 0 avg_leaf_area = 0 avg_leaf_width = 0 avg_leaf_length = 0 avg_root_length = 0 avg_rootgreen_length = 0 avg_rootwhite_length = 0 avg_leafyellow_area = 0 avg_leafgreen_area = 0 height,width = image.shape[:2] for i in range(n_instance): color = colors[i] if not np.any(boxes[i]): continue y1,x1,y2,x2 = boxes[i] mask = masks[:,:,i] label = names[ids[i]] color = class_dict[label] image = cv2.rectangle(image, (x1, y1), (x2, y2), color, 2) image = apply_mask(image,mask,color) padded_mask = np.zeros( (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) binary_1,contours_1,hierarchy_1 = cv2.findContours(padded_mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) image = cv2.drawContours(image,contours_1,-1,color,1) score = scores[i] if scores is not None else None caption = '{}:{:.2f}'.format(label,score) if score else label #image = cv2.putText(image,caption,(x1,y1-10),cv2.FONT_HERSHEY_SIMPLEX,0.6,color,2) if label == 'leaf': skeleton = morphology.skeletonize(padded_mask) binary_2, contours_2, hierarchy_2 = cv2.findContours(skeleton.astype('uint8'), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) #plt.imshow(skeleton,cmap="gray") #plt.contour(skeleton,cmap=plt.get_cmap("Spectral")) #plt.show() #print(np.array(contours_2).shape) if len(np.array(contours_2).shape) == 1: leaflength = 0 for i in range(np.array(contours_2).shape[0]): arr = np.array(contours_2[i]).squeeze() if len(np.array(arr).shape) ==1: leaflength += 7.5 else: #length += cv2.arcLength(np.unique(np.array(arr),axis=0), False) leaflength += cv2.arcLength(arr, True)/2 + 7.5 else: contours_2 = np.array(contours_2).squeeze() #contours_2 = np.unique(np.array(contours_2),axis=0) if len(np.array(contours_2).shape) == 1: leaflength = 7.5 else: leaflength = cv2.arcLength(contours_2, True)/2 + 7.5 #print(leaflength) #cv2.putText(image, "length:{}cm".format(round(leaflength/57.5,2)),(x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2) total_leaf_length += leaflength leaf_num+=1 #leafarea = 0 '''for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 #p = Polygon(verts, facecolor="none", edgecolor=color) leafarea += math.ceil(area(verts))''' leafarea = np.sum([math.ceil(area(np.fliplr(verts) - 1)) for verts in contours]) #cv2.putText(image,"Area:{}cm2".format(round(leafarea/3150,2)),(x1,y1-10),cv2.FONT_HERSHEY_SIMPLEX,0.6,color,2) #print(leafarea) total_leaf_area += leafarea cnt = np.array(contours_1[0]) # print(cnt) rect = cv2.minAreaRect(cnt) leafwidth = np.min(rect[1]) #box = np.int0(cv2.boxPoints(rect)) #cv2.drawContours(image, [box], 0, (255, 0, 0), 2) #print(leafwidth) cv2.putText(image, "width:{}cm".format(round(leafwidth/57.5,2)),(x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2) total_leaf_width += leafwidth elif label == 'root': skeleton = morphology.skeletonize_3d(padded_mask) binary_2, contours_2, hierarchy_2 = cv2.findContours(skeleton.astype('uint8'), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) #plt.imshow(skeleton,cmap="gray") #plt.contour(skeleton,cmap=plt.get_cmap("Spectral")) #plt.show() #print(np.array(contours_2).squeeze()[0].shape) if len(np.array(contours_2).shape) == 1: rootlength = 0 for i in range(np.array(contours_2).shape[0]): arr = np.array(contours_2[i]).squeeze() if len(np.array(arr).shape) == 1: rootlength += 7.5 else: # rootlength += cv2.arcLength(np.unique(np.array(arr),axis=0), False) rootlength += cv2.arcLength(arr, True) / 2 + 7.5 else: contours_2 = np.array(contours_2).squeeze() # contours_2 = np.unique(np.array(contours_2),axis=0) if len(np.array(contours_2).shape) == 1: rootlength = 7.5 elif len(np.array(contours_2).shape) == 3: rootlength = np.sum([cv2.arcLength(contours_2[index], True) / 2 + 7.5 for index in range(contours_2.shape[0])]) else: rootlength = cv2.arcLength(contours_2, True) / 2 + 7.5 #print(rootlength) #cv2.putText(image, "length:{}cm".format(round(rootlength/57.5,2)),(x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2) total_root_length += rootlength root_num += 1 elif label == 'rgreen': skeleton = morphology.skeletonize_3d(padded_mask) binary_2, contours_2, hierarchy_2 = cv2.findContours(skeleton.astype('uint8'), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) #plt.imshow(skeleton,cmap="gray") #plt.contour(skeleton,cmap=plt.get_cmap("Spectral")) #plt.show() # print(np.array(contours_2).shape) if len(np.array(contours_2).shape) == 1: rootgreenlength = 0 for i in range(np.array(contours_2).shape[0]): arr = np.array(contours_2[i]).squeeze() if len(np.array(arr).shape) == 1: rootgreenlength += 7.5 else: # length += cv2.arcLength(np.unique(np.array(arr),axis=0), False) rootgreenlength += cv2.arcLength(arr, True) / 2 + 7.5 else: contours_2 = np.array(contours_2).squeeze() # contours_2 = np.unique(np.array(contours_2),axis=0) if len(np.array(contours_2).shape) == 1: rootgreenlength = 7.5 else: rootgreenlength = cv2.arcLength(contours_2, True) / 2 + 7.5 #print(rootgreenlength) #cv2.putText(image, "length:{}cm".format(round(rootgreenlength/57.5,2)),(x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2) root_green_num += 1 total_rootgreen_length += rootgreenlength elif label == 'rwhite': skeleton = morphology.skeletonize_3d(padded_mask) binary_2, contours_2, hierarchy_2 = cv2.findContours(skeleton.astype('uint8'), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) #plt.imshow(skeleton,cmap="gray") #plt.contour(skeleton,cmap=plt.get_cmap("Spectral")) #plt.show() # print(np.array(contours_2).shape) if len(np.array(contours_2).shape) == 1: rootwhitelength = 0 for i in range(np.array(contours_2).shape[0]): arr = np.array(contours_2[i]).squeeze() if len(np.array(arr).shape) == 1: rootwhitelength += 7.5 else: # length += cv2.arcLength(np.unique(np.array(arr),axis=0), False) rootwhitelength += cv2.arcLength(arr, True) / 2 + 7.5 else: contours_2 = np.array(contours_2).squeeze() # contours_2 = np.unique(np.array(contours_2),axis=0) if len(np.array(contours_2).shape) == 1: rootwhitelength = 7.5 else: rootwhitelength = cv2.arcLength(contours_2, True) / 2 + 7.5 # print(rootwhitelength) #cv2.putText(image, "length:{}cm".format(round(rootwhitelength,2)),(x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2) root_white_num += 1 total_rootwhite_length += rootwhitelength elif label == 'lyellow': leaf_yellow_num += 1 #leafyellowarea = 0 '''for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 # p = Polygon(verts, facecolor="none", edgecolor=color) leafyellowarea += math.ceil(area(verts))''' leafyellowarea = np.sum([math.ceil(area(np.fliplr(verts) - 1)) for verts in contours]) #cv2.putText(image,"Area:{}cm2".format(leafyellowarea/3150),(x1,y1-10),cv2.FONT_HERSHEY_SIMPLEX,0.6,color,2) #print(leafyellowarea) total_leafyellow_area += leafyellowarea elif label == 'lgreen': leaf_green_num += 1 #leafgreenarea = 0 '''for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 # p = Polygon(verts, facecolor="none", edgecolor=color) leafgreenarea += math.ceil(area(verts))''' leafgreenarea = np.sum([math.ceil(area(np.fliplr(verts) - 1)) for verts in contours]) #cv2.putText(image,"Area:{}cm2".format(leafgreenarea/3150),(x1,y1-10),cv2.FONT_HERSHEY_SIMPLEX,0.6,color,2) #print(leafgreenarea) total_leafgreen_area += leafgreenarea if leaf_num == 0: total_leaf_area = 0 total_leaf_width = 0 total_leaf_length = 0 avg_leaf_area = 0 avg_leaf_width = 0 avg_leaf_length = 0 elif leaf_num != 0: avg_leaf_area += total_leaf_area/leaf_num avg_leaf_length += total_leaf_length/leaf_num avg_leaf_width += total_leaf_width/leaf_num if root_num == 0: total_root_length = 0 elif root_num != 0: avg_root_length += (total_root_length + total_rootwhite_length + total_rootwhite_length)/root_num if root_green_num == 0: total_rootgreen_length = 0 elif root_green_num != 0: avg_rootgreen_length += total_rootgreen_length/root_green_num if root_white_num == 0: total_rootwhite_length = 0 elif root_white_num != 0: avg_rootwhite_length += total_rootwhite_length/root_white_num if leaf_yellow_num == 0: total_leafyellow_area = 0 elif leaf_yellow_num != 0: avg_leafyellow_area += total_leafyellow_area/leaf_yellow_num if leaf_green_num == 0: total_leafgreen_area = 0 elif leaf_green_num != 0: avg_leafgreen_area += total_leafgreen_area/leaf_green_num cv2.putText(image,'leaf_number:{}'.format(leaf_num),(10,25),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,0,0),2) #cv2.putText(image, 'Avg_leaf_area:{}cm2'.format(round(avg_leaf_area/3150,2)), (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2) #cv2.putText(image, 'Avg_leaf_length:{}cm'.format(round(avg_leaf_length/57.5,2)), (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2) #cv2.putText(image, 'Avg_leaf_width:{}cm'.format(round(avg_leaf_width/57.5, 2)), (10, 25),cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2) #cv2.putText(image, 'Avg_root_length:{}cm'.format(round((total_root_length+total_rootgreen_length+total_rootwhite_length)/root_num/57.5, 2)), (10, 55), cv2.FONT_HERSHEY_SIMPLEX, 0.8,(255, 0, 0), 2) #cv2.putText(image, 'Avg_leafgreen_area:{}cm2'.format(round(avg_leafgreen_area/3150,2)), (10, 55), cv2.FONT_HERSHEY_SIMPLEX, 0.8,(255, 0, 0), 2) #cv2.putText(image, 'Avg_leafyellow_area:{}cm2'.format(round(avg_leafyellow_area/3150,2)), (10, 85),cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2) #cv2.putText(image, 'Avg_rootgreen_length:{}cm'.format(round(avg_rootgreen_length/57.5,2)), (10, 85), cv2.FONT_HERSHEY_SIMPLEX,0.8, (255, 0, 0), 2) #cv2.putText(image,'Avg_rootwhite_length:{}cm'.format(round(avg_rootwhite_length/57.5,2)), (10, 115), cv2.FONT_HERSHEY_SIMPLEX,0.8, (255, 0, 0), 2) cv2.putText(image, 'root_number:{}'.format(root_num), (10,55), cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 0, 0), 2) cv2.putText(image, 'rootgreen_number:{}'.format(root_green_num), (10, 85), cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 0, 0), 2) cv2.putText(image, 'rootwhite_number:{}'.format(root_white_num), (10, 115), cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 0, 0), 2) cv2.putText(image, 'leafgreen_number:{}'.format(leaf_green_num), (10, 145), cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 0, 0), 2) cv2.putText(image, 'leafyellow_number:{}'.format(leaf_yellow_num), (10, 175), cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 0, 0), 2) return image
def convert_segmentation(self, save_path): self.seg_save_path = save_path image_id = 0 box_id = 0 images_dic = dict() image_info = list() annos = list() categories = list() print('=' * 100) print('Reading segm file...') bbox_annos = self.__read_csv(self.openimage_seg_file, 1) print('Counting images...') counted_annos = list() for ba in tqdm(bbox_annos, ncols=WIDTH): # name_key: ImageID name_key = ba[1] cls_id = ba[2] if self.convert_cls_into_coco: if cls_id in COCO_OPENIMAGE_RELATED_CLASSES_DIC_CONVERT: counted_annos.append(ba) if not name_key in images_dic: images_dic.update({name_key: image_id}) image_id += 1 else: counted_annos.append(ba) if not name_key in images_dic: # ImageID <==> image_id images_dic.update({name_key: image_id}) image_id += 1 print('Getting image infos...') name_key_height_width_dic = dict() for name_key in tqdm(images_dic, ncols=WIDTH): im = cv2.imread(os.path.join(self.image_root, self.which_set, name_key + '.jpg')) height, width = im.shape[ :2] if name_key not in name_key_height_width_dic: name_key_height_width_dic[name_key] = (height, width) image = { 'file_name': name_key + '.jpg', 'height': height, 'width': width, 'id': images_dic[name_key] } image_info.append(image) print('Writing annotations...') for ba in tqdm(counted_annos, ncols=WIDTH): mask_key = ba[0] mask_img = cv2.imread(os.path.join(self.segm_image_root, self.which_set, mask_key), 0) name_key = ba[1] height, width = name_key_height_width_dic[name_key] mask_img = cv2.resize(mask_img, (width, height)) mask_img[0,: ] = 0 mask_img[-1,: ] = 0 mask_img[:, 0] = 0 mask_img[:, -1] = 0 fortran_ground_truth_binary_mask = np.asfortranarray(mask_img) encoded_ground_truth = mask.encode(fortran_ground_truth_binary_mask) ground_truth_area = mask.area(encoded_ground_truth) contours = measure.find_contours(mask_img, 0.5) bbox = [ float(ba[4]) * width, float(ba[6]) * height, (float(ba[5]) - float(ba[4])) * width, (float(ba[7]) - float(ba[6])) * height ] LabelName = ba[2] if LabelName in self.cls_id_dic: anno = { 'bbox': bbox, 'area': ground_truth_area.tolist(), 'image_id': images_dic[name_key], 'category_id': self.cls_id_dic[LabelName], 'iscrowd': 0, 'id': int(box_id), 'segmentation': [] } for contour in contours: contour = np.flip(contour, axis=1) segmentation = contour.ravel().tolist() anno["segmentation"].append(segmentation) annos.append(anno) box_id += 1 if self.convert_cls_into_coco: for k, v in COCO_CLASS_NAMES_ID_DIC.items(): category = { 'supercategory': k, 'id': v, 'name': k } categories.append(category) else: for cat in self.cls_dic: category = { 'supercategory': self.cls_dic[cat], 'id': self.cls_id_dic[cat], 'name': self.cls_dic[cat] } categories.append(category) inputfile = { 'info': self.info, 'images': image_info, 'type': 'instances', 'annotations': annos, 'categories': categories } print('Writing into JSON...') with open(save_path, 'w', encoding='utf8') as f: json.dump(inputfile,f) print('=' * 100)
def add_data_to_coco(self, mode, data_path, category_number): if mode =='train': coco_dict = self.train_dict coco_images_path = self.coco_train_path coco_json_path = self.train_json_path elif mode =='val': coco_dict = self.val_dict coco_images_path = self.coco_val_path coco_json_path = self.val_json_path else: raise NotImplementedError images_path = os.path.join(data_path ,'processed', 'images') masks_path = os.path.join(data_path ,'processed', 'image_masks') yaml_path = os.path.join(data_path ,'processed', 'door_lever_3_keypoint.yaml') with open(yaml_path, 'r') as f: dataset_yaml_map = yaml.load(f.read()) id_index = self.get_dataset_number(mode) train_mode = 'Door_ ' +mode for key in dataset_yaml_map.keys(): origin_file_path = os.path.join(images_path, dataset_yaml_map[key]['rgb_image_filename']) target_file_name = train_mode + '_%06d.png ' %id_index target_file_path = os.path.join(coco_images_path, target_file_name) shutil.copyfile(origin_file_path ,target_file_path ) img_dict ={'license': 3, 'file_name': target_file_name, 'coco_url': '', 'height': 480, 'width': 640, 'date_captured': '2013-11-14 11:18:45', 'flickr_url': '', 'id': id_index} x, y = dataset_yaml_map[key]['bbox_top_left_xy'] x2, y2 = dataset_yaml_map[key]['bbox_bottom_right_xy'] w = x2 - x h = y2 - y area = float(w * h) img_number = int(dataset_yaml_map[key]['rgb_image_filename'].split('_')[0]) mask_file_path = os.path.join(masks_path, "%06d_mask.png" % img_number) ground_truth_binary_mask = cv2.imread(mask_file_path, cv2.IMREAD_UNCHANGED) # plt.imshow(ground_truth_binary_mask) # plt.colorbar() fortran_ground_truth_binary_mask = np.asfortranarray(ground_truth_binary_mask) encoded_ground_truth = mask.encode(fortran_ground_truth_binary_mask) ground_truth_area = mask.area(encoded_ground_truth) ground_truth_bounding_box = mask.toBbox(encoded_ground_truth) contours = measure.find_contours(ground_truth_binary_mask, 0.5) annot_dict = {'segmentation': [], 'area': ground_truth_area.tolist(), 'iscrowd': 0, 'image_id': id_index, 'bbox': [x, y, w, h], 'category_id': category_number, 'id': id_index} for contour in contours: contour = np.flip(contour, axis=1) segmentation = contour.ravel().tolist() annot_dict["segmentation"].append(segmentation) coco_dict['images'].append(img_dict) coco_dict['annotations'].append(annot_dict) id_index += 1 with open(coco_json_path, "w") as f: json.dump(coco_dict, f)
def find_contour_around_maximum(data, ji, level, border_j=(5, 5), border_i=(5, 5), max_width=100, max_footprint=None, proj_kwargs={}, periodic=(False, False)): j, i = ji max_val = data[j, i] # increments for increasing bounds of region delta_b = 5 target_con = None grow_down, grow_up, grow_left, grow_right = 4 * (False, ) while target_con is None: footprint_area = sum(border_j) * sum(border_i) if max_footprint and footprint_area > max_footprint: raise ValueError('Footprint exceeded max_footprint') # maybe expand the border if grow_down: border_j = (border_j[0] + delta_b, border_j[1]) if grow_up: border_j = (border_j[0], border_j[1] + delta_b) if grow_left: border_i = (border_i[0] + delta_b, border_i[1]) if grow_right: border_i = (border_i[0], border_i[1] + delta_b) # find the local region (j_rel, i_rel), region_data = get_local_region(data, (j, i), border_j, border_i, periodic=periodic) nj, ni = region_data.shape # extract the contours contours = find_contours(region_data, level) if len(contours) == 0: # no contours found, grow in all directions grow_down, grow_up, grow_left, grow_right = 4 * (True, ) # check each contour for con in contours: is_closed = is_contour_closed(con) is_inside = point_in_contour(con, (j_rel, i_rel)) if is_inside and is_closed: # we found the right contour target_con = con break # check for is_inside doesn't work for non-closed contours grow_down |= (con[0][0] == 0) or (con[-1][0] == 0) grow_up |= (con[0][0] == nj - 1) or (con[-1][0] == nj - 1) grow_left |= (con[0][1] == 0) or (con[-1][1] == 0) grow_right |= (con[0][1] == ni - 1) or (con[-1][1] == ni - 1) # if we got here without growing the region in any direction, # we are probably in a weird situation where there is a closed # contour that does not enclose the maximum if target_con is None and not (grow_down or grow_up or grow_left or grow_right): raise ValueError("Couldn't find a contour") if (np.array(border_i) > max_width).any() or ( np.array(border_j) > max_width).any(): #set a limit on the width of the window raise ValueError("Local region becomes too large.") return target_con, region_data, border_j, border_i
def draw_instances(config, image, depth, boxes, masks, class_ids, parameters, scores=None, title="", figsize=(16, 16), ax=None, draw_mask=False, transform_planes=False, statistics=[], detection_flags={}): """ boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates. masks: [height, width, num_instances] class_ids: [num_instances] class_names: list of class names of the dataset scores: (optional) confidence scores for each box figsize: (optional) the size of the image. """ ## Number of instances N = len(boxes) if not N: pass else: assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0] ## Generate random colors instance_colors = ColorPalette(N).getColorMap(returnTuples=True) if len(detection_flags) and False: for index in range(N): if detection_flags[index] < 0.5: instance_colors[index] = (128, 128, 128) pass continue pass class_colors = ColorPalette(11).getColorMap(returnTuples=True) class_colors[0] = (128, 128, 128) ## Show area outside image boundaries. height, width = image.shape[:2] masked_image = image.astype(np.uint8).copy() normal_image = np.zeros(image.shape) depth_image = depth.copy() for i in range(N): ## Bounding box if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in image cropping. continue y1, x1, y2, x2 = boxes[i] ## Label class_id = class_ids[i] score = scores[i] if scores is not None else None x = random.randint(x1, (x1 + x2) // 2) ## Mask mask = masks[:, :, i] masked_image = apply_mask(masked_image.astype(np.float32), mask, instance_colors[i]).astype(np.uint8) ## Mask Polygon ## Pad to ensure proper polygons for masks that touch image edges. if draw_mask: padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) for verts in contours: ## Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 cv2.polylines(masked_image, np.expand_dims(verts.astype(np.int32), 0), True, color=class_colors[class_id]) continue continue normal_image = drawNormalImage(normal_image) depth_image = drawDepthImage(depth_image) return masked_image.astype(np.uint8), normal_image.astype( np.uint8), depth_image
thresh = threshs[d.argmin()] bin = fdata > thresh labeled, n = ndimage.label(bin) xy = np.zeros((0, 2)) areas = np.zeros((0, 1)) for region in regionprops(labeled): if region.area > 100: xy = np.vstack((xy, region.centroid)) areas = np.vstack((areas, region.area*nmpx**2)) num = xy.shape[0] particles[i] = num if num == 2: c1 = measure.find_contours(labeled == 2, 0)[0] c2 = measure.find_contours(labeled == 1, 0)[0] d = find_shortest_distance(c1,c2) fig = plt.figure() #fig.set_size_inches(1, 1) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.set_cmap('hot') ax.imshow(labeled) plt.savefig(denoisedir+file+"_blobdetect.png") plt.close() if num == 2:
# Menemukan image yang akan diproses dengan 'nama image.format image' img = Image.open("dolphin.jpg") # Menampilkan image img.show() # Membaca image img = imread("dolphin.jpg") # Mengubah RGB menjadi grayscale img_gray = rgb2gray(img) # Fungsi sobel untuk menemukan tepi image img_edges = sobel(img_gray) # Menemukan contour pada image contours = measure.find_contours(img_edges, 0.2) # Menampilkan gambar fig, ax = plt.subplots() ax.imshow(img_edges, interpolation='nearest', cmap=plt.cm.gray) for n, contour in enumerate(contours): ax.plot(contour[:, 1], contour[:, 0], linewidth=2) ax.axis('image') ax.set_xticks([]) ax.set_yticks([]) # Menampilkan hasil image plt.show()
def _sample_contour(self, mask): # indices_y, indices_x = np.where(mask) # npoints = len(indices_y) try: contour = measure.find_contours(mask, 0) contour = np.concatenate(contour) sample_size = self.n_contour except: print( '***\n***\n*** Contour error "find_contours" : {}\n***\n***\n'. format(self.image)) return None def offset_and_clip_contour(contour, offset, img_size): contour = contour + offset contour = np.clip(contour, a_min=0, a_max=img_size - 1) return contour offsets = np.array([ [0, 0], [0, 1], [0, 2], [0, -1], [0, -2], [1, 0], [2, 0], [-1, 0], [-2, 0], [-1, -1], [-2, -2], [1, 1], [2, 2], [-1, 1], [-2, 2], [1, -1], [2, -2], ]) new_contours = [] for offset in offsets: temp_contour = offset_and_clip_contour(contour, offset.reshape(-1, 2), self.img_size) new_contours.append(temp_contour) new_contours = np.concatenate(new_contours) # contour_mask = mask * 0 # new_contours = new_contours.astype(np.int) # contour_mask[new_contours[:,0], new_contours[:,1]] = 1 npoints = len(new_contours) try: sample_indices = np.random.choice(range(npoints), size=sample_size, replace=False) except ValueError: print('***\n***\n*** Contour error: {}\n***\n***\n'.format( self.image)) sample_indices = np.random.choice(range(npoints), size=sample_size, replace=True) # swtich x any y. temp = np.stack( [new_contours[sample_indices, 1], new_contours[sample_indices, 0]], axis=1) temp = temp.copy() return temp
def save_mask_images(image, boxes, masks, class_ids, class_names, scores=None, title="", figsize=(16, 16), ax=None, show_mask=True, show_bbox=True, colors=None, captions=None, is_pb=False): """This function is for saving inference image in test_example_image dir.""" # Number of instances N = boxes.shape[0] if not N: print("\n*** No instances to display *** \n") else: assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0] # If no axis is passed, create one and automatically call show() #auto_show = False #if not ax: # _, ax = plt.subplots(1, figsize=figsize) # auto_show = True # Generate random colors colors = colors or random_colors(N) # Show area outside image boundaries. height, width = image.shape[:2] #ax.set_ylim(height + 10, -10) # ax.set_xlim(-10, width + 10) # ax.axis('off') # ax.set_title(title) masked_image = image.astype(np.uint32).copy() for i in range(N): color = colors[i] # Bounding box if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in image cropping. continue y1, x1, y2, x2 = boxes[i] #if show_bbox: #p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, # alpha=0.7, linestyle="dashed", # edgecolor=color, facecolor='none') #ax.add_patch(p) # Label if not captions: class_id = class_ids[i] score = scores[i] if scores is not None else None label = class_names[class_id] x = random.randint(x1, (x1 + x2) // 2) caption = "{} {:.3f}".format(label, score) if score else label else: caption = captions[i] #ax.text(x1, y1 + 8, caption, #color='w', size=11, backgroundcolor="none") # Mask mask = masks[:, :, i] if show_mask: masked_image = apply_mask(masked_image, mask, color) # Mask Polygon # Pad to ensure proper polygons for masks that touch image edges. padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 p = Polygon(verts, facecolor="none", edgecolor=color) #ax.add_patch(p) #ax.imshow(masked_image.astype(np.uint8)) save_path = os.path.join(ROOT_DIR, "test_examples_images") print("The masked image has been saved.\n") imforsave = masked_image.astype(np.uint8) imsave = Image.fromarray(imforsave) draw = ImageDraw.Draw(imsave) if show_bbox: for i in range(N): draw.rectangle(boxes[i], 'red') if (is_pb): imsave.save('test1pb.png') else: imsave.save('test1.png')
def display_instances_plt(image, boxes, masks, class_ids, class_names, scores=None, title="", figsize=(16, 16), fig=None, ax=None, class_colors=None): """ boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates. masks: [height, width, num_instances] class_ids: [num_instances] class_names: list of class names of the dataset scores: (optional) confidence scores for each box figsize: (optional) the size of the image. """ # Number of instances N = boxes.shape[0] if not N: print("\n*** No instances to display *** \n") else: assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0] if not ax: fig, ax = plt.subplots(1, figsize=figsize) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) # Generate random colors if class_colors is None: colors = random_colors(N) # Show area outside image boundaries. height, width = image.shape[:2] ax.set_ylim(height, 0) ax.set_xlim(0, width) ax.axis('off') ax.set_title(title) masked_image = image.astype(np.uint32).copy() for i in range(N): class_id = class_ids[i] if class_colors is None: color = colors[i] else: color = class_colors[class_id] # Bounding box if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in image cropping. continue y1, x1, y2, x2 = boxes[i] p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, alpha=0.7, linestyle="dashed", edgecolor=color, facecolor='none') ax.add_patch(p) # Label score = scores[i] if scores is not None else None label = class_names[class_id] x = random.randint(x1, (x1 + x2) // 2) caption = "{} {:.3f}".format(label, score) if score else label ax.text(x1, y1 + 8, caption, color='black', size=17, bbox=dict(boxstyle='square,pad=0.2', fc='white', ec='black')) # Mask mask = masks[:, :, i] masked_image = apply_mask(masked_image, mask, color) # Mask Polygon # Pad to ensure proper polygons for masks that touch image edges. padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 p = Polygon(verts, facecolor="none", edgecolor='black', lw=2) ax.add_patch(p) ax.imshow(masked_image.astype(np.uint8)) fig.canvas.draw() width, height = fig.canvas.get_width_height() img = np.fromstring(fig.canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3) plt.close(fig) return img