def test_label_output_typed(): data = cp.ones([5]) for t in types: output = cp.zeros([5], dtype=t) n = ndimage.label(data, output=output) assert_array_almost_equal(output, 1) assert_equal(n, 1)
def apply_hysteresis_threshold(image, low, high): """Apply hysteresis thresholding to ``image``. This algorithm finds regions where ``image`` is greater than ``high`` OR ``image`` is greater than ``low`` *and* that region is connected to a region greater than ``high``. Parameters ---------- image : array, shape (M,[ N, ..., P]) Grayscale input image. low : float, or array of same shape as ``image`` Lower threshold. high : float, or array of same shape as ``image`` Higher threshold. Returns ------- thresholded : array of bool, same shape as ``image`` Array in which ``True`` indicates the locations where ``image`` was above the hysteresis threshold. Examples -------- >>> import cupy as cp >>> image = cp.asarray([1, 2, 3, 2, 1, 2, 1, 3, 2]) >>> apply_hysteresis_threshold(image, 1.5, 2.5).astype(int) array([0, 1, 1, 1, 0, 0, 0, 1, 1]) References ---------- .. [1] J. Canny. A computational approach to edge detection. IEEE Transactions on Pattern Analysis and Machine Intelligence. 1986; vol. 8, pp.679-698. :DOI:`10.1109/TPAMI.1986.4767851` """ low = cp.clip(low, a_min=None, a_max=high) # ensure low always below high mask_low = image > low mask_high = image > high # Connected components of mask_low labels_low, num_labels = ndi.label(mask_low) # Check which connected components contain pixels from mask_high sums = ndi.sum(mask_high, labels_low, cp.arange(num_labels + 1)) connected_to_high = sums > 0 thresholded = connected_to_high[labels_low] return thresholded
def test_label10(): data = cp.asarray([ [0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 1, 0], [0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], ]) struct = ndimage.generate_binary_structure(2, 2) out, n = ndimage.label(data, struct) assert_array_almost_equal( out, [ [0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 1, 0], [0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], ], ) assert_equal(n, 1)
def test_label13(): for type in types: data = cp.asarray( [ [1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1], [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], type, ) out, n = ndimage.label(data) expected = [ [1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1], [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ] assert_array_almost_equal(out, expected) assert_equal(n, 1)
def test_label08(): data = cp.asarray([ [1, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0], ]) out, n = ndimage.label(data) assert_array_almost_equal( out, [ [1, 0, 0, 0, 0, 0], [0, 0, 2, 2, 0, 0], [0, 0, 2, 2, 2, 0], [3, 3, 0, 0, 0, 0], [3, 3, 0, 0, 0, 0], [0, 0, 0, 4, 4, 0], ], ) assert_equal(n, 4)
def test_label07(): data = cp.asarray([ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], ]) out, n = ndimage.label(data) assert_array_almost_equal( out, [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], ], ) assert_equal(n, 0)
def test_label_structuring_elements(): data = cp.asarray( np.loadtxt( os.path.join(os.path.dirname(__file__), "data", "label_inputs.txt"))) strels = cp.asarray( np.loadtxt( os.path.join(os.path.dirname(__file__), "data", "label_strels.txt"))) results = cp.asarray( np.loadtxt( os.path.join(os.path.dirname(__file__), "data", "label_results.txt"))) data = data.reshape((-1, 7, 7)) strels = strels.reshape((-1, 3, 3)) results = results.reshape((-1, 7, 7)) r = 0 for i in range(data.shape[0]): d = data[i, :, :] for j in range(strels.shape[0]): s = strels[j, :, :] assert_array_equal(ndimage.label(d, s)[0], results[r, :, :]) r += 1
def test_label11_inplace(): for type in types: data = cp.asarray( [ [1, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0], ], type, ) n = ndimage.label(data, output=data) expected = [ [1, 0, 0, 0, 0, 0], [0, 0, 2, 2, 0, 0], [0, 0, 2, 2, 2, 0], [3, 3, 0, 0, 0, 0], [3, 3, 0, 0, 0, 0], [0, 0, 0, 4, 4, 0], ] assert_array_almost_equal(data, expected) assert_equal(n, 4)
def canny( image, sigma=1.0, low_threshold=None, high_threshold=None, mask=None, use_quantiles=False, ): """Edge filter an image using the Canny algorithm. Parameters ----------- image : 2D array Grayscale input image to detect edges on; can be of any dtype. sigma : float, optional Standard deviation of the Gaussian filter. low_threshold : float, optional Lower bound for hysteresis thresholding (linking edges). If None, low_threshold is set to 10% of dtype's max. high_threshold : float, optional Upper bound for hysteresis thresholding (linking edges). If None, high_threshold is set to 20% of dtype's max. mask : array, dtype=bool, optional Mask to limit the application of Canny to a certain area. use_quantiles : bool, optional If True then treat low_threshold and high_threshold as quantiles of the edge magnitude image, rather than absolute edge magnitude values. If True then the thresholds must be in the range [0, 1]. Returns ------- output : 2D array (image) The binary edge map. See also -------- skimage.sobel Notes ----- The steps of the algorithm are as follows: * Smooth the image using a Gaussian with ``sigma`` width. * Apply the horizontal and vertical Sobel operators to get the gradients within the image. The edge strength is the norm of the gradient. * Thin potential edges to 1-pixel wide curves. First, find the normal to the edge at each point. This is done by looking at the signs and the relative magnitude of the X-Sobel and Y-Sobel to sort the points into 4 categories: horizontal, vertical, diagonal and antidiagonal. Then look in the normal and reverse directions to see if the values in either of those directions are greater than the point in question. Use interpolation to get a mix of points instead of picking the one that's the closest to the normal. * Perform a hysteresis thresholding: first label all points above the high threshold as edges. Then recursively label any point above the low threshold that is 8-connected to a labeled point as an edge. References ----------- .. [1] Canny, J., A Computational Approach To Edge Detection, IEEE Trans. Pattern Analysis and Machine Intelligence, 8:679-714, 1986 :DOI:`10.1109/TPAMI.1986.4767851` .. [2] William Green's Canny tutorial https://en.wikipedia.org/wiki/Canny_edge_detector Examples -------- >>> import cupy as cp >>> from cupyimg.skimage import feature >>> # Generate noisy image of a square >>> im = cp.zeros((256, 256)) >>> im[64:-64, 64:-64] = 1 >>> im += 0.2 * cp.random.rand(*im.shape) >>> # First trial with the Canny filter, with the default smoothing >>> edges1 = feature.canny(im) >>> # Increase the smoothing for better results >>> edges2 = feature.canny(im, sigma=3) """ # # The steps involved: # # * Smooth using the Gaussian with sigma above. # # * Apply the horizontal and vertical Sobel operators to get the gradients # within the image. The edge strength is the sum of the magnitudes # of the gradients in each direction. # # * Find the normal to the edge at each point using the arctangent of the # ratio of the Y sobel over the X sobel - pragmatically, we can # look at the signs of X and Y and the relative magnitude of X vs Y # to sort the points into 4 categories: horizontal, vertical, # diagonal and antidiagonal. # # * Look in the normal and reverse directions to see if the values # in either of those directions are greater than the point in question. # Use interpolation to get a mix of points instead of picking the one # that's the closest to the normal. # # * Label all points above the high threshold as edges. # * Recursively label any point above the low threshold that is 8-connected # to a labeled point as an edge. # # Regarding masks, any point touching a masked point will have a gradient # that is "infected" by the masked point, so it's enough to erode the # mask by one and then mask the output. We also mask out the border points # because who knows what lies beyond the edge of the image? # check_nD(image, 2) dtype_max = dtype_limits(image, clip_negative=False)[1] if low_threshold is None: low_threshold = 0.1 elif use_quantiles: if not (0.0 <= low_threshold <= 1.0): raise ValueError("Quantile thresholds must be between 0 and 1.") else: low_threshold = low_threshold / dtype_max if high_threshold is None: high_threshold = 0.2 elif use_quantiles: if not (0.0 <= high_threshold <= 1.0): raise ValueError("Quantile thresholds must be between 0 and 1.") else: high_threshold = high_threshold / dtype_max if mask is None: mask = cp.ones(image.shape, dtype=bool) def fsmooth(x): return img_as_float(gaussian(x, sigma, mode="constant")) smoothed = smooth_with_function_and_mask(image, fsmooth, mask) jsobel = ndi.sobel(smoothed, axis=1) isobel = ndi.sobel(smoothed, axis=0) abs_isobel = cp.abs(isobel) abs_jsobel = cp.abs(jsobel) magnitude = cp.hypot(isobel, jsobel) # # Make the eroded mask. Setting the border value to zero will wipe # out the image edges for us. # s = generate_binary_structure(2, 2) eroded_mask = binary_erosion(mask, s, border_value=0) eroded_mask = eroded_mask & (magnitude > 0) # # --------- Find local maxima -------------- # # Assign each point to have a normal of 0-45 degrees, 45-90 degrees, # 90-135 degrees and 135-180 degrees. # local_maxima = cp.zeros(image.shape, bool) # ----- 0 to 45 degrees ------ pts_plus = (isobel >= 0) & (jsobel >= 0) & (abs_isobel >= abs_jsobel) pts_minus = (isobel <= 0) & (jsobel <= 0) & (abs_isobel >= abs_jsobel) pts = pts_plus | pts_minus pts = eroded_mask & pts # Get the magnitudes shifted left to make a matrix of the points to the # right of pts. Similarly, shift left and down to get the points to the # top right of pts. c1 = magnitude[1:, :][pts[:-1, :]] c2 = magnitude[1:, 1:][pts[:-1, :-1]] m = magnitude[pts] w = abs_jsobel[pts] / abs_isobel[pts] c_plus = c2 * w + c1 * (1 - w) <= m c1 = magnitude[:-1, :][pts[1:, :]] c2 = magnitude[:-1, :-1][pts[1:, 1:]] c_minus = c2 * w + c1 * (1 - w) <= m local_maxima[pts] = c_plus & c_minus # ----- 45 to 90 degrees ------ # Mix diagonal and vertical # pts_plus = (isobel >= 0) & (jsobel >= 0) & (abs_isobel <= abs_jsobel) pts_minus = (isobel <= 0) & (jsobel <= 0) & (abs_isobel <= abs_jsobel) pts = pts_plus | pts_minus pts = eroded_mask & pts c1 = magnitude[:, 1:][pts[:, :-1]] c2 = magnitude[1:, 1:][pts[:-1, :-1]] m = magnitude[pts] w = abs_isobel[pts] / abs_jsobel[pts] c_plus = c2 * w + c1 * (1 - w) <= m c1 = magnitude[:, :-1][pts[:, 1:]] c2 = magnitude[:-1, :-1][pts[1:, 1:]] c_minus = c2 * w + c1 * (1 - w) <= m local_maxima[pts] = c_plus & c_minus # ----- 90 to 135 degrees ------ # Mix anti-diagonal and vertical # pts_plus = (isobel <= 0) & (jsobel >= 0) & (abs_isobel <= abs_jsobel) pts_minus = (isobel >= 0) & (jsobel <= 0) & (abs_isobel <= abs_jsobel) pts = pts_plus | pts_minus pts = eroded_mask & pts c1a = magnitude[:, 1:][pts[:, :-1]] c2a = magnitude[:-1, 1:][pts[1:, :-1]] m = magnitude[pts] w = abs_isobel[pts] / abs_jsobel[pts] c_plus = c2a * w + c1a * (1.0 - w) <= m c1 = magnitude[:, :-1][pts[:, 1:]] c2 = magnitude[1:, :-1][pts[:-1, 1:]] c_minus = c2 * w + c1 * (1.0 - w) <= m local_maxima[pts] = c_plus & c_minus # ----- 135 to 180 degrees ------ # Mix anti-diagonal and anti-horizontal # pts_plus = (isobel <= 0) & (jsobel >= 0) & (abs_isobel >= abs_jsobel) pts_minus = (isobel >= 0) & (jsobel <= 0) & (abs_isobel >= abs_jsobel) pts = pts_plus | pts_minus pts = eroded_mask & pts c1 = magnitude[:-1, :][pts[1:, :]] c2 = magnitude[:-1, 1:][pts[1:, :-1]] m = magnitude[pts] w = abs_jsobel[pts] / abs_isobel[pts] c_plus = c2 * w + c1 * (1 - w) <= m c1 = magnitude[1:, :][pts[:-1, :]] c2 = magnitude[1:, :-1][pts[:-1, 1:]] c_minus = c2 * w + c1 * (1 - w) <= m local_maxima[pts] = c_plus & c_minus # # ---- If use_quantiles is set then calculate the thresholds to use # if use_quantiles: high_threshold = cp.percentile(magnitude, 100.0 * high_threshold) low_threshold = cp.percentile(magnitude, 100.0 * low_threshold) # # ---- Create two masks at the two thresholds. # high_mask = local_maxima & (magnitude >= high_threshold) low_mask = local_maxima & (magnitude >= low_threshold) # # Segment the low-mask, then only keep low-segments that have # some high_mask component in them # labels, count = ndi.label(low_mask, structure=cp.ones((3, 3), bool)) if count == 0: return low_mask sums = cp.asarray( ndi.sum(high_mask, labels, cp.arange(count, dtype=cp.int32) + 1), ) sums = cp.atleast_1d(sums) good_label = cp.zeros((count + 1,), bool) good_label[1:] = sums > 0 output_mask = good_label[labels] return output_mask
def _prominent_peaks(image, min_xdistance=1, min_ydistance=1, threshold=None, num_peaks=cp.inf): """Return peaks with non-maximum suppression. Identifies most prominent features separated by certain distances. Non-maximum suppression with different sizes is applied separately in the first and second dimension of the image to identify peaks. Parameters ---------- image : (M, N) ndarray Input image. min_xdistance : int Minimum distance separating features in the x dimension. min_ydistance : int Minimum distance separating features in the y dimension. threshold : float Minimum intensity of peaks. Default is `0.5 * max(image)`. num_peaks : int Maximum number of peaks. When the number of peaks exceeds `num_peaks`, return `num_peaks` coordinates based on peak intensity. Returns ------- intensity, xcoords, ycoords : tuple of array Peak intensity values, x and y indices. """ img = image.copy() rows, cols = img.shape if threshold is None: threshold = 0.5 * cp.max(img) ycoords_size = 2 * min_ydistance + 1 xcoords_size = 2 * min_xdistance + 1 img_max = ndi.maximum_filter1d(img, size=ycoords_size, axis=0, mode="constant", cval=0) img_max = ndi.maximum_filter1d(img_max, size=xcoords_size, axis=1, mode="constant", cval=0) mask = img == img_max img *= mask img_t = img > threshold warnings.warn( "host/device transfer required. TODO: implement measure.label") if False: label_img = cpu_measure.label(cp.asnumpy(img_t)) else: # can use cupyimg.ndimage.label instead. # have to specify structure to match skimage's default connectivity label_img, _ = ndi.label(img_t, structure=cp.ones((3, 3))) # props = measure.regionprops(label_img, img_max) regionprops_on_cpu = False if regionprops_on_cpu: img_max = cp.asnumpy(img_max) label_img = cp.asnumpy(label_img) props = cpu_measure.regionprops(label_img, img_max) else: props = measure.regionprops(label_img, img_max) # Sort the list of peaks by intensity, not left-right, so larger peaks # in Hough space cannot be arbitrarily suppressed by smaller neighbors props = sorted(props, key=lambda x: x.max_intensity)[::-1] coords = cp.asarray([np.round(p.centroid) for p in props], dtype=int) img_peaks = [] ycoords_peaks = [] xcoords_peaks = [] # relative coordinate grid for local neighbourhood suppression ycoords_ext, xcoords_ext = cp.mgrid[-min_ydistance:min_ydistance + 1, -min_xdistance:min_xdistance + 1] for ycoords_idx, xcoords_idx in coords: accum = img_max[ycoords_idx, xcoords_idx] if accum > threshold: # absolute coordinate grid for local neighbourhood suppression ycoords_nh = ycoords_idx + ycoords_ext xcoords_nh = xcoords_idx + xcoords_ext # no reflection for distance neighbourhood ycoords_in = cp.logical_and(ycoords_nh > 0, ycoords_nh < rows) ycoords_nh = ycoords_nh[ycoords_in] xcoords_nh = xcoords_nh[ycoords_in] # reflect xcoords and assume xcoords are continuous, # e.g. for angles: # (..., 88, 89, -90, -89, ..., 89, -90, -89, ...) xcoords_low = xcoords_nh < 0 ycoords_nh[xcoords_low] = rows - ycoords_nh[xcoords_low] xcoords_nh[xcoords_low] += cols xcoords_high = xcoords_nh >= cols ycoords_nh[xcoords_high] = rows - ycoords_nh[xcoords_high] xcoords_nh[xcoords_high] -= cols # suppress neighbourhood img_max[ycoords_nh, xcoords_nh] = 0 # add current feature to peaks img_peaks.append(accum) ycoords_peaks.append(ycoords_idx) xcoords_peaks.append(xcoords_idx) img_peaks = cp.array(img_peaks) ycoords_peaks = cp.array(ycoords_peaks) xcoords_peaks = cp.array(xcoords_peaks) if num_peaks < len(img_peaks): idx_maxsort = cp.argsort(img_peaks)[::-1][:num_peaks] img_peaks = img_peaks[idx_maxsort] ycoords_peaks = ycoords_peaks[idx_maxsort] xcoords_peaks = xcoords_peaks[idx_maxsort] return img_peaks, xcoords_peaks, ycoords_peaks
def remove_small_objects(ar, min_size=64, connectivity=1, in_place=False): """Remove objects smaller than the specified size. Expects ar to be an array with labeled objects, and removes objects smaller than min_size. If `ar` is bool, the image is first labeled. This leads to potentially different behavior for bool and 0-and-1 arrays. Parameters ---------- ar : ndarray (arbitrary shape, int or bool type) The array containing the objects of interest. If the array type is int, the ints must be non-negative. min_size : int, optional (default: 64) The smallest allowable object size. connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1) The connectivity defining the neighborhood of a pixel. Used during labelling if `ar` is bool. in_place : bool, optional (default: False) If ``True``, remove the objects in the input array itself. Otherwise, make a copy. Raises ------ TypeError If the input array is of an invalid type, such as float or string. ValueError If the input array contains negative values. Returns ------- out : ndarray, same shape and type as input `ar` The input array with small connected components removed. Examples -------- >>> import cupy as cp >>> from cupyimg.skimage import morphology >>> a = cp.array([[0, 0, 0, 1, 0], ... [1, 1, 1, 0, 0], ... [1, 1, 1, 0, 1]], bool) >>> b = morphology.remove_small_objects(a, 6) >>> b array([[False, False, False, False, False], [ True, True, True, False, False], [ True, True, True, False, False]]) >>> c = morphology.remove_small_objects(a, 7, connectivity=2) >>> c array([[False, False, False, True, False], [ True, True, True, False, False], [ True, True, True, False, False]]) >>> d = morphology.remove_small_objects(a, 6, in_place=True) >>> d is a True """ # Raising type error if not int or bool _check_dtype_supported(ar) if in_place: out = ar else: out = ar.copy() if min_size == 0: # shortcut for efficiency return out if out.dtype == bool: selem = ndi.generate_binary_structure(ar.ndim, connectivity) ccs = cp.zeros_like(ar, dtype=cp.int32) ndi.label(ar, selem, output=ccs) else: ccs = out try: component_sizes = cp.bincount(ccs.ravel()) except ValueError: raise ValueError("Negative value labels are not supported. Try " "relabeling the input with `scipy.ndimage.label` or " "`skimage.morphology.label`.") if len(component_sizes) == 2 and out.dtype != bool: warn("Only one label was provided to `remove_small_objects`. " "Did you mean to use a boolean array?") too_small = component_sizes < min_size too_small_mask = too_small[ccs] out[too_small_mask] = 0 return out
def test_label03(): data = cp.ones([1]) out, n = ndimage.label(data) assert_array_almost_equal(out, [1]) assert_equal(n, 1)
def test_label02(): data = cp.zeros([]) out, n = ndimage.label(data) assert_array_almost_equal(out, 0) assert_equal(n, 0)
def test_label_default_dtype(): test_array = cp.random.rand(10, 10) label, no_features = ndimage.label(test_array > 0.5) assert_(label.dtype in (cp.int32, cp.int64))
def test_label_output_dtype(): data = cp.ones([5]) for t in types: output, n = ndimage.label(data, output=t) assert_array_almost_equal(output, 1) assert output.dtype == t
def test_label06(): data = cp.asarray([1, 0, 1, 1, 0, 1]) out, n = ndimage.label(data) assert_array_almost_equal(out, [1, 0, 2, 2, 0, 3]) assert_equal(n, 3)