Python scipy.ndimage.morphology.distance_transform_edt() Examples

The following are 16 code examples of scipy.ndimage.morphology.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.morphology , or try the search function .
Example #1
Source File: utils.py    From mriqc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def spectrum_mask(size):
    """Creates a mask to filter the image of size size"""
    import numpy as np
    from scipy.ndimage.morphology import distance_transform_edt as distance

    ftmask = np.ones(size)

    # Set zeros on corners
    # ftmask[0, 0] = 0
    # ftmask[size[0] - 1, size[1] - 1] = 0
    # ftmask[0, size[1] - 1] = 0
    # ftmask[size[0] - 1, 0] = 0
    ftmask[size[0] // 2, size[1] // 2] = 0

    # Distance transform
    ftmask = distance(ftmask)
    ftmask /= ftmask.max()

    # Keep this just in case we want to switch to the opposite filter
    ftmask *= -1.0
    ftmask += 1.0

    ftmask[ftmask >= 0.4] = 1
    ftmask[ftmask < 1] = 0
    return ftmask 
Example #2
Source File: transforms.py    From elektronn3 with MIT License 6 votes vote down vote up
def edt(self, target: np.ndarray) -> np.ndarray:
        sh = target.shape
        if target.min() == 1:  # If everything is 1, the EDT should be inf for every pixel
            nc = target.ndim if self.vector else 1
            return np.full((nc, *sh), np.inf, dtype=np.float32)

        if self.vector:
            if target.ndim == 2:
                coords = np.mgrid[:sh[0], :sh[1]]
            elif target.ndim == 3:
                coords = np.mgrid[:sh[0], :sh[1], :sh[2]]
            else:
                raise RuntimeError(f'Target shape {sh} not understood.')
            inds = distance_transform_edt(
                target, return_distances=False, return_indices=True
            ).astype(np.float32)
            dist = inds - coords
            # assert np.isclose(np.sqrt(dist[0] ** 2 + dist[1] ** 2), distance_transform_edt(target))
            return dist

        # Else: Regular scalar edt
        dist = distance_transform_edt(target).astype(np.float32)[None]
        return dist 
Example #3
Source File: generate_click.py    From BRS-Interactive_segmentation with MIT License 6 votes vote down vote up
def generate_click(fn_map, fp_map, click_map, net_size, y_meshgrid, x_meshgrid):
    fn_map = np.pad(fn_map, ((1,1),(1,1)), 'constant')
    fndist_map = distance_transform_edt(fn_map)
    fndist_map = fndist_map[1:-1, 1:-1]
    fndist_map = np.multiply(fndist_map, 1-click_map)

    fp_map = np.pad(fp_map, ((1,1),(1,1)), 'constant')
    fpdist_map = distance_transform_edt(fp_map)
    fpdist_map = fpdist_map[1:-1, 1:-1]
    fpdist_map = np.multiply(fpdist_map, 1-click_map)

    if np.max(fndist_map) > np.max(fpdist_map):
        is_pos = 1
        return fndist_map, is_pos
    else:
        is_pos = 0
        return fpdist_map, is_pos 
Example #4
Source File: metrics.py    From deep_pipe with MIT License 5 votes vote down vote up
def surface_distances(y_true, y_pred, voxel_shape=None):
    check_bool(y_pred, y_true)
    check_shapes(y_pred, y_true)

    pred_border = np.logical_xor(y_pred, binary_erosion(y_pred))
    true_border = np.logical_xor(y_true, binary_erosion(y_true))

    dt = distance_transform_edt(~true_border, sampling=voxel_shape)
    return dt[pred_border] 
Example #5
Source File: centerlines.py    From oggm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _make_costgrid(mask, ext, z):
    """Computes a costgrid following Kienholz et al. (2014) Eq. (2)

    Parameters
    ----------
    mask : numpy.array
        The glacier mask.
    ext : numpy.array
        The glacier boundaries' mask.
    z : numpy.array
        The terrain height.

    Returns
    -------
    numpy.array of the costgrid
    """

    dis = np.where(mask, distance_transform_edt(mask), np.NaN)
    z = np.where(mask, z, np.NaN)

    dmax = np.nanmax(dis)
    zmax = np.nanmax(z)
    zmin = np.nanmin(z)
    cost = ((dmax - dis) / dmax * cfg.PARAMS['f1']) ** cfg.PARAMS['a'] + \
           ((z - zmin) / (zmax - zmin) * cfg.PARAMS['f2']) ** cfg.PARAMS['b']

    # This is new: we make the cost to go over boundaries
    # arbitrary high to avoid the lines to jump over adjacent boundaries
    cost[np.where(ext)] = np.nanmax(cost[np.where(ext)]) * 50

    return np.where(mask, cost, np.Inf) 
Example #6
Source File: ops.py    From imgscaper with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def distance(img):
    return distance_transform_edt(img) 
Example #7
Source File: fontdata_preprocess.py    From FET-GAN with MIT License 5 votes vote down vote up
def PreProcess(img_path):
    img = cv2.imread(img_path)
    I = img[:,:,2]
    I2 = bwdist(I <= 100);
    I3 = bwdist(I > 100);

    img[:,:,0] = np.clip(I2,0,255);
    img[:,:,1] = np.clip(I3,0,255);

    return img 
Example #8
Source File: morph.py    From kraken with Apache License 2.0 5 votes vote down vote up
def spread_labels(labels, maxdist=9999999):
    """Spread the given labels to the background"""
    distances, features = morphology.distance_transform_edt(labels == 0,
                                                            return_distances=1,
                                                            return_indices=1)
    indexes = features[0] * labels.shape[1] + features[1]
    spread = labels.ravel()[indexes.ravel()].reshape(*labels.shape)
    spread *= (distances < maxdist)
    return spread 
Example #9
Source File: chan_vese.py    From HistomicsTK with Apache License 2.0 5 votes vote down vote up
def mask_to_sdf(im_mask):
    # convert binary mask to signed distance function

    Phi0 = dtx(1 - im_mask) - dtx(im_mask) + im_mask - 1 / 2
    return Phi0 
Example #10
Source File: preparation.py    From open-solution-mapping-challenge with MIT License 5 votes vote down vote up
def update_distances(dist, mask):
    if dist.sum() == 0:
        distances = distance_transform_edt(1 - mask)
    else:
        distances = np.dstack([dist, distance_transform_edt(1 - mask)])
    return distances 
Example #11
Source File: OfflineAdaptingForwarder.py    From PReMVOS with MIT License 5 votes vote down vote up
def create_bad_labels():
  from scipy.ndimage.morphology import distance_transform_edt
  thresholds = [100, 150, 175, 180, 190, 200, 220, 250]
  l = []
  for threshold in thresholds:
    x = numpy.ones((480, 854))
    dt = distance_transform_edt(x)
    z = numpy.zeros((480, 854))
    z[:] = 255
    negatives = dt > threshold
    z[negatives] = 0
    l.append(numpy.expand_dims(z, axis=2))
  return l 
Example #12
Source File: InteractiveEval.py    From PReMVOS with MIT License 5 votes vote down vote up
def generate_click(self, mask, inst):
    dt = np.where(mask == inst, 1, 0)
    # Set the current click points to 0, so that a reasonable new sample is obtained.
    dt[self.pos_row, self.col_pos] = 0
    dt[self.neg_row, self.neg_col] = 0
    
    #Set the border pixels of the image to 0, so that the click is centred on the required mask.
    dt[[0,dt.shape[0] - 1], : ] = 0
    dt[:, [0, dt.shape[1] - 1]] = 0

    dt = distance_transform_edt(dt)
    row = None
    col = None

    if np.max(dt) > 0:
      # get points that are farthest from the object boundary.
      #farthest_pts = np.where(dt > np.max(dt) / 2.0) 
      farthest_pts = np.where(dt == np.max(dt))
      # sample from the list since there could be more that one such points.
      row, col = random.sample(list(zip(farthest_pts[0], farthest_pts[1])), 1)[0]

      #Calculate distance from the existing clicks, and ignore if it is within d_step distance.
      dt_pts = np.ones_like(dt)
      dt_pts[self.pos_row, self.col_pos] = 0
      dt_pts[self.neg_row, self.neg_col] = 0
      dt_pts = distance_transform_edt(dt_pts)

      if dt_pts[row, col] < self.d_step:
        row = None
        col = None

    return row, col 
Example #13
Source File: image.py    From perception with Apache License 2.0 5 votes vote down vote up
def to_distance_im(self):
        """ Returns the distance-transformed image as a raw float array.

        Returns
        -------
        :obj:`numpy.ndarray`
            HxW float array containing the distance transform of the binary image
        """
        return snm.distance_transform_edt(BINARY_IM_MAX_VAL - self.data) 
Example #14
Source File: dilate_xor.py    From HistomicsTK with Apache License 2.0 4 votes vote down vote up
def dilate_xor(im_label, neigh_width=8):
    """Computes a label mask highlighting a ring-like neighborhood of each
    object or region in a given label mask

    Parameters
    ----------
    im_label : array_like
        A labeled mask image wherein intensity of a pixel is the ID of the
        object it belongs to. Non-zero values are considered to be foreground
        objects.

    neigh_width : float, optional
        The width of the ring-like neighborhood around each object.

    Returns
    -------
    im_neigh_label : array_like
        A labeled mask image highlighting pixels in a ring-like neighborhood of
        width upto `neigh_width` around each object in the given label mask.
        The intensity of each pixel in the ring-like neighborhood is set
        equal to the label of the closest object in the given label mask.
        other pixels (including the ones inside objects) are set to zero.

    """

    # For each background pixel compute the distance to the nearest object and
    # the indices of the nearest object pixel
    im_dist, closest_obj_ind = distance_transform_edt(im_label == 0,
                                                      return_indices=True)
    closest_obj_rind, closest_obj_cind = closest_obj_ind

    # Get indices of background pixels within a given distance from an object
    neigh_rind, neigh_cind = np.where(
        np.logical_and(im_dist > 0, im_dist <= neigh_width)
    )

    # generate labeled neighborhood mask
    im_neigh_label = np.zeros_like(im_label)

    im_neigh_label[neigh_rind, neigh_cind] = im_label[
        closest_obj_rind[neigh_rind, neigh_cind],
        closest_obj_cind[neigh_rind, neigh_cind]]

    return im_neigh_label 
Example #15
Source File: OnlineAdaptingForwarder.py    From PReMVOS with MIT License 4 votes vote down vote up
def _adapt(self, video_idx, frame_idx, last_mask, get_posteriors_fn):
    eroded_mask = grey_erosion(last_mask, size=(self.erosion_size, self.erosion_size, 1))
    dt = distance_transform_edt(numpy.logical_not(eroded_mask))

    adaptation_target = numpy.zeros_like(last_mask)
    adaptation_target[:] = VOID_LABEL

    current_posteriors = get_posteriors_fn()
    positives = current_posteriors[:, :, 1] > self.posterior_positive_threshold
    if self.use_positives:
      adaptation_target[positives] = 1

    threshold = self.distance_negative_threshold
    negatives = dt > threshold
    if self.use_negatives:
      adaptation_target[negatives] = 0

    do_adaptation = eroded_mask.sum() > 0

    if self.debug:
      adaptation_target_visualization = adaptation_target.copy()
      adaptation_target_visualization[adaptation_target == 1] = 128
      if not do_adaptation:
        adaptation_target_visualization[:] = VOID_LABEL
      from scipy.misc import imsave
      folder = self.val_data.video_tag().replace("__", "/")
      imsave("forwarded/" + self.model + "/valid/" + folder + "/adaptation_%05d.png" % frame_idx,
             numpy.squeeze(adaptation_target_visualization))

    self.train_data.set_video_idx(video_idx)

    for idx in range(self.n_adaptation_steps):
      do_step = True
      if idx % self.adaptation_interval == 0:
        if do_adaptation:
          feed_dict = self.train_data.feed_dict_for_video_frame(frame_idx, with_annotations=True)
          feed_dict[self.train_data.get_label_placeholder()] = adaptation_target
          loss_scale = self.adaptation_loss_scale
          adaption_frame_idx = frame_idx
        else:
          print("skipping current frame adaptation, since the target seems to be lost", file=log.v4)
          do_step = False
      else:
        # mix in first frame to avoid drift
        # (do this even if we think the target is lost, since then this can help to find back the target)
        feed_dict = self.train_data.feed_dict_for_video_frame(frame_idx=0, with_annotations=True)
        loss_scale = 1.0
        adaption_frame_idx = 0

      if do_step:
        loss, _, n_imgs = self.trainer.train_step(epoch=idx, feed_dict=feed_dict, loss_scale=loss_scale,
                                                  learning_rate=self.adaptation_learning_rate)
        assert n_imgs == 1
        print("adapting on frame", adaption_frame_idx, "of sequence", video_idx + 1, \
            self.train_data.video_tag(video_idx), "loss:", loss, file=log.v4)
    if do_adaptation:
      return negatives
    else:
      return None 
Example #16
Source File: exclude_labels.py    From gunpowder with MIT License 4 votes vote down vote up
def process(self, batch, request):

        gt = batch.arrays[self.labels]

        # 0 marks included regions (to be used directly with distance transform
        # later)
        include_mask = np.ones(gt.data.shape)

        gt_labels = np.unique(gt.data)
        logger.debug("batch contains GT labels: " + str(gt_labels))
        for label in gt_labels:
            if label in self.exclude:
                logger.debug("excluding label " + str(label))
                gt.data[gt.data==label] = self.background_value
            else:
                include_mask[gt.data==label] = 0

        # if no ignore mask is provided or requested, we are done
        if not self.ignore_mask or not self.ignore_mask in request:
            return

        voxel_size = self.spec[self.labels].voxel_size
        distance_to_include = distance_transform_edt(include_mask, sampling=voxel_size)
        logger.debug("max distance to foreground is " + str(distance_to_include.max()))

        # 1 marks included regions, plus a context area around them
        include_mask = distance_to_include<self.ignore_mask_erode

        # include mask was computed on labels ROI, we need to copy it to
        # the requested ignore_mask ROI
        gt_ignore_roi = request[self.ignore_mask].roi

        intersection = gt.spec.roi.intersect(gt_ignore_roi)
        intersection_in_gt = intersection - gt.spec.roi.get_offset()
        intersection_in_gt_ignore = intersection - gt_ignore_roi.get_offset()

        # to voxel coordinates
        intersection_in_gt //= voxel_size
        intersection_in_gt_ignore //= voxel_size

        gt_ignore = np.zeros((gt_ignore_roi//voxel_size).get_shape(), dtype=np.uint8)
        gt_ignore[intersection_in_gt_ignore.get_bounding_box()] = include_mask[intersection_in_gt.get_bounding_box()]

        spec = self.spec[self.labels].copy()
        spec.roi = gt_ignore_roi
        spec.dtype = np.uint8
        batch.arrays[self.ignore_mask] = Array(gt_ignore, spec)