def predict(self, mask, ref, obs): bad = np.logical_or(~np.isfinite(ref), ~np.isfinite(obs)).any(axis=2) ref[bad] = np.nan obs[bad] = np.nan X = self.generate_features1(ref, obs) good = np.isfinite(X).all(axis=1) X[~good] = 0 yhat1 = self._model1.predict_proba(X).astype(np.float32).reshape( (obs.shape[0], obs.shape[1], -1)) X = self.generate_features2(ref, obs) good = np.isfinite(X).all(axis=1) X[~good] = 0 yhat2 = self._model2.predict_proba(X).astype(np.float32).reshape( (obs.shape[0], obs.shape[1], -1)) yhat = 0.5 * (yhat1 + yhat2) cloud = yhat[:, :, 1] > 0.5 shadow = yhat[:, :, 2] > 0.5 from skimage import morphology cloud = morphology.binary_erosion(cloud, morphology.disk(6)) cloud = morphology.binary_dilation(cloud, morphology.diamond(20)) shadow = morphology.binary_erosion(shadow, morphology.disk(6)) shadow = morphology.binary_dilation(shadow, morphology.diamond(20)) result = np.zeros((obs.shape[0], obs.shape[1]), dtype=np.int8) result[cloud] = 1 result[shadow] = 2 return result
def predict(self, mask, ref, obs): from sklearn import cluster, mixture, linear_model from skimage import morphology F = self.generate_features(ref, obs) self.log(f"Features shape: {F.shape}") good = np.isfinite(F).all(axis=2) good[mask == 0] = False F[~good] = 0 X = F.reshape((-1, F.shape[-1])) model = self._model lbls = model.predict(X).astype(np.int8) lbls = lbls.reshape((obs.shape[0], obs.shape[1])) lbl1 = morphology.binary_closing(lbls == 1, morphology.diamond(3)) lbl2 = morphology.binary_closing(lbls == 2, morphology.diamond(3)) water = morphology.binary_dilation(mask == 5, morphology.diamond(3)) lbls[:, :] = 0 lbls[lbl1] = 1 lbls[lbl2] = 2 lbls[water] = 0 return lbls
def gaussiano(imagen,rgb,intensidad,unsolocolor,roj=None,ver=None,azu=None): if intensidad == True: dureza = 5 else: dureza = 3 if rgb == True: fil = imagen.copy() cont = 0 while cont < 3: fil[:,:,cont] = median(imagen[:,:,cont],diamond(dureza)) cont = cont +1 if unsolocolor == True: orig = imagen.copy() red = imagen[:,:,0] == roj green = imagen[:,:,1] == ver blue = imagen[:,:,2] == azu parte = red == green parte = parte == blue contraparte = ~parte seccion = fil.copy() resto = orig.copy() a = 0 while a < 3: seccion[:,:,a]=seccion[:,:,a]*parte resto[:,:,a]=resto[:,:,a]*contraparte a=a+1 final = resto+seccion else: final = fil else: final = median(imagen,diamond(dureza)) return final
def morp(arr, selema=diamond(8), selemb=diamond(4)): """Apply the morphology transformation over the image array.""" # res = morphology.binary_(arr, selem=selema) # res = morphology.binary_opening(arr, selem=selema) res = morphology.binary_dilation(arr, selem=selemb) res = morphology.binary_closing(res, selem=selema) return res
def postprocessing(prediction, threshold=0.75, dataset='G'): if dataset[0] == 'D': prediction = prediction.numpy() prediction_copy = np.copy(prediction) disc_mask = prediction[1] cup_mask = prediction[0] disc_mask = (disc_mask > 0.5) # return binary mask cup_mask = (cup_mask > 0.1) # return binary mask disc_mask = disc_mask.astype(np.uint8) cup_mask = cup_mask.astype(np.uint8) # _disc_mask = disc_mask.copy() # _cup_mask = cup_mask.copy() for i in range(5): disc_mask = scipy.signal.medfilt2d(disc_mask, 7) cup_mask = scipy.signal.medfilt2d(cup_mask, 7) disc_mask = morphology.binary_erosion( disc_mask, morphology.diamond(7)).astype(np.uint8) cup_mask = morphology.binary_erosion( cup_mask, morphology.diamond(7)).astype(np.uint8) disc_mask = get_largest_fillhole(disc_mask).astype(np.uint8) cup_mask = get_largest_fillhole(cup_mask).astype(np.uint8) prediction_copy[0] = cup_mask prediction_copy[1] = disc_mask # ROI_mask = _cup_mask + _disc_mask ROI_mask = cup_mask + disc_mask ROI_mask[ROI_mask < 1] = 255 ROI_mask[ROI_mask < 2] = 128 ROI_mask[ROI_mask < 3] = 0 return prediction_copy, ROI_mask else: prediction = prediction.numpy() prediction = (prediction > threshold) # return binary mask prediction = prediction.astype(np.uint8) prediction_copy = np.copy(prediction) disc_mask = prediction[1] cup_mask = prediction[0] # _disc_mask = disc_mask.copy() # _cup_mask = cup_mask.copy() for i in range(5): disc_mask = scipy.signal.medfilt2d(disc_mask, 7) cup_mask = scipy.signal.medfilt2d(cup_mask, 7) disc_mask = morphology.binary_erosion( disc_mask, morphology.diamond(7)).astype(np.uint8) cup_mask = morphology.binary_erosion( cup_mask, morphology.diamond(7)).astype(np.uint8) disc_mask = get_largest_fillhole(disc_mask).astype(np.uint8) cup_mask = get_largest_fillhole(cup_mask).astype(np.uint8) prediction_copy[0] = cup_mask prediction_copy[1] = disc_mask # ROI_mask = _cup_mask + _disc_mask ROI_mask = cup_mask + disc_mask ROI_mask[ROI_mask < 1] = 255 ROI_mask[ROI_mask < 2] = 128 ROI_mask[ROI_mask < 3] = 0 return prediction_copy, ROI_mask
def analizirajRegione(putanja, korijenSlike): img = cv2.imread(putanja, cv2.IMREAD_GRAYSCALE) plt.imshow(img, 'gray') plt.show() #img_gray = rgb2gray(img) # height, width = img.shape ret, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) plt.imshow(thresh, 'gray') plt.show() height, width = thresh.shape for x in range(0, height): for y in range(0, width): if thresh[x, y] == 255: thresh[x, y] = 0 else: thresh[x, y] = 255 # img[x, y] = [0, 0, 0] plt.imshow(thresh, 'gray') plt.show() thresh = dilation(thresh, selem=diamond(3)) #plt.imshow(thresh, 'gray') #plt.show() thresh = erosion(thresh, selem=diamond(3)) #plt.imshow(thresh, 'gray') #plt.show() #kernel = np.ones((5,5), np.uint8) # cv2.dilate(thresh, kernel, iterations = 7) # plt.imshow(thresh, 'gray') # plt.show() derp, contours, hierarchy = cv2.findContours(thresh, 1, 2) print(len(contours)) maxArea = 0 x = 0 for i in range(0, len(contours)): cnt = contours[i] M = cv2.moments(cnt) area = cv2.contourArea(cnt) if (area > maxArea): maxArea = area x = i print(maxArea, ' area ', x) cnt = contours[x] duzina = cv2.arcLength(cnt, False) # print(duzina, ' duzina ', i) rect = cv2.minAreaRect(cnt) print(rect, ' rect ', i) print(rect[0][0], ' prvi clan ', i) print(rect[0][1], ' drugi clan ', i) # print (cx) # print (cy) # print (hull) # print (M) line = str(maxArea) + ',' + str(rect[0][0]) + ',' + str( rect[0][1]) + ',' + korijenSlike return line
def imageDilation(data, rad): ans = np.zeros(data.shape, dtype=np.float) if data.ndim >= 3: for i in range(data.shape[2]): channel = data[:, :, i] ans[:, :, i] = morphology.dilation(channel, morphology.diamond(rad)) else: ans[:, :] = morphology.dilation(data, morphology.diamond(rad)) return ans
def segm_watershed(input_image, gradient_level=10, denoised_d_radius=10, rank_d_radius=2, compactness=1): """Función para generar la segmentación mediante la técnica de WaterShed. Args: input_image ([Numpy Array]): Imagen de entrada sobre la que obtener la segmentación. gradient_level (int, optional): Nivel del gradiente para encontrar regiones continuas. Defaults to 10. denoised_d_radius (int, optional): Radio del elemento morfologico 'diamond' para obtener una imagen más suave.Defaults to 10. rank_d_radius (int, optional): Radio del elemento morfológico 'diamond' para expresar la vecindad. Defaults to 2. compactness (int, optional): A mayor valor, se dan lugar cuencas de forma más regular. Defaults to 1. Returns: Tuple (output image, labels, number classes): Tupla con la imagen segmentada, las etiquetas y el número total de segmentos encontrados. """ input_image = rgb2gray(input_image) # denoise image denoised = rank.median(input_image, diamond(denoised_d_radius)) # find continuous region (low gradient - # where less than 10 for this image) --> markers # disk(5) is used here to get a more smooth image markers = rank.gradient(denoised, diamond(rank_d_radius)) < gradient_level markers = ndi.label(markers)[0] # local gradient (disk(2) is used to keep edges thin) gradient = rank.gradient(denoised, diamond(5)) # process the watershed segments_watershed = watershed(gradient, markers, compactness=compactness) output_image = mark_boundaries(input_image, segments_watershed) labeled_ws = color.label2rgb(segments_watershed, input_image, kind='avg', bg_label=0) return (output_image, labeled_ws, len(np.unique(segments_watershed)))
def test_morpho2(self, bigsize=20.0, smallsize=3.0, threshold=5.0): img = self.read_H_image() pref = self.morpho_rec(img, 10) filename = os.path.join(test_out_folder, 'morpho_00_rec_%s.png' % self.image_name) skimage.io.imsave(filename, pref) res = self.difference_of_gaussian(pref, bigsize, smallsize) filename = os.path.join(test_out_folder, 'morpho_01_diff_%s_%i_%i.png' % (self.image_name, int(bigsize), int(smallsize))) skimage.io.imsave(filename, res) #res = self.morpho_rec2(diff, 15) #filename = os.path.join(test_out_folder, 'morpho_02_rec_%s.png' % self.image_name) #skimage.io.imsave(filename, res) res[res>threshold] = 255 filename = os.path.join(test_out_folder, 'morpho_03_res_%s_%i.png' % (self.image_name, threshold)) skimage.io.imsave(filename, res) se = morphology.diamond(3) ero = morphology.erosion(res, se) filename = os.path.join(test_out_folder, 'morpho_03_ero_%s_%i.png' % (self.image_name, threshold)) skimage.io.imsave(filename, ero) res[ero>0] = 0 overlay_img = self.overlay(img, res) filename = os.path.join(test_out_folder, 'morpho_04_overlay_%s_%i.png' % (self.image_name, int(threshold))) skimage.io.imsave(filename, overlay_img) return
def morpho_rec2(self, img, size=10): # internal gradient of the cells: se = morphology.diamond(size) dil = morphology.dilation(img, se) rec = morphology.reconstruction(dil, img, method='erosion').astype(np.dtype('uint8')) return rec
def mask_fl(gf, t): """ Returns the mask around Rapunzel for the given time t """ frame = clip.get_frame(t) diff = (((frame - ref_frame)**2).max(axis=2) > 10**2) cleaned = skm.remove_small_objects(diff, 40) dilated = skm.binary_dilation(cleaned, skm.diamond(2)) return np.minimum(gf(t), 1.0 - dilated)
def test_pad_input(): """Test `match_template` when `pad_input=True`. This test places two full templates (one with values lower than the image mean, the other higher) and two half templates, which are on the edges of the image. The two full templates should score the top (positive and negative) matches and the centers of the half templates should score 2nd. """ # Float prefactors ensure that image range is between 0 and 1 template = 0.5 * diamond(2) image = 0.5 * np.ones((9, 19)) mid = slice(2, 7) image[mid, :3] -= template[:, -3:] # half min template centered at 0 image[mid, 4:9] += template # full max template centered at 6 image[mid, -9:-4] -= template # full min template centered at 12 image[mid, -3:] += template[:, :3] # half max template centered at 18 result = match_template(image, template, pad_input=True, constant_values=image.mean()) # get the max and min results. sorted_result = np.argsort(result.flat) i, j = np.unravel_index(sorted_result[:2], result.shape) assert_equal(j, (12, 0)) i, j = np.unravel_index(sorted_result[-2:], result.shape) assert_equal(j, (18, 6))
def image_filter(img): img2 = img.copy(); img2[img2 < 30] = 100; img2 = exp.smooth_image(img2, sigma = 1.0); #plt.figure(6); plt.clf(); #plt.imshow(img2); # threshold image and take zero smaller components.. th = img2 < 92; th2 = morph.binary_closing(th, morph.diamond(1)) label = meas.label(th2, background=0) #plt.imshow(mask) bs = meas.regionprops(label+1); area = np.array([prop.area for prop in bs]); if len(area) > 0: mask = np.logical_and(label > -1, label != np.argsort(area)[-1]); img2[mask] = 100; img2[:2,:] = 100; img2[-2:,:] = 100; img2[:,:2] = 100; img2[:,-2:] = 100; #plt.figure(6); plt.clf(); #plt.subplot(1,2,1); #plt.imshow(img2, vmin = 84, vmax = 92, cmap = plt.cm.gray) #plt.subplot(1,2,2); #plt.imshow(img2); return img2;
def detect_edges(image_array): """ Detect edges in a given image Takes a numpy.array representing an image, apply filters and edge detection and return a numpy.array Parameters ---------- image_array : ndarray (2D) Image data to be processed. Detect edges on this 2D array representing the image Returns ------- edges : ndarray (2D) Edges of an image. """ #Transform image into grayscale img = rgb2gray(image_array) #Remove some noise from the image img = denoise_tv_chambolle(img, weight=0.55) #Apply canny edges = filter.canny(img, sigma=3.2) #Clear the borders clear_border(edges, 15) #Dilate edges to make them more visible and connected edges = binary_dilation(edges, selem=diamond(3)) return edges
def image_filter(img): img2 = img.copy() img2[img2 < 30] = 100 img2 = exp.smooth_image(img2, sigma=1.0) #plt.figure(6); plt.clf(); #plt.imshow(img2); # threshold image and take zero smaller components.. th = img2 < 92 th2 = morph.binary_closing(th, morph.diamond(1)) label = meas.label(th2, background=0) #plt.imshow(mask) bs = meas.regionprops(label + 1) area = np.array([prop.area for prop in bs]) if len(area) > 0: mask = np.logical_and(label > -1, label != np.argsort(area)[-1]) img2[mask] = 100 img2[:2, :] = 100 img2[-2:, :] = 100 img2[:, :2] = 100 img2[:, -2:] = 100 #plt.figure(6); plt.clf(); #plt.subplot(1,2,1); #plt.imshow(img2, vmin = 84, vmax = 92, cmap = plt.cm.gray) #plt.subplot(1,2,2); #plt.imshow(img2); return img2
def diamondMask(maskImg, diamond_radius): boxsize = maskImg.get_xsize() maskArray = EMNumPy.em2numpy(maskImg) if (boxsize <= (diamond_radius * 2 + 1)): print "ERROR: the width of the square cannot be larger than the boxsize of particles." sys.exit() #from skimage.morphology import diamond #Generates a flat, diamond-shaped structuring element of a given radius. #A pixel is part of the neighborhood (i.e. labeled 1) if the city block/manhattan distance between it and the center of the neighborhood is no greater than radius. diamArray = diamond(diamond_radius, dtype=np.uint8) m, n = diamArray.shape assert m==n if (m%2 == 0): pad_before = (boxsize - m)/2 pad_after = (boxsize - m)/2 else: pad_before = (boxsize - m)/2 pad_after = (boxsize - m)/2+1 diamArrayPad = np.pad(diamArray, (pad_before, pad_after), mode='constant') diamImg = EMNumPy.numpy2em(diamArrayPad) return diamImg
def find_searchblocks(inputimage, blockwidth): ''' perform canny edge detection and binary operations to define searchblocks, i.e. blocks in which to perform blockmatching ''' size_ver, size_hor = inputimage.shape[:2] # is calculated twice... optimize MVs_ver = math.floor(size_ver/blockwidth) # number of MVs in horizontal direction MVs_hor = math.floor(size_hor/blockwidth) blur = cv2.GaussianBlur(inputimage, (7,7), 2) I = np.max(blur) - blur edges = feature.canny(I,sigma = 3, use_quantiles = True, low_threshold = 0.2,high_threshold = 0.7) #https://www.mathworks.com/matlabcentral/answers/458235-why-is-the-canny-edge-detection-in-matlab-different-to-opencv dil = morphology.dilation(edges,selem = morphology.diamond(2)) bw_close = morphology.binary_closing(dil, selem=morphology.disk(3)) bw_fill = binary_fill_holes(bw_close) cleaned = morphology.remove_small_objects(bw_fill, min_size=500, connectivity=0) #out = np.copy(imstack[0]) #img_prev[~cleaned] = 0 # if one component of edge(=cleaned) in searchRegion -> dont't find MV #edges = np.ones((MVs_ver, MVs_hor), dtype=bool) searchblocks = block_reduce(cleaned, block_size=(blockwidth,blockwidth), func=np.any) #downsample detected edge -> if any value in block = True -> calculate optical flow return searchblocks[:MVs_ver,:MVs_hor] #cut off overlapping values
def saturated_pixel_classification(gray_img, baseMask, saturatedMask, dilateSize=0): # add saturated area into basic mask saturatedMask = morphology.binary_dilation(saturatedMask, morphology.diamond(dilateSize)) rel_img = np.zeros_like(gray_img) rel_img[saturatedMask] = MAX_PIXEL_VAL label_img, num = morphology.label(rel_img, connectivity=2, return_num=True) rel_mask = baseMask for i in range(1, num): x = (label_img == i) if np.sum( x ) > 100000: # if the area is too large, do not add it into basic mask continue if not (x & baseMask).any(): continue rel_mask = rel_mask | x return rel_mask
def ExtractCandidates(im_norm,h,radius,nbit): """extract signal candidates applying h_maxima transform INPUTS: im_norm=normalised image, h=h_maxima threshold, radius=structuring element radius, nbit= encoding""" # Normalized top_hat filtering se=disk(radius) im=white_tophat(im_norm,se) #filtering local maxima h_maxima=extrema.h_maxima(im, h,selem=diamond(1)) label_h_max=label(h_maxima,neighbors=4) labels=pd.DataFrame(data={'labels':np.sort(label_h_max[np.where(label_h_max!=0)])}) dup=labels.index[labels.duplicated() == True].tolist() #find duplicates labels (=connected components) #splitting connected regions to get only one local maxima max_mask=np.zeros(im.shape) max_mask[label_h_max!=0]=np.iinfo(nbit).max for i in range (len(dup)): r,c=np.where(label_h_max==labels.loc[dup[i],'labels']) #find coord of points having the same label meanpoint_x=np.mean(c) meanpoint_y=np.mean(r) dist=[distance.euclidean([meanpoint_y,meanpoint_x],[r[j],c[j]]) for j in range(len(r))] ind=dist.index(min(dist)) r,c=np.delete(r,ind),np.delete(c,ind) #delete values at ind position. max_mask[r,c]=0 #set to 0 points != medoid coordinates return max_mask
def morph(img): for i in range(img.shape[0]): morphed = (img[i] * 255).astype(np.int16) morphed = morphology.dilation(morphed, morphology.diamond(2)) morphed = (morphed / 255).astype(np.float32) img[i] = morphed return img
def _get_axial_shifts(ndim=2, include_diagonals=False): r''' Helper function to generate the axial shifts that will be performed on the image to identify bordering pixels/voxels ''' if ndim == 2: if include_diagonals: neighbors = square(3) else: neighbors = diamond(1) neighbors[1, 1] = 0 x, y = np.where(neighbors) x -= 1 y -= 1 return np.vstack((x, y)).T else: if include_diagonals: neighbors = cube(3) else: neighbors = octahedron(1) neighbors[1, 1, 1] = 0 x, y, z = np.where(neighbors) x -= 1 y -= 1 z -= 1 return np.vstack((x, y, z)).T
def get_internal_wsl(self, labelimage): se = morphology.diamond(1) ero = morphology.erosion(labelimage, se) grad = labelimage - ero res = np.zeros(labelimage.shape) res[grad>0] = 255 return res
def get_pos_dst_transform(label_unmodified, img, instance, old_label=None, dt_method="edt"): label = np.where(label_unmodified == instance, 1, 0) # If an old label is available, then sample positive clicks on the difference between the two. if old_label is not None: # The difference should be taken only if there is atleast one object pixel in the difference. label = np.max(0, label - old_label) if np.any( (label - old_label) == 1) else label # Leave a margin around the object boundary img_area = morphology.binary_erosion(label, morphology.diamond(D_MARGIN)) img_area = img_area if len(np.where( img_area == 1)[0]) > 0 else np.copy(label) # Set of ground truth pixels. O = np.where(img_area == 1) # Randomly sample the number of positive clicks and negative clicks to use. num_clicks_pos = 0 if len(O) == 0 else random.sample( list(range(1, Npos + 1)), 1) # num_clicks_pos = random.sample(range(1, Npos + 1), 1) pts = get_sampled_locations(O, img_area, num_clicks_pos) u1 = get_distance_transform(pts, img_area, img=img, dt_method=dt_method) return u1, pts
def draw_dot_tree(frame): """ use a grayscale copy of the frame to draw a quadtree and put a dot at centers of nodes """ tree = trees.tree_dots(grayscale(frame)) selem = morphology.diamond(4, dtype=np.bool) tree = morphology.binary_dilation(tree, selem=selem) return color_mask(frame, np.logical_not(tree))
def inference(img): #if ecDNA is touching chromosome/nuclei, mark that whole #component as that class def merge_comp(img, class_id): I = img if (class_id == 1): mask_id = 2 else: mask_id = 1 temp = I == mask_id I[temp] = 0 O = I s = generate_binary_structure(2, 2) labeled_array, num_features = label(I, structure=s) for i in range(146, num_features): ind = (labeled_array == i) if (np.any(I[ind] == class_id)): O[ind] = class_id img[opening(O, diamond(1)) == class_id] = class_id #reset nuclei and chromosomes in main image img[temp] = mask_id return img #fill holes in connected components def fill_holes(img, class_id): temp = binary_fill_holes(img == class_id) img[temp == 1] = class_id return img #remove ecDNA too small and mark ecDNA that are too large as chromosomes def size_thresh(img): RP = measure.regionprops(measure.label(img == 3)) for region in RP: if (region.area > 125): img[tuple(region.coords.T)] = 2 if (region.area < 15): img[tuple(region.coords.T)] = 0 return img img = fill_holes(fill_holes(fill_holes(img, 1), 2), 3) #fill holes img = size_thresh(img) img[binary_dilation(img == 3, diamond(1)) ^ binary_erosion(img == 3, diamond(1))] = 0 img = merge_comp(merge_comp(img, 1), 2) img[binary_dilation(img == 3, diamond(1))] = 3 return img
def Watershed_Condition_erosion(mask): fine_structure = morphology.diamond(1) coarse_structure = morphology.diamond(3) coarse_structure[3, 0] = 0 coarse_structure[3, 6] = 0 #==========step1 coarse erosion============= seed_mask = condition_erosion(mask, coarse_structure, 200) #==========step2 fine erosion============= seed_mask = condition_erosion(seed_mask, fine_structure, 50) distance = ndi.distance_transform_edt(mask) markers = label(seed_mask) labels = watershed(-distance, markers, mask=mask) labelsrgb = label2rgb(labels, bg_label=0, bg_color=(0.2, 0.5, 0.6)) # markersrgb = label2rgb(markers,bg_label = 0, bg_color=(0.2, 0.5, 0.6)) return labels, labelsrgb
def get_diamond(radius): """ :param radius: Radius of diamond :type radius: int :return: The structuring element where elements of the neighborhood are 1 and 0 otherwise. :rtype: numpy.ndarray """ return diamond(radius)
def get_large_wsl(self, labelimage): se = morphology.diamond(1) dil = morphology.dilation(labelimage, se) ero = morphology.erosion(labelimage, se) grad = dil - ero res = np.zeros(labelimage.shape) res[grad>0] = 255 return res
def get_external_wsl(self, labelimage): #se = morphology.square(3) se = morphology.diamond(1) dil = morphology.dilation(labelimage, se) grad = dil - labelimage res = np.zeros(labelimage.shape) res[grad>0] = 255 return res
def test_padding_reflect(): template = diamond(2) image = np.zeros((10, 10)) image[2:7, :3] = template[:, -3:] result = match_template(image, template, pad_input=True, mode='reflect') assert_equal(np.unravel_index(result.argmax(), result.shape), (4, 0))
def predict(self, mask, ref, pst): from sklearn import semi_supervised from skimage import morphology nodata = np.logical_or( np.isnan(ref).any(axis=2), np.isnan(pst).any(axis=2)) X = self.generate_features(ref, pst) X[nodata] = 0 outliers = np.prod(1 + np.clip(X, 0, None), axis=-1) outliers[~np.isfinite(outliers)] = 0 cloud = np.nanmean(outliers[mask == 2]) water = np.nanmean(outliers[mask == 5]) cutoff = 0.5 * (cloud + water) outliers -= max(1, cutoff) outliers /= min(1, np.nanmax(outliers)) outliers = np.clip(outliers, 0, 1, out=outliers) known = morphology.binary_erosion(outliers, morphology.diamond(6)) unknown = morphology.binary_dilation(outliers, morphology.diamond(20)) focus = morphology.binary_dilation(outliers, morphology.diamond(30)) outliers[:, :] = 0 outliers[unknown] = -1 outliers[known] = 1 y = outliers[focus].reshape((-1, )) X = X[focus].reshape((-1, X.shape[-1])) lblspread = semi_supervised.LabelSpreading(kernel="knn", alpha=0.8, max_iter=100, n_neighbors=20, n_jobs=1) lblspread.fit(X, y) self.log(f"Iters: {lblspread.n_iter_}") outliers[focus] = lblspread.transduction_ outliers = outliers.reshape(mask.shape) outliers[nodata] = 0 return outliers[:, :, np.newaxis]
def morpho_rec2(self, img, size=10): # internal gradient of the cells: se = morphology.diamond(size) dil = morphology.dilation(img, se) rec = morphology.reconstruction(dil, img, method='erosion').astype( np.dtype('uint8')) return rec
def __call__(self, **kwargs): img = io.imread(self.src_file) r_threshold = 90 g_threshold = 90 b_threshold = 90 img[img[:, :, 0] < r_threshold] = 0 img[img[:, :, 1] < g_threshold] = 0 img[img[:, :, 2] < b_threshold] = 0 img = color.rgb2gray(img) img = dilation(img, diamond(1)) img = erosion(img, diamond(1)) img = img.astype(np.float32) io.imsave(self.dest_file, img)
def ProcessImage(im, targetDim = 250, doDenoiseOpening = True): #Resize to specified pixels max edge size scaling = 1. if im.shape[0] > im.shape[1]: if im.shape[0] != targetDim: scaling = float(targetDim) / im.shape[0] im = misc.imresize(im, (targetDim, int(round(im.shape[1] * scaling)))) else: if im.shape[1] != targetDim: scaling = float(targetDim) / im.shape[1] im = misc.imresize(im, (int(round(im.shape[0] * scaling)), targetDim)) #print "scaling", scaling greyim = 0.2126 * im[:,:,0] + 0.7152 * im[:,:,1] + 0.0722 * im[:,:,2] #Highlight number plate imnorm = np.array(greyim, dtype=np.uint8) se = np.ones((3, 30), dtype=np.uint8) opim = morph.opening(imnorm, se) diff = greyim - opim + 128. misc.imsave("diff.png", diff) #Binarize image vals = diff.copy() vals = vals.reshape((vals.size)) meanVal = vals.mean() stdVal = vals.std() threshold = meanVal + stdVal #print "Threshold", threshold binIm = diff > threshold misc.imsave("threshold.png", binIm) #print vals.shape #plt.plot(vals) #plt.show() #Denoise diamond = morph.diamond(2) if doDenoiseOpening: currentIm = morph.binary_opening(binIm, diamond) else: currentIm = binIm denoiseIm2 = morph.binary_closing(currentIm, np.ones((3, 13))) #print "currentIm", currentIm.min(), currentIm.max(), currentIm.mean() #print "denoiseIm2", denoiseIm2.min(), denoiseIm2.max(), currentIm.mean() #misc.imsave("denoised1.png", currentIm * 255) #misc.imsave("denoised2.png", denoiseIm2 * 255) #Number candidate regions #print "Numbering regions" numberedRegions, maxRegionNum = morph.label(denoiseIm2, 4, 0, return_num = True) return numberedRegions, scaling
def create_rois(image, size_thresh, method_thresh, closing, scale_factor): ''' Main entry-point function for generating ROIs automatically. Does thresholding, clever merging of intersecting ROIs and ordering left-right-top-bottom. Parameters: image (np.array): 3-dimensional (2d + RGB) numpy array with pixel data for retrieved jpeg from OMERO size_thresh (num): Minimum size (in full-resolution pixels) for an ROI to be considered an ROI method_thresh (str): Thresholding method. Current options are 'otsu', 'triangle', 'yen' and 'li'. closing (int): radius for the diamond-shaped structuring element used for closing operation. scale_factor (int): scaling that was used to generate the downsampled image. Used to re-scale minimum size threshold. Returns: regions (list): list of pruned, ordered tuples of the form (y1,x1,y2,x2) representing the ROIs to be saved back to OMERO. ''' from skimage.color import rgb2gray from skimage.filters import threshold_otsu, threshold_triangle, threshold_yen, threshold_li from skimage.util import invert from skimage.morphology import diamond, binary_closing from skimage.measure import regionprops, label import numpy as np # we're assuming the image is RGB and dark features on light background im = rgb2gray(image) im = invert(im) # ugly thresholding choice here - I'm assuming the inputs to be well-behaved if method_thresh == 'otsu': im_thresh = im > threshold_otsu(im) elif method_thresh == 'triangle': im_thresh = im > threshold_triangle(im) elif method_thresh == 'yen': im_thresh = im > threshold_yen(im) elif method_thresh == 'li': im_thresh = im > threshold_li(im) # do a bit of closing to already merge regions that are almost touching # how much? up to you, it's an input parameter im_thresh = binary_closing(im_thresh, diamond(closing)) im_lab = label(im_thresh) # get rid of ROIs smaller than required size threshold for i in range(1, im_lab.max() + 1): coords = np.where(im_lab == i) if len(coords[0]) < (size_thresh / (scale_factor**2)): im_lab[coords] = 0 regionproperties = regionprops(im_lab) regions = [] # at least for now we only care about the bounding boxes for ROIs for r in regionproperties: regions.append(r.bbox) regions = prune_regions(regions) regions = order_regions(regions) #return [] return regions
def filter_wsl(self, imbin, ws_labels, imin): # internal gradient of the cells: se = morphology.diamond(1) #ero = morphology.erosion(imbin, se) #grad = imbin - ero # watershed line wsl = self.get_external_wsl(ws_labels) #wsl = self.get_large_wsl(ws_labels) wsl_remove = wsl.copy() # watershed line outside the cells is 0 wsl_remove[imbin==0] = 0 # watershed line on the gradient (border of objects) # is also not considered #wsl_remove[grad>0] = 0 # gradient image pref = 255 * filters.gaussian_filter(imin, 3.0) pref[pref < 0] = 0 pref = pref.astype(np.dtype('uint8')) ero = morphology.erosion(pref, se) dil = morphology.dilation(pref, se) grad = dil - ero grad_filtered = grad if self.settings.debug: out_filename = os.path.join(self.settings.img_debug_folder, '%s09_watershed_regions.png' % self.prefix) skimage.io.imsave(out_filename, ws_labels.astype(np.dtype('uint8'))) out_filename = os.path.join(self.settings.img_debug_folder, '%s09_wsl.png' % self.prefix) skimage.io.imsave(out_filename, wsl.astype(np.dtype('uint8'))) out_filename = os.path.join(self.settings.img_debug_folder, '%s09_wsl_remove.png' % self.prefix) skimage.io.imsave(out_filename, wsl_remove.astype(np.dtype('uint8'))) out_filename = os.path.join(self.settings.img_debug_folder, '%s09_wsl_gradient.png' % self.prefix) skimage.io.imsave(out_filename, grad_filtered.astype(np.dtype('uint8'))) labimage = label(wsl_remove) properties = measure.regionprops(labimage, grad_filtered) mean_intensities = np.array([0.0] + [pr.mean_intensity for pr in properties]) filter_intensities = np.where(mean_intensities < self.settings.postfilter['wsl_mean_intensity'], 255, 0) filter_intensities[0] = 0 wsl_remove = filter_intensities[labimage] #print filter_intensities #print mean_intensities wsl[wsl_remove>0] = 0 if self.settings.debug: out_filename = os.path.join(self.settings.img_debug_folder, '%s09_wsl_remove2.png' % self.prefix) skimage.io.imsave(out_filename, wsl_remove.astype(np.dtype('uint8'))) return wsl
def cast_rays(image, blur, resolution): image = cv2.threshold(image, thresh=128, maxval=255, type=cv2.THRESH_BINARY)[1] image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image = morphology.dilation(image, morphology.diamond(3)) plt.imshow(image) plt.show() start = time.time() ray_array = raycast(image, rays=8, ret_type="array", resolution=resolution, blur=blur) end = time.time() return ray_array
def binarizacion(thresholds, out2, arreq, orig_array): """Binarize the image array to extract the ash object.""" plt.figure() # rso = morp(np.logical_and(out2 < thr, out2>tl)) thresh = thresholds[0] thr = thresh(out2) rso = morp(out2 < thr) rso = np.logical_or(morphology.binary_opening(arreq < 5, diamond(2)), rso) rso = morphology.binary_dilation(rso, diamond(2)) rso = morphology.binary_closing(rso, diamond(7)) v1a = masked_array(arreq, rso) v1b = masked_array(orig_array, np.logical_not(rso)) fig = plt.figure() plt.imshow(v1a, cmap='gray', interpolation='nearest') plt.imshow(v1b, cmap='Reds', interpolation='nearest') plt.title('Pluma Popocatepetl') plt.savefig('Pluma_popo_PRUEBA.png') plt.show() return fig
def overlay(self, img, imbin, contour=False): colim = color.gray2rgb(img) colorvalue = (0, 100, 200) if contour: se = morphology.diamond(2) ero = morphology.erosion(imbin, se) grad = imbin - ero colim[grad > 0] = colorvalue else: colim[imbin > 0] = colorvalue return colim
def overlay(self, img, imbin, contour=False): colim = color.gray2rgb(img) colorvalue = (0, 100, 200) if contour: se = morphology.diamond(2) ero = morphology.erosion(imbin, se) grad = imbin - ero colim[grad > 0] = colorvalue else: colim[imbin>0] = colorvalue return colim
def test_default_footprint(function): footprint = morphology.diamond(radius=1) image = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], np.uint8) im_expected = function(image, footprint) im_test = function(image) assert_array_equal(im_expected, im_test)
def get_spectrum_grayscale_image(img, str_elem_name, str_elem_size): if str_elem_name == 'disk': str_elem = disk(str_elem_size, dtype=np.bool) elif str_elem_name == 'diamond': str_elem = diamond(str_elem_size, dtype=np.bool) # preprocess img = img.copy() img = ImageOps.grayscale(img) img = ImageOps.invert(img) img = np.array(img) # get spectrum spectrum_list = get_spectrum(img, str_elem, grayscale_operation) # postprocessing return spectrum_list
def create_word_mask(roi, threshold=None, rel_height=0.5): if threshold is None: threshold = threshold_otsu(roi) # binarize bw = roi > threshold # remove small objects lbl, _ = ndi.label(bw) sizes = np.bincount(lbl.ravel()) mask_sizes = sizes > 20 mask_sizes[0] = 0 bwc = mask_sizes[lbl] # dilate bwcd = ndi.binary_dilation(bwc, diamond(1)) # morphological reconstruction from the center part # to make sure that the mask contains that every considered object # is in fact anchored there x = bwc.sum(0) x[x < x.max() * 0.1] = 0 nzx = x.nonzero() x_lb = nzx[0].min() x_ub = nzx[0].max() y = bwc.sum(1) y[y < y.max() * rel_height] = 0 nzy = y.nonzero() y_lb = nzy[0].min() y_ub = nzy[0].max() if y_lb == y_ub: y_lb -= 3 y_ub += 3 seed = np.zeros(bwcd.shape, dtype=bool) seed[y_lb:y_ub, x_lb:x_ub] = True seed &= bwcd rec = reconstruction(seed, bwcd) return np.array(rec, dtype=bool)
def test_roi_pixel_values(): images = morphology.diamond(8) # width incompatible with num_rings label_array = np.zeros((256, 256)) # different shapes for the images and labels assert_raises(ValueError, lambda: roi.roi_pixel_values(images, label_array)) # create a label mask center = (8., 8.) inner_radius = 2. width = 1 spacing = 1 edges = roi.ring_edges(inner_radius, width, spacing, num_rings=5) rings = roi.rings(edges, center, images.shape) intensity_data, index = roi.roi_pixel_values(images, rings) assert_array_equal(intensity_data[0], ([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])) assert_array_equal([1, 2, 3, 4, 5], index)
import os import matplotlib.pyplot as plt import skimage.io as io from skimage import filter, color img = io.imread('sheep.png') gray=color.rgb2gray(img) # otsu thresh = filter.threshold_otsu(gray) binary = gray <= thresh # labels binary image import skimage.morphology as mp import skimage.measure as ms binary=mp.binary_closing(binary,mp.diamond(1)) #binary=mp.binary_closing(binary,mp.diamond(1)) labels = ms.label(binary, neighbors=8) contours = ms.find_contours(labels, 0.8) # Display the image and plot all contours found with plt.xkcd(): fig, ax = plt.subplots() ax.imshow(binary, interpolation='nearest', cmap=plt.cm.gray) for n, contour in enumerate(contours): ax.plot(contour[:, 1], contour[:, 0], linewidth=1) ax.annotate('Do you know?\n I\'m a cute sheep.', (0.2, 0.45), textcoords='axes fraction', size=20) ax.axis('image') ax.set_xticks([])
def enhance(self): self.data -= scipy.ndimage.minimum_filter( self.data, footprint=morph.diamond(4))
def process_img(i): fig, ax = plt.subplots() img = io.imread(i, as_grey=True) simg = sobel(img) gauss_img = gaussian(img, sigma=1) contours = measure.find_contours(gauss_img, 0.3) int_contour = [] for n, contour in enumerate(contours): #ax.plot(contour[:, 1], contour[:, 0], linewidth=2) for point in contour: int_contour.append((round(point[0]), round(point[1]))) int_contour = list(set(int_contour)) #print int_contour black_img = img[:] black_img[:] = 0 for point in contour: black_img[point[0]][point[1]] = 1 #plt.imshow(black_img, cmap=plt.cm.gray) #plt.show() black_img = dilation(black_img, diamond(1)) #gauss_img = gaussian(img, sigma=1) #coords = corner_peaks(corner_harris(gauss_img), min_distance=1) coords = corner_peaks(corner_harris(img), min_distance=1) #fig, ax = plt.subplots() ax.imshow(img, interpolation='nearest', cmap=plt.cm.gray) plt.plot(coords[:, 1], coords[:, 0], '.r', markersize=5) #circ=plt.Circle((200,200), radius=10, color='g', fill=False) r = 3 sy, sx = img.shape print sy, sx cfiltered = get_extend_coord(img.shape, sy, sx, coords) #filtrowanie najbardziej wystajacych tmp_perim = simg for c in cfiltered: cy, cx = c print " " print "CY CX: " + str(cy) + " " + str(cx) c_perim = get_circle_perimeter(img.shape, cy, cx, 25) merge = [] tmp_points = [] #lista kandydatow na punkty przecinajace sie z okregiem for j in range(sy): for i in range(sx): #if simg[j][i] * c_perim[j][i] > 0.3: print j, i if black_img[j][i] * c_perim[j][i] > 0.0: #print j, i tmp_points.append((j,i)) #print "po kopiowaniu" iter_points = [] iter_p = [] for a in tmp_points: iter_points.append(a) #print type(iter_points) for i in range(len(tmp_points)): if tmp_points[i] not in iter_points: #print "punkt juz usuniety: " + str(tmp_points[i]) continue #print "iteruje dla: " + str(p) new_point = [tmp_points[i][0], tmp_points[i][1]] count = 1 for j in reversed(range(len(iter_points))): #print j #print tmp_points[i] #print iter_points[j] #print "AAAAAA", iter_points if tmp_points[i] != iter_points[j]: #nie badam dystansu sam do siebie if distance(tmp_points[i], iter_points[j]) <= 3: #if distance < 2 then delete new_point[0] += iter_points[j][0] new_point[1] += iter_points[j][1] count += 1 #print "Do usuniecia: " + str(iter_points[j]) iter_points.remove(iter_points[j]) #j -= 2 else: iter_points.remove(tmp_points[i]) #tmp_points.remove(cmpp) #print "dodaje ", (round(new_point[0]/count), round(new_point[1]/count)) iter_p.append((round(new_point[0]/count), round(new_point[1]/count))) print "Punkty sasiadujace" print len(iter_points) #for p in iter_points: # print p print iter_p[0]#, iter_p[0] print iter_p[1]#, iter_p[1] angle = get_angle(c, iter_p[0], iter_p[1]) print "ANGLE: " + str(angle) ''' iter_points = [] for a in tmp_points: iter_points.append(a) #print type(iter_points) for p in tmp_points: if p not in iter_points: #print "punkt juz usuniety: " + str(p) continue #print "iteruje dla: " + str(p) for cmpp in iter_points: #print p #print cmpp if p != cmpp: #nie badam dystansu sam do siebie if distance(p, cmpp) <= 3: #if distance < 2 then delete #print "Do usuniecia: " + str(cmpp) iter_points.remove(cmpp) print "Punkty sasiadujace" #for p in iter_points: # print p print iter_points[0] print iter_points[1] angle = get_angle(c, iter_points[0], iter_points[1]) print "ANGLE: " + str(angle) ''' #merge = [c_perim == simg] #tmp = simg + c_perim tmp_perim += c_perim plt.imshow(tmp_perim, cmap=plt.get_cmap('gray')) #print y, x #a = plt.axes([0, sy, 0, sx]) #circ=plt.Circle((x,y), radius=3, color='g', fill=False) #plt.gca().add_patch(circ) #plt.axis([0, sx, 0, sy]) #plt.show() #w = np.zeros(size) #rr, cc = circle_perimeter(y, x, r) #w[rr, cc] = 1 #plt.imshow(w, cmap=plt.get_cmap('gray')) #plt.plot(w[:, 1], w[:, 0], '.b', markersize=1) #for j in range(size[0]): # for i in range(size[1]): # if w[j][i] * img[j][i] == 1: # print j, i #tmp = [w*img == 1] #plt.imshow(w, cmap=plt.get_cmap('gray')) #plt.plot(w) #print np.sum(tmp) #circ=plt.Circle((x,y), radius=3, color='g', fill=False) #plt.gca().add_patch(circ) #ax.add_patch(circ) #print circ #plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15) plt.show()
def process_img(i): fig, ax = plt.subplots() img = io.imread(i, as_grey=True) white_count = np.sum(img > 0) simg = sobel(img) gauss_img = gaussian(img, sigma=1) contours = measure.find_contours(gauss_img, 0.3) int_contour = [] for n, contour in enumerate(contours): for point in contour: int_contour.append((round(point[0]), round(point[1]))) int_contour = list(set(int_contour)) black_img = img[:] black_img[:] = 0 for point in int_contour: #contour black_img[point[0]][point[1]] = 1 black_img = dilation(black_img, diamond(1)) coords = corner_peaks(corner_harris(img), min_distance=1) ax.imshow(img, interpolation='nearest', cmap=plt.cm.gray) plt.plot(coords[:, 1], coords[:, 0], '.r', markersize=5) sy, sx = img.shape print sy, sx cfiltered = get_extend_coord(img.shape, sy, sx, coords) #filtrowanie najbardziej wystajacych tmp_perim = simg angles = {} for c in cfiltered: cy, cx = c print " " iter_p = get_mean_coords(black_img, cy, cx, 25) print "Punkty sasiadujace" #print len(iter_points) print iter_p[0] print iter_p[1] try: angle = get_angle(c, iter_p[0], iter_p[1]) print "ANGLE: " + str(angle) except ValueError: print "ANGLE_ERROR" angles[c] = abs(95 - angle) #tmp_perim += c_perim #plt.imshow(tmp_perim, cmap=plt.get_cmap('gray')) #print "Base_vertices:" v0, v1 = get_base_vertices(angles) black_img_line = img[:] black_img_line[:] = 0 for point in int_contour: #nakladanie konturu black_img_line[point[0]][point[1]] = 1 #black_img = dilation(black_img, diamond(1)) remove_lines = probabilistic_hough_line(black_img_line, threshold=10, line_length=15, line_gap=2) max_line_length = 0 black_img_line, max_line_length = filter_contours_lines(v0, v1, remove_lines, black_img_line, 6) #filtruje kontur z linii o poczatkach w okolicach punktow print "MAX_LINE_LENGTH: ", max_line_length print "DIMENSION: ", white_count/max_line_length #cnt = 0 #plt.show() print "HISTOGRAM" tmp_hist = [] tmpR = int(math.ceil(max_line_length/40)) print "R for image is: ", tmpR print type(tmpR) for point in int_contour: #nakladanie konturu if black_img_line[point[0]][point[1]] == 1: #tmp_mean_coords = get_mean_coords(black_img, int(point[0]), int(point[1]), 4) #pobiera srednie wspolrzedne #print tmpR tmp_mean_coords = get_mean_coords(black_img, int(point[0]), int(point[1]), tmpR) #pobiera srednie wspolrzedne if len(tmp_mean_coords) < 2: print "not enough mean cords ", tmp_mean_coords continue try: angle = get_angle(point, tmp_mean_coords[0], tmp_mean_coords[1]) tmp_hist.append(angle) except ValueError: print "ANGLE_ERROR" #result = 0 #print "HIST_ANGLE: " + str(angle) #angles[point] = abs(95 - angle) #plt.hist(gaussian_numbers) hist, bins = np.histogram(tmp_hist, normed = True, bins = 10) hist_dict[i] = hist #plt.plot() #plt.show() #plt.hist() print "KONIEC"
from skimage import filters import matplotlib.pyplot as plt from scipy import ndimage as ndi from skimage import morphology from skimage import feature import os test1 = io.imread("Img09-3.tif", 1) edge_img = io.imread("edges.png",1) testnp = np.asarray(test1) testnp = testnp[0:1024,0:1024] val = filters.threshold_otsu(testnp) mask = testnp < val morphology.binary_opening(mask, morphology.diamond(10)).astype(np.uint8) edges1 = feature.canny(mask) edges2 = feature.canny(mask, sigma = 3) fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3,figsize =(8,3), sharex = True, sharey = True) ax1.imshow(mask, cmap=plt.cm.gray) ax1.axis('off') ax1.set_title('noisy image', fontsize=20) ax2.imshow(edges1, cmap=plt.cm.gray) ax2.axis('off') ax2.set_title('Canny filter, $\sigma=1$', fontsize=20) ax3.imshow(edges2, cmap=plt.cm.gray) ax3.axis('off')
#ax[0].imshow(subtracted1, cmap=plt.cm.gray) #ax[1].imshow(im_phase_1, cmap=plt.cm.gray) import numpy as np from skimage.morphology import erosion,dilation, reconstruction from skimage.morphology import diamond,disk #h= 0.1 seed = np.copy(im_phase_1) seed[1:-1,1:-1] = im_phase_1.min() mask = im_phase_1 filled = reconstruction(seed,mask,method='dilation',selem=diamond(10)) contour = im_phase_1 - filled plt.imshow(contour, cmap=plt.cm.gray) selem0 = disk(1) selem1 = diamond(1) selem2 = diamond(1) dilated2 = dilation(contour, selem0) erosed2 = erosion(dilated2, selem1) dilated3 = dilation(erosed2, selem1) erosed3 = erosion(dilated3, selem2) fig, ax = plt.subplots(1, 4, figsize=(10, 5))
indices_borders = [regions[0, 0], regions[0, l1/2], \ regions[l0 - 1, l1/2]] for index in indices_borders: regions[regions == index] = 0 seg, _, _ = segmentation.relabel_from_one(regions) # Compute neighbors # ------------------------------------------------------ neighbors = [] for lab in range(1, seg.max() + 1): dilation_of_region = morphology.binary_dilation(seg == lab, morphology.diamond(3)) neighbors.append(np.unique(seg[dilation_of_region])) res = measure.regionprops(seg, ['Area', 'Centroid']) areas = np.array([entry['Area'] for entry in res]) centroids = np.array([entry['Centroid'] for entry in res]) # Number of neighbors of each grain # Remove 2 because the list of neighbors contains the index of the grain # and the index of the background number_of_neighbors = np.array([len(el) - 2 for el in neighbors]) # Plot links between neighbors new = np.zeros_like(img)
vals = vals.reshape((vals.size)) meanVal = vals.mean() stdVal = vals.std() threshold = meanVal + stdVal print "Threshold", threshold binIm = diff > threshold misc.imsave("threshold.png", binIm) #print vals.shape #plt.plot(vals) #plt.show() #Denoise diamond = morph.diamond(2) denoiseIm = morph.binary_opening(binIm, diamond) denoiseIm2 = morph.binary_closing(denoiseIm, np.ones((3, 13))) #Number candidate regions print "Numbering regions" numberedRegions, maxRegionNum = morph.label(denoiseIm2, 4, 0, return_num = True) if not os.path.exists("candidates"): os.mkdir("candidates") scores1 = ScoreUsingAspect(numberedRegions, "firstcritera.png") scores1.sort() scores1.reverse() print "Using first criteria", scores1[0]