Python skimage.morphology.binary_erosion() Examples
The following are 14
code examples of skimage.morphology.binary_erosion().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
skimage.morphology
, or try the search function
.
Example #1
Source File: custom_mouse_functions.py From napari with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_connected_component_shape(layer, event): cords = np.round(layer.coordinates).astype(int) val = layer.get_value() if val is None: return if val != 0: data = layer.data binary = data == val if 'Shift' in event.modifiers: binary_new = binary_erosion(binary) data[binary] = 0 data[binary_new] = val else: binary_new = binary_dilation(binary) data[binary_new] = val size = np.sum(binary_new) layer.data = data msg = f'clicked at {cords} on blob {val} which is now {size} pixels' else: msg = f'clicked at {cords} on background which is ignored' layer.status = msg print(msg)
Example #2
Source File: preprocessing.py From bird-species-classification with MIT License | 6 votes |
def compute_binary_mask_sprengel(spectrogram, threshold): """ Computes a binary mask for the spectrogram # Arguments spectrogram : a numpy array representation of a spectrogram (2-dim) threshold : a threshold for times larger than the median # Returns binary_mask : the binary mask """ # normalize to [0, 1) norm_spectrogram = normalize(spectrogram) # median clipping binary_image = median_clipping(norm_spectrogram, threshold) # erosion binary_image = morphology.binary_erosion(binary_image, selem=np.ones((4, 4))) # dilation binary_image = morphology.binary_dilation(binary_image, selem=np.ones((4, 4))) # extract mask mask = np.array([np.max(col) for col in binary_image.T]) mask = smooth_mask(mask) return mask
Example #3
Source File: Util.py From PReMVOS with MIT License | 6 votes |
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
Example #4
Source File: postprocess0.py From 2018DSB with MIT License | 6 votes |
def basin(label_mask, wall): h,w = np.shape(label_mask) y, x = np.mgrid[0:h, 0:w] struct = generate_binary_structure(2,2) shifty, shiftx = np.mgrid[0:3, 0:3] shifty = (shifty-1).flatten() shiftx = (shiftx-1).flatten() for i in range(4): obdr = label_mask^binary_dilation(label_mask, struct) ibdr = label_mask^binary_erosion(label_mask, struct) yob, xob = y[obdr], x[obdr] ynb, xnb = yob.reshape(-1,1)+shifty, xob.reshape(-1,1)+shiftx wallnb = np.min(map_coords(wall, (ynb, xnb))*(map_coords(ibdr, (ynb, xnb))==1)+\ 5*(map_coords(ibdr, (ynb, xnb))!=1),1) keep = (wall[yob,xob]>wallnb)&(wallnb<=4) label_mask[yob[keep], xob[keep]]=True if np.sum(keep)==0: break return label_mask
Example #5
Source File: raster_manipulation.py From pyeo with GNU General Public License v3.0 | 5 votes |
def buffer_mask_in_place(mask_path, buffer_size): """Expands a mask in-place, overwriting the previous mask""" log = logging.getLogger(__name__) log.info("Buffering {} with buffer size {}".format(mask_path, buffer_size)) mask = gdal.Open(mask_path, gdal.GA_Update) mask_array = mask.GetVirtualMemArray(eAccess=gdal.GA_Update) cache = morph.binary_erosion(mask_array.squeeze(), selem=morph.disk(buffer_size)) np.copyto(mask_array, cache) mask_array = None mask = None
Example #6
Source File: megafacade.py From facade-segmentation with MIT License | 5 votes |
def _create_facade_mask(self): facade_mask = self.driving_layers.building() > 0.5 facade_mask = binary_erosion(facade_mask, disk(10)) # Sky is noisy # Remove non-wall elements from the facade (we want just the wall) facade_mask[self.window_mask()] = 0 facade_mask[self.facade_layers.door() > 0.5] = 0 facade_mask[self.balcony_mask()] = 0 # facade_mask[self.shop_mask()] = 0 facade_mask[self.pillar_mask()] = 0 facade_mask[self.facade_layers.molding() > 0.5] = 0 return facade_mask
Example #7
Source File: visualizer.py From bird-species-classification with MIT License | 5 votes |
def sprengel_binary_mask_from_wave_file(filepath): fs, x = utils.read_wave_file(filepath) Sxx = sp.wave_to_amplitude_spectrogram(x, fs) Sxx_log = sp.wave_to_log_amplitude_spectrogram(x, fs) # plot spectrogram fig = plt.figure(1) subplot_image(Sxx_log, 411, "Spectrogram") Sxx = pp.normalize(Sxx) binary_image = pp.median_clipping(Sxx, 3.0) subplot_image(binary_image + 0, 412, "Median Clipping") binary_image = morphology.binary_erosion(binary_image, selem=np.ones((4, 4))) subplot_image(binary_image + 0, 413, "Erosion") binary_image = morphology.binary_dilation(binary_image, selem=np.ones((4, 4))) subplot_image(binary_image + 0, 414, "Dilation") mask = np.array([np.max(col) for col in binary_image.T]) mask = morphology.binary_dilation(mask, np.ones(4)) mask = morphology.binary_dilation(mask, np.ones(4)) # plot_vector(mask, "Mask") fig.set_size_inches(10, 12) plt.tight_layout() fig.savefig(utils.get_basename_without_ext(filepath) + "_binary_mask.png", dpi=100)
Example #8
Source File: reduce_to_aseg.py From FastSurfer with Apache License 2.0 | 5 votes |
def create_mask(aseg_data, dnum, enum): from skimage.morphology import binary_dilation, binary_erosion from skimage.measure import label print ("Creating dilated mask ...") # treat lateral orbital frontal and parsorbitalis special to avoid capturing too much of eye nerve lat_orb_front_mask = np.logical_or(aseg_data == 2012, aseg_data == 1012) parsorbitalis_mask = np.logical_or(aseg_data == 2019, aseg_data == 1019) frontal_mask = np.logical_or(lat_orb_front_mask, parsorbitalis_mask) print("Frontal region special treatment: ", format(np.sum(frontal_mask))) # reduce to binary datab = (aseg_data > 0) datab[frontal_mask] = 0 # dilate and erode for x in range(dnum): datab = binary_dilation(datab, np.ones((3, 3, 3))) for x in range(enum): datab = binary_erosion(datab, np.ones((3, 3, 3))) # extract largest component labels = label(datab) assert (labels.max() != 0) # assume at least 1 real connected component print(" Found {} connected component(s)!".format(labels.max())) if labels.max() > 1: print(" Selecting largest component!") datab = (labels == np.argmax(np.bincount(labels.flat)[1:]) + 1) # add frontal regions back to mask datab[frontal_mask] = 1 # set mask aseg_data[~datab] = 0 aseg_data[datab] = 1 return aseg_data
Example #9
Source File: preparation.py From open-solution-mapping-challenge with MIT License | 5 votes |
def get_simple_eroded_mask(mask, selem_size, small_annotations_size): if mask.sum() > small_annotations_size**2: selem = rectangle(selem_size, selem_size) mask_eroded = binary_erosion(mask, selem=selem) else: mask_eroded = mask return mask_eroded
Example #10
Source File: preparation.py From open-solution-mapping-challenge with MIT License | 5 votes |
def get_simple_eroded_dilated_mask(mask, erode_selem_size, dilate_selem_size, small_annotations_size): if mask.sum() > small_annotations_size**2: selem = rectangle(erode_selem_size, erode_selem_size) mask_ = binary_erosion(mask, selem=selem) else: selem = rectangle(dilate_selem_size, dilate_selem_size) mask_ = binary_dilation(mask, selem=selem) return mask_
Example #11
Source File: Utils.py From BEAL with MIT License | 5 votes |
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) 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) # return 0,1 cup_mask = morphology.binary_erosion(cup_mask, morphology.diamond(7)).astype(np.uint8) # return 0,1 disc_mask = get_largest_fillhole(disc_mask).astype(np.uint8) # return 0,1 cup_mask = get_largest_fillhole(cup_mask).astype(np.uint8) prediction_copy[0] = cup_mask prediction_copy[1] = disc_mask return prediction_copy 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] 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) # return 0,1 cup_mask = morphology.binary_erosion(cup_mask, morphology.diamond(7)).astype(np.uint8) # return 0,1 disc_mask = get_largest_fillhole(disc_mask).astype(np.uint8) # return 0,1 cup_mask = get_largest_fillhole(cup_mask).astype(np.uint8) prediction_copy[0] = cup_mask prediction_copy[1] = disc_mask return prediction_copy
Example #12
Source File: helpers.py From kaggle_ndsb2017 with MIT License | 5 votes |
def get_segmented_lungs(im, plot=False): # Step 1: Convert into a binary image. binary = im < -400 # Step 2: Remove the blobs connected to the border of the image. cleared = clear_border(binary) # Step 3: Label the image. label_image = label(cleared) # Step 4: Keep the labels with 2 largest areas. areas = [r.area for r in regionprops(label_image)] areas.sort() if len(areas) > 2: for region in regionprops(label_image): if region.area < areas[-2]: for coordinates in region.coords: label_image[coordinates[0], coordinates[1]] = 0 binary = label_image > 0 # Step 5: Erosion operation with a disk of radius 2. This operation is seperate the lung nodules attached to the blood vessels. selem = disk(2) binary = binary_erosion(binary, selem) # Step 6: Closure operation with a disk of radius 10. This operation is to keep nodules attached to the lung wall. selem = disk(10) # CHANGE BACK TO 10 binary = binary_closing(binary, selem) # Step 7: Fill in the small holes inside the binary mask of lungs. edges = roberts(binary) binary = ndi.binary_fill_holes(edges) # Step 8: Superimpose the binary mask on the input image. get_high_vals = binary == 0 im[get_high_vals] = -2000 return im, binary
Example #13
Source File: candidates.py From luna16 with BSD 2-Clause "Simplified" License | 4 votes |
def unet_candidates(): cands = glob.glob("../data/predictions_epoch9_23_all/*.png") #df = pd.DataFrame(columns=['seriesuid','coordX','coordY','coordZ','class']) data = [] imname = "" origin = [] spacing = [] nrimages = 0 for name in tqdm(cands): #image = imread(name) image_t = imread(name) image_t = image_t.transpose() #Thresholding image_t[image_t<THRESHOLD] = 0 image_t[image_t>0] = 1 #erosion selem = morphology.disk(1) image_eroded = image_t image_eroded = morphology.binary_erosion(image_t,selem=selem) label_im, nb_labels = ndimage.label(image_eroded) imname3 = os.path.split(name)[1].replace('.png','') splitted = imname3.split("slice") slice = splitted[1] imname2 = splitted[0][:-1] centers = [] for i in xrange(1,nb_labels+1): blob_i = np.where(label_im==i,1,0) mass = center_of_mass(blob_i) centers.append([mass[1],mass[0]]) if imname2 != imname: if os.path.isfile("../data/1_1_1mm_512_x_512_annotation_masks/spacings/{0}.pickle".format(imname2)): with open("../data/1_1_1mm_512_x_512_annotation_masks/spacings/{0}.pickle".format(imname2), 'rb') as handle: dic = pickle.load(handle) origin = dic["origin"] spacing = dic["spacing"] imname = imname2 nrimages +=1 for center in centers: coords = voxel_2_world([int(slice),center[1]+(512-324)*0.5,center[0]+(512-324)*0.5],origin,spacing) data.append([imname2,coords[2],coords[1],coords[0],'?']) #if nrimages == 5: # break df = pd.DataFrame(data,columns=CANDIDATES_COLUMNS) save_candidates("../data/candidates_unet_final_23.csv",df)
Example #14
Source File: postprocess0.py From 2018DSB with MIT License | 1 votes |
def postprocess(preds, config): assert preds.shape[2]==5 ldelta = delta(preds[:,:,1:]) #ldelta = delta0(preds[:,:,5:]) connected = np.all(ldelta>config.GRADIENT_THRES, 2) base = connected * (preds[:,:,0]>config.MASK_THRES) wall = np.sum(np.abs(preds[:,:,1:]),axis = -1) base_label = label(base) vals, counts = np.unique(base_label[base_label>0], return_counts=True) for val in vals[(counts<config.CLIP_AREA_LOW)]: base_label[base_label==val]=0 vals = vals[(counts>=config.CLIP_AREA_LOW)] for val in vals: label_mask = base_label == val if np.sum(label_mask)==0: continue label_mask = remove_small_holes(label_mask) label_mask = basin(label_mask, wall) label_mask = remove_small_holes(label_mask) ''' label_bdr = label_mask^binary_erosion(label_mask) min_wall = np.min(wall[label_mask]) ave_bdr_wall = np.mean(wall[label_bdr]) if ave_bdr_wall < min_wall + config.WALL_DEPTH: label_mask = 0 ''' base_label[label_mask] = val vals, counts = np.unique(base_label[base_label>0], return_counts=True) for val in vals[(counts<config.CLIP_AREA_LOW)]: base_label[base_label==val]=0 return base_label