Python scipy.ndimage.distance_transform_edt() Examples
The following are 30
code examples of scipy.ndimage.distance_transform_edt().
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
scipy.ndimage
, or try the search function
.
Example #1
Source File: metrics.py From Brain-Tumor-Segmentation-using-Topological-Loss with BSD 3-Clause "New" or "Revised" License | 6 votes |
def border_distance(ref,seg): """ This functions determines the map of distance from the borders of the segmentation and the reference and the border maps themselves """ neigh=8 border_ref = border_map(ref,neigh) border_seg = border_map(seg,neigh) oppose_ref = 1 - ref oppose_seg = 1 - seg # euclidean distance transform distance_ref = ndimage.distance_transform_edt(oppose_ref) distance_seg = ndimage.distance_transform_edt(oppose_seg) distance_border_seg = border_ref * distance_seg distance_border_ref = border_seg * distance_ref return distance_border_ref, distance_border_seg#, border_ref, border_seg
Example #2
Source File: pmlib.py From sea_ice_drift with GNU General Public License v3.0 | 6 votes |
def get_distance_to_nearest_keypoint(x1, y1, shape): ''' Return full-res matrix with distance to nearest keypoint in pixels Parameters ---------- x1 : 1D vector - X coordinates of keypoints y1 : 1D vector - Y coordinates of keypoints shape : shape of image Returns ------- dist : 2D numpy array - image with distances ''' seed = np.zeros(shape, dtype=bool) seed[np.uint16(y1), np.uint16(x1)] = True dist = nd.distance_transform_edt(~seed, return_distances=True, return_indices=False) return dist
Example #3
Source File: degrade.py From calamari with Apache License 2.0 | 6 votes |
def random_blobs(shape, blobdensity, size, roughness=2.0): from random import randint from builtins import range # python2 compatible h, w = shape numblobs = int(blobdensity * w * h) mask = np.zeros((h, w), 'i') for i in range(numblobs): mask[randint(0, h-1), randint(0, w-1)] = 1 dt = ndi.distance_transform_edt(1-mask) mask = np.array(dt < size, 'f') mask = ndi.gaussian_filter(mask, size/(2*roughness)) mask -= np.amin(mask) mask /= np.amax(mask) noise = np.random.rand(h, w) noise = ndi.gaussian_filter(noise, size/(2*roughness)) noise -= np.amin(noise) noise /= np.amax(noise) return np.array(mask * noise > 0.5, 'f')
Example #4
Source File: test_ndimage.py From Computable with MIT License | 6 votes |
def test_distance_transform_edt01(self): #euclidean distance transform (edt) for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_edt(data, return_indices=True) bf = ndimage.distance_transform_bf(data, 'euclidean') assert_array_almost_equal(bf, out) dt = ft - numpy.indices(ft.shape[1:], dtype=ft.dtype) dt = dt.astype(numpy.float64) numpy.multiply(dt, dt, dt) dt = numpy.add.reduce(dt, axis=0) numpy.sqrt(dt, dt) assert_array_almost_equal(bf, dt)
Example #5
Source File: test_ndimage.py From Computable with MIT License | 6 votes |
def test_distance_transform_edt03(self): for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 2]) out = ndimage.distance_transform_edt(data, sampling=[2, 2]) assert_array_almost_equal(ref, out)
Example #6
Source File: test_ndimage.py From GraphicDesignPatternByPython with MIT License | 6 votes |
def test_distance_transform_edt01(self): # euclidean distance transform (edt) for type_ in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type_) out, ft = ndimage.distance_transform_edt(data, return_indices=True) bf = ndimage.distance_transform_bf(data, 'euclidean') assert_array_almost_equal(bf, out) dt = ft - numpy.indices(ft.shape[1:], dtype=ft.dtype) dt = dt.astype(numpy.float64) numpy.multiply(dt, dt, dt) dt = numpy.add.reduce(dt, axis=0) numpy.sqrt(dt, dt) assert_array_almost_equal(bf, dt)
Example #7
Source File: test_ndimage.py From Computable with MIT License | 6 votes |
def test_distance_transform_edt4(self): for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 1]) out = ndimage.distance_transform_edt(data, sampling=[2, 1]) assert_array_almost_equal(ref, out)
Example #8
Source File: Evaluation_FROC.py From NCRF with Apache License 2.0 | 6 votes |
def computeEvaluationMask(maskDIR, resolution, level): """Computes the evaluation mask. Args: maskDIR: the directory of the ground truth mask resolution: Pixel resolution of the image at level 0 level: The level at which the evaluation mask is made Returns: evaluation_mask """ slide = openslide.open_slide(maskDIR) dims = slide.level_dimensions[level] pixelarray = np.zeros(dims[0]*dims[1], dtype='uint') pixelarray = np.array(slide.read_region((0,0), level, dims)) distance = nd.distance_transform_edt(255 - pixelarray[:,:,0]) Threshold = 75/(resolution * pow(2, level) * 2) # 75µm is the equivalent size of 5 tumor cells binary = distance < Threshold filled_image = nd.morphology.binary_fill_holes(binary) evaluation_mask = measure.label(filled_image, connectivity = 2) return evaluation_mask
Example #9
Source File: labeling.py From pyImSegm with BSD 3-Clause "New" or "Revised" License | 6 votes |
def compute_distance_map(seg, label=1): """ compute distance from label boundaries :param ndarray seg: integer images, typically a segmentation :param int label: selected singe label in segmentation :return ndarray: >>> img = np.zeros((6, 6), dtype=int) >>> img[1:5, 2:] = 1 >>> dist = compute_distance_map(img) >>> np.round(dist, 2) array([[ 2.24, 1.41, 1. , 1. , 1. , 1.41], [ 2. , 1. , 0. , 0. , 0. , 1. ], [ 2. , 1. , 0. , 1. , 1. , 1.41], [ 2. , 1. , 0. , 1. , 1. , 1.41], [ 2. , 1. , 0. , 0. , 0. , 1. ], [ 2.24, 1.41, 1. , 1. , 1. , 1.41]]) """ contour_coord = contour_coords(seg, label) # logger.debug('contour coordinates {}'.format(repr(contourCoord))) contour_map = 1 - binary_image_from_coords(contour_coord, seg.shape) dist = ndimage.distance_transform_edt(contour_map) # logger.debug('distance map \total{}'.format(repr(dist))) return dist
Example #10
Source File: train_LA_Rec_FGDTM_L1PlusL2.py From SegWithDistMap with Apache License 2.0 | 6 votes |
def compute_dtm(img_gt, out_shape): """ compute the distance transform map of foreground in binary mask input: segmentation, shape = (batch_size, x, y, z) output: the foreground Distance Map (SDM) dtm(x) = 0; x in segmentation boundary inf|x-y|; x in segmentation """ fg_dtm = np.zeros(out_shape) for b in range(out_shape[0]): # batch size for c in range(out_shape[1]): posmask = img_gt[b].astype(np.bool) if posmask.any(): posdis = distance(posmask) fg_dtm[b][c] = posdis return fg_dtm
Example #11
Source File: train_LA_MultiHead_FGDTM_L1PlusL2.py From SegWithDistMap with Apache License 2.0 | 6 votes |
def compute_dtm(img_gt, out_shape): """ compute the distance transform map of foreground in binary mask input: segmentation, shape = (batch_size, x, y, z) output: the foreground Distance Map (SDM) dtm(x) = 0; x in segmentation boundary inf|x-y|; x in segmentation """ fg_dtm = np.zeros(out_shape) for b in range(out_shape[0]): # batch size for c in range(out_shape[1]): posmask = img_gt[b].astype(np.bool) if posmask.any(): posdis = distance(posmask) fg_dtm[b][c] = posdis return fg_dtm
Example #12
Source File: train_LA_HD.py From SegWithDistMap with Apache License 2.0 | 6 votes |
def compute_dtm01(img_gt, out_shape): """ compute the normalized distance transform map of foreground in binary mask input: segmentation, shape = (batch_size, x, y, z) output: the foreground Distance Map (SDM) shape=out_shape sdf(x) = 0; x in segmentation boundary inf|x-y|; x in segmentation 0; x out of segmentation normalize sdf to [0, 1] """ normalized_dtm = np.zeros(out_shape) for b in range(out_shape[0]): # batch size # ignore background for c in range(1, out_shape[1]): posmask = img_gt[b].astype(np.bool) if posmask.any(): posdis = distance(posmask) normalized_dtm[b][c] = posdis/np.max(posdis) return normalized_dtm
Example #13
Source File: train_LA_HD.py From SegWithDistMap with Apache License 2.0 | 6 votes |
def hd_loss(seg_soft, gt, seg_dtm, gt_dtm): """ compute huasdorff distance loss for binary segmentation input: seg_soft: softmax results, shape=(b,2,x,y,z) gt: ground truth, shape=(b,x,y,z) seg_dtm: segmentation distance transform map; shape=(b,2,x,y,z) gt_dtm: ground truth distance transform map; shape=(b,2,x,y,z) output: boundary_loss; sclar """ delta_s = (seg_soft[:,1,...] - gt.float()) ** 2 s_dtm = seg_dtm[:,1,...] ** 2 g_dtm = gt_dtm[:,1,...] ** 2 dtm = s_dtm + g_dtm multipled = torch.einsum('bxyz, bxyz->bxyz', delta_s, dtm) hd_loss = multipled.mean() return hd_loss
Example #14
Source File: train_LA_MultiHead_FGDTM_L1.py From SegWithDistMap with Apache License 2.0 | 6 votes |
def compute_dtm(img_gt, out_shape): """ compute the distance transform map of foreground in binary mask input: segmentation, shape = (batch_size, x, y, z) output: the foreground Distance Map (SDM) dtm(x) = 0; x in segmentation boundary inf|x-y|; x in segmentation """ fg_dtm = np.zeros(out_shape) for b in range(out_shape[0]): # batch size for c in range(out_shape[1]): posmask = img_gt[b].astype(np.bool) if posmask.any(): posdis = distance(posmask) fg_dtm[b][c] = posdis return fg_dtm
Example #15
Source File: train_LA_HD.py From SegWithDistMap with Apache License 2.0 | 6 votes |
def compute_dtm(img_gt, out_shape): """ compute the distance transform map of foreground in binary mask input: segmentation, shape = (batch_size, x, y, z) output: the foreground Distance Map (SDM) dtm(x) = 0; x in segmentation boundary inf|x-y|; x in segmentation """ fg_dtm = np.zeros(out_shape) for b in range(out_shape[0]): # batch size for c in range(1, out_shape[1]): posmask = img_gt[b].astype(np.bool) if posmask.any(): posdis = distance(posmask) fg_dtm[b][c] = posdis return fg_dtm
Example #16
Source File: mask_morphology.py From NucleiDetectron with Apache License 2.0 | 6 votes |
def skimage_random_walker_segmentation(mask, kernel=k_3x3, k=1): if mask.dtype != np.bool: mask = mask > 0 distance = ndimage.distance_transform_edt(mask) local_maxi = peak_local_max(distance, indices=False, footprint=kernel, labels=mask) markers = measure.label(local_maxi) markers[~mask] = -1 labels_rw = random_walker(mask, markers) if labels_rw.max() < 2: return [mask.astype(np.uint8)], labels_rw res_masks = [] for idx in range(1, labels_rw.max() + 1): m = labels_rw == idx if m.sum() > 20: res_masks.append(m.astype(np.uint8)) return res_masks, labels_rw
Example #17
Source File: mask_morphology.py From NucleiDetectron with Apache License 2.0 | 6 votes |
def skimage_watershed_segmentation(mask, kernel=k_3x3, k=1): # mask = cv.dilate(mask, kernel, iterations=k) distance = ndimage.distance_transform_edt(mask) local_maxi = peak_local_max(distance, indices=False, footprint=kernel, labels=mask) markers = measure.label(local_maxi) labels_ws = watershed(-distance, markers, mask=mask) if labels_ws.max() < 2: return [mask], labels_ws res_masks = [] for idx in range(1, labels_ws.max() + 1): m = labels_ws == idx if m.sum() > 20: res_masks.append(m.astype(np.uint8)) return res_masks, labels_ws
Example #18
Source File: __funcs__.py From porespy with MIT License | 6 votes |
def ps_ball(radius): r""" Creates spherical ball structuring element for morphological operations Parameters ---------- radius : float or int The desired radius of the structuring element Returns ------- strel : 3D-array A 3D numpy array of the structuring element """ rad = int(np.ceil(radius)) other = np.ones((2 * rad + 1, 2 * rad + 1, 2 * rad + 1), dtype=bool) other[rad, rad, rad] = False ball = spim.distance_transform_edt(other) < radius return ball
Example #19
Source File: __funcs__.py From porespy with MIT License | 6 votes |
def ps_disk(radius): r""" Creates circular disk structuring element for morphological operations Parameters ---------- radius : float or int The desired radius of the structuring element Returns ------- strel : 2D-array A 2D numpy bool array of the structring element """ rad = int(np.ceil(radius)) other = np.ones((2 * rad + 1, 2 * rad + 1), dtype=bool) other[rad, rad] = False disk = spim.distance_transform_edt(other) < radius return disk
Example #20
Source File: Util.py From PReMVOS with MIT License | 6 votes |
def get_image_area_to_sample(img): """ calculate set g_c, which has two properties 1) They represent background pixels 2) They are within a certain distance to the object :param img: Image that represents the object instance """ #TODO: In the paper 'Deep Interactive Object Selection', they calculate g_c first based on the original object instead # of the dilated one. # Dilate the object by d_margin pixels to extend the object boundary img_area = np.copy(img) img_area = morphology.binary_dilation(img_area, morphology.diamond(D_MARGIN)).astype(np.uint8) g_c = np.logical_not(img_area).astype(int) g_c[np.where(distance_transform_edt(g_c) > D)] = 0 return g_c
Example #21
Source File: train_LA_Rec_FGDTM_L1.py From SegWithDistMap with Apache License 2.0 | 6 votes |
def compute_dtm(img_gt, out_shape): """ compute the distance transform map of foreground in binary mask input: segmentation, shape = (batch_size, x, y, z) output: the foreground Distance Map (SDM) dtm(x) = 0; x in segmentation boundary inf|x-y|; x in segmentation """ fg_dtm = np.zeros(out_shape) for b in range(out_shape[0]): # batch size for c in range(out_shape[1]): posmask = img_gt[b].astype(np.bool) if posmask.any(): posdis = distance(posmask) fg_dtm[b][c] = posdis return fg_dtm
Example #22
Source File: train_LA_MultiHead_FGDTM_L2.py From SegWithDistMap with Apache License 2.0 | 6 votes |
def compute_dtm(img_gt, out_shape): """ compute the distance transform map of foreground in binary mask input: segmentation, shape = (batch_size, x, y, z) output: the foreground Distance Map (SDM) dtm(x) = 0; x in segmentation boundary inf|x-y|; x in segmentation """ fg_dtm = np.zeros(out_shape) for b in range(out_shape[0]): # batch size for c in range(out_shape[1]): posmask = img_gt[b].astype(np.bool) if posmask.any(): posdis = distance(posmask) fg_dtm[b][c] = posdis return fg_dtm
Example #23
Source File: train_LITS_HD.py From SegWithDistMap with Apache License 2.0 | 6 votes |
def compute_dtm(img_gt, out_shape): """ compute the distance transform map of foreground in binary mask input: segmentation, shape = (batch_size, x, y, z) output: the foreground Distance Map (SDM) dtm(x) = 0; x in segmentation boundary inf|x-y|; x in segmentation """ fg_dtm = np.zeros(out_shape) for b in range(out_shape[0]): # batch size for c in range(1, out_shape[1]): posmask = img_gt[b].astype(np.bool) if posmask.any(): posdis = distance(posmask) fg_dtm[b][c] = posdis return fg_dtm
Example #24
Source File: train_LITS_HD.py From SegWithDistMap with Apache License 2.0 | 6 votes |
def compute_dtm01(img_gt, out_shape): """ compute the normalized distance transform map of foreground in binary mask input: segmentation, shape = (batch_size, x, y, z) output: the foreground Distance Map (SDM) shape=out_shape sdf(x) = 0; x in segmentation boundary inf|x-y|; x in segmentation 0; x out of segmentation normalize sdf to [0, 1] """ normalized_dtm = np.zeros(out_shape) for b in range(out_shape[0]): # batch size # ignore background for c in range(1, out_shape[1]): posmask = img_gt[b].astype(np.bool) if posmask.any(): posdis = distance(posmask) normalized_dtm[b][c] = posdis/np.max(posdis) return normalized_dtm
Example #25
Source File: train_LA_Rec_FGDTM_L2.py From SegWithDistMap with Apache License 2.0 | 6 votes |
def compute_dtm(img_gt, out_shape): """ compute the distance transform map of foreground in binary mask input: segmentation, shape = (batch_size, x, y, z); out_shape = (batch_size, 1, x, y, z) output: the foreground Distance Map (SDM) dtm(x) = 0; x in segmentation boundary inf|x-y|; x in segmentation """ fg_dtm = np.zeros(out_shape) for b in range(out_shape[0]): # batch size for c in range(out_shape[1]): posmask = img_gt[b].astype(np.bool) if posmask.any(): posdis = distance(posmask) fg_dtm[b][c] = posdis return fg_dtm
Example #26
Source File: train_LA_Rec_SDF_L1PlusL2.py From SegWithDistMap with Apache License 2.0 | 5 votes |
def compute_sdf(img_gt, out_shape): """ compute the signed distance map of binary mask input: segmentation, shape = (batch_size,c, x, y, z) output: the Signed Distance Map (SDM) sdf(x) = 0; x in segmentation boundary -inf|x-y|; x in segmentation +inf|x-y|; x out of segmentation normalize sdf to [-1,1] """ img_gt = img_gt.astype(np.uint8) normalized_sdf = np.zeros(out_shape) for b in range(out_shape[0]): # batch size for c in range(out_shape[1]): posmask = img_gt[b].astype(np.bool) if posmask.any(): negmask = ~posmask posdis = distance(posmask) negdis = distance(negmask) boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8) sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis)) sdf[boundary==1] = 0 normalized_sdf[b][c] = sdf assert np.min(sdf) == -1.0, print(np.min(posdis), np.max(posdis), np.min(negdis), np.max(negdis)) assert np.max(sdf) == 1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis)) return normalized_sdf
Example #27
Source File: rasterlayer.py From Pyspatialml with GNU General Public License v3.0 | 5 votes |
def distance(self, file_path=None, driver="GTiff", nodata=None): """Calculate euclidean grid distances to non-NaN pixels Parameters ---------- file_path : str (optional, default None) Optional path to save calculated Raster object. If not specified then a tempfile is used. driver : str (default 'GTiff') Named of GDAL-supported driver for file export. nodata : any number (optional, default None) Nodata value for new dataset. If not specified then a nodata value is set based on the minimum permissible value of the Raster's data type. Returns ------- pyspatialml.RasterLayer Grid distance raster """ arr = self.read(masked=True) arr = ndimage.distance_transform_edt(1 - arr) dtype = arr.dtype layer = self._write(arr, file_path, driver, dtype, nodata) return layer
Example #28
Source File: train_LA_BD.py From SegWithDistMap with Apache License 2.0 | 5 votes |
def compute_sdf1_1(img_gt, out_shape): """ compute the normalized signed distance map of binary mask input: segmentation, shape = (batch_size, x, y, z) output: the Signed Distance Map (SDM) sdf(x) = 0; x in segmentation boundary -inf|x-y|; x in segmentation +inf|x-y|; x out of segmentation normalize sdf to [-1, 1] """ img_gt = img_gt.astype(np.uint8) normalized_sdf = np.zeros(out_shape) for b in range(out_shape[0]): # batch size # ignore background for c in range(1, out_shape[1]): posmask = img_gt[b] negmask = 1-posmask posdis = distance(posmask) negdis = distance(negmask) boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8) sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis)) sdf[boundary==1] = 0 normalized_sdf[b][c] = sdf assert np.min(sdf) == -1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis)) assert np.max(sdf) == 1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis)) return normalized_sdf
Example #29
Source File: DistanceTransform.py From MOTSFusion with MIT License | 5 votes |
def get_distance_transform(pts, label): dt = np.ones_like(label) if len(pts) > 0: for y, x in pts: dt[y, x] = 0 dt = distance_transform_edt(dt) return dt else: # This is important since we divide it by 255 while normalizing the inputs. return dt * 255
Example #30
Source File: test_ndimage.py From Computable with MIT License | 5 votes |
def test_distance_transform_edt5(self): #Ticket #954 regression test out = ndimage.distance_transform_edt(False) assert_array_almost_equal(out, [0.])