Python scipy.ndimage.find_objects() Examples

The following are 30 code examples of scipy.ndimage.find_objects(). 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: parse_image_segments.py    From geosolver with Apache License 2.0 6 votes vote down vote up
def _get_image_segments(image, kernel, block_size, c):
    binarized_image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                            cv2.THRESH_BINARY_INV, block_size, c)

    labeled, nr_objects = ndimage.label(binarized_image, structure=kernel)
    slices = ndimage.find_objects(labeled)

    image_segments = {}
    for idx, slice_ in enumerate(slices):
        offset = instantiators['point'](slice_[1].start, slice_[0].start)
        sliced_image = image[slice_]
        boolean_array = labeled[slice_] == (idx+1)
        segmented_image = 255- (255-sliced_image) * boolean_array
        pixels = set(instantiators['point'](x, y) for x, y in np.transpose(np.nonzero(np.transpose(boolean_array))))
        binarized_segmented_image = cv2.adaptiveThreshold(segmented_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                                          cv2.THRESH_BINARY_INV, block_size, c)

        image_segment = ImageSegment(segmented_image, sliced_image, binarized_segmented_image, pixels, offset, idx)
        image_segments[idx] = image_segment

    return image_segments 
Example #2
Source File: iterators.py    From kaggle-right-whale with MIT License 6 votes vote down vote up
def get_transformed_bbox(bbox, image_width, image_height, **kwargs):
    l, t, w, h = bbox
    r = l + w
    b = t + h
    y_heatmap = np.zeros((image_height, image_width)).astype(bool)
    y_heatmap[t:b, l:r] = True

    y_heatmap = im_affine_transform(y_heatmap[np.newaxis, ...], **kwargs)
    y_heatmap = y_heatmap[0].astype(bool)

    dets = find_objects(y_heatmap)

    if len(dets) == 1:
        t = dets[0][0].start
        b = dets[0][0].stop
        l = dets[0][1].start
        r = dets[0][1].stop
        w = r - l
        h = b - t
    else:
        l, t, w, h = 0, 0, 0, 0

    return l, t, w, h 
Example #3
Source File: tightcrop.py    From LaSO with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def find_paws(data, smooth_radius = 5, threshold = 0.0001):
    # http://stackoverflow.com/questions/4087919/how-can-i-improve-my-paw-detection
    """Detects and isolates contiguous regions in the input array"""
    # Blur the input data a bit so the paws have a continous footprint
    data = ndimage.uniform_filter(data, smooth_radius)
    # Threshold the blurred data (this needs to be a bit > 0 due to the blur)
    thresh = data > threshold
    # Fill any interior holes in the paws to get cleaner regions...
    filled = ndimage.morphology.binary_fill_holes(thresh)
    # Label each contiguous paw
    coded_paws, num_paws = ndimage.label(filled)
    # Isolate the extent of each paw
    # find_objects returns a list of 2-tuples: (slice(...), slice(...))
    # which represents a rectangular box around the object
    data_slices = ndimage.find_objects(coded_paws)
    return data_slices 
Example #4
Source File: dem_processing.py    From pydem with Apache License 2.0 6 votes vote down vote up
def _find_flats_edges(self, data, mag, direction):
        """
        Extend flats 1 square downstream
        Flats on the downstream side of the flat might find a valid angle,
        but that doesn't mean that it's a correct angle. We have to find
        these and then set them equal to a flat
        """

        i12 = np.arange(data.size).reshape(data.shape)

        flat = mag == FLAT_ID_INT
        flats, n = spndi.label(flat, structure=FLATS_KERNEL3)
        objs = spndi.find_objects(flats)

        f = flat.ravel()
        d = data.ravel()
        for i, _obj in enumerate(objs):
            region = flats[_obj] == i+1
            I = i12[_obj][region]
            J = get_adjacent_index(I, data.shape, data.size)
            f[J] = d[J] == d[I[0]]

        flat = f.reshape(data.shape)
        return flat 
Example #5
Source File: test_measurements.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_find_objects04():
    data = np.zeros([1], dtype=int)
    out = ndimage.find_objects(data)
    assert_equal(out, []) 
Example #6
Source File: __funcs__.py    From porespy with MIT License 5 votes vote down vote up
def extract_regions(regions, labels: list, trim=True):
    r"""
    Combine given regions into a single boolean mask

    Parameters
    -----------
    regions : ND-array
        An image containing an arbitrary number of labeled regions
    labels : array_like or scalar
        A list of labels indicating which region or regions to extract
    trim : bool
        If ``True`` then image shape will trimmed to a bounding box around the
        given regions.

    Returns
    -------
    im : ND-array
        A boolean mask with ``True`` values indicating where the given labels
        exist

    """
    if type(labels) is int:
        labels = [labels]
    s = spim.find_objects(regions)
    im_new = np.zeros_like(regions)
    x_min, y_min, z_min = np.inf, np.inf, np.inf
    x_max, y_max, z_max = 0, 0, 0
    for i in labels:
        im_new[s[i-1]] = regions[s[i-1]] == i
        x_min, x_max = min(s[i-1][0].start, x_min), max(s[i-1][0].stop, x_max)
        y_min, y_max = min(s[i-1][1].start, y_min), max(s[i-1][1].stop, y_max)
        if regions.ndim == 3:
            z_min, z_max = min(s[i-1][2].start, z_min), max(s[i-1][2].stop, z_max)
    if trim:
        if regions.ndim == 3:
            bbox = bbox_to_slices([x_min, y_min, z_min, x_max, y_max, z_max])
        else:
            bbox = bbox_to_slices([x_min, y_min, x_max, y_max])
        im_new = im_new[bbox]
    return im_new 
Example #7
Source File: scoring_utils.py    From RoboND-DeepLearning-Project with MIT License 5 votes vote down vote up
def get_centroid_largest_blob(seg_mask):
    labeled_blobs = ndi.label(seg_mask)
    objs = ndi.find_objects(labeled_blobs[0])
    largest_obj = find_largest_obj(seg_mask, objs)
    return np.array(get_centroid(seg_mask, largest_obj)) 
Example #8
Source File: process.py    From Lifting-from-the-Deep-release with GNU General Public License v3.0 5 votes vote down vote up
def detect_objects_heatmap(heatmap):
    data = 256 * heatmap
    data_max = filters.maximum_filter(data, 3)
    maxima = (data == data_max)
    data_min = filters.minimum_filter(data, 3)
    diff = ((data_max - data_min) > 0.3)
    maxima[diff == 0] = 0
    labeled, num_objects = ndimage.label(maxima)
    slices = ndimage.find_objects(labeled)
    objects = np.zeros((num_objects, 2), dtype=np.int32)
    pidx = 0
    for (dy, dx) in slices:
        pos = [(dy.start + dy.stop - 1) // 2, (dx.start + dx.stop - 1) // 2]
        if heatmap[pos[0], pos[1]] > config.CENTER_TR:
            objects[pidx, :] = pos
            pidx += 1
    return objects[:pidx] 
Example #9
Source File: test_regression.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_ticket_742():
    def SE(img, thresh=.7, size=4):
        mask = img > thresh
        rank = len(mask.shape)
        la, co = ndimage.label(mask,
                               ndimage.generate_binary_structure(rank, rank))
        slices = ndimage.find_objects(la)

    if np.dtype(np.intp) != np.dtype('i'):
        shape = (3,1240,1240)
        a = np.random.rand(np.product(shape)).reshape(shape)
        # shouldn't crash
        SE(a) 
Example #10
Source File: test_measurements.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_find_objects09():
    data = np.array([[1, 0, 0, 0, 0, 0],
                           [0, 0, 2, 2, 0, 0],
                           [0, 0, 2, 2, 2, 0],
                           [0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 4, 4, 0]])
    out = ndimage.find_objects(data)
    assert_equal(out, [(slice(0, 1, None), slice(0, 1, None)),
                       (slice(1, 3, None), slice(2, 5, None)),
                       None,
                       (slice(5, 6, None), slice(3, 5, None))]) 
Example #11
Source File: test_measurements.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_find_objects08():
    data = np.array([[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]])
    out = ndimage.find_objects(data)
    assert_equal(out, [(slice(0, 1, None), slice(0, 1, None)),
                       (slice(1, 3, None), slice(2, 5, None)),
                       (slice(3, 5, None), slice(0, 2, None)),
                       (slice(5, 6, None), slice(3, 5, None))]) 
Example #12
Source File: test_measurements.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_find_objects07():
    data = np.array([[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 = ndimage.find_objects(data)
    assert_equal(out, []) 
Example #13
Source File: test_measurements.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_find_objects06():
    data = np.array([1, 0, 2, 2, 0, 3])
    out = ndimage.find_objects(data)
    assert_equal(out, [(slice(0, 1, None),),
                       (slice(2, 4, None),),
                       (slice(5, 6, None),)]) 
Example #14
Source File: find_bounding_boxes.py    From kaggle-carvana-2017 with MIT License 5 votes vote down vote up
def find_slices(mask_img):
    mask = mask_img > 100
    label_im, nb_labels = ndimage.label(mask)
    # Find the largest connect component
    sizes = ndimage.sum(mask, label_im, range(nb_labels + 1))
    mask_size = sizes < 50000
    remove_pixel = mask_size[label_im]
    label_im[remove_pixel] = 0
    labels = np.unique(label_im)
    label_im = np.searchsorted(labels, label_im)
    # Now that we have only one connect component, extract it's bounding box
    slice_y, slice_x = ndimage.find_objects(label_im == 1)[0]
    return slice_x, slice_y 
Example #15
Source File: test_measurements.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_find_objects03():
    data = np.ones([1], dtype=int)
    out = ndimage.find_objects(data)
    assert_equal(out, [(slice(0, 1, None),)]) 
Example #16
Source File: test_measurements.py    From Computable with MIT License 5 votes vote down vote up
def test_find_objects03():
    "find_objects 3"
    data = np.ones([1], dtype=int)
    out = ndimage.find_objects(data)
    assert_equal(out, [(slice(0, 1, None),)]) 
Example #17
Source File: stitch_patches_page.py    From ScanSSD with MIT License 5 votes vote down vote up
def find_blank_rows(image, line_spacing=1):

    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blank_rows = np.all(gray_image == 255, axis=1)

    im_bw = np.zeros(gray_image.shape)
    im_bw[blank_rows] = 255
    #gray_image[~blank_rows] = 0

    #cv2.imwrite("/home/psm2208/code/eval/test.png", im_bw)

    labeled, ncomponents = ndimage.label(im_bw)
    rows = []

    indices = np.indices(im_bw.shape).T[:, :, [1, 0]]

    line_bbs = ndimage.find_objects(labeled)
    sizes = np.array([[bb.stop - bb.start for bb in line_bb]
                      for line_bb in line_bbs])

    sizes = sizes[:,0]
    mask = (sizes > line_spacing)

    idx = np.flatnonzero(mask)

    for i in idx:
        labels = (labeled == (i+1))
        pixels = indices[labels.T]
        box = [min(pixels[:, 0]), min(pixels[:, 1]), max(pixels[:, 0]), max(pixels[:, 1])]
        rows.append(box)

    return rows 
Example #18
Source File: test_measurements.py    From Computable with MIT License 5 votes vote down vote up
def test_label_default_dtype():
    test_array = np.random.rand(10, 10)
    label, no_features = ndimage.label(test_array > 0.5)
    assert_(label.dtype in (np.int32, np.int64))
    # Shouldn't raise an exception
    ndimage.find_objects(label) 
Example #19
Source File: test_measurements.py    From Computable with MIT License 5 votes vote down vote up
def test_find_objects01():
    "find_objects 1"
    data = np.ones([], dtype=int)
    out = ndimage.find_objects(data)
    assert_(out == [()]) 
Example #20
Source File: test_measurements.py    From Computable with MIT License 5 votes vote down vote up
def test_find_objects02():
    "find_objects 2"
    data = np.zeros([], dtype=int)
    out = ndimage.find_objects(data)
    assert_(out == []) 
Example #21
Source File: test_measurements.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_find_objects02():
    data = np.zeros([], dtype=int)
    out = ndimage.find_objects(data)
    assert_(out == []) 
Example #22
Source File: test_measurements.py    From Computable with MIT License 5 votes vote down vote up
def test_find_objects04():
    "find_objects 4"
    data = np.zeros([1], dtype=int)
    out = ndimage.find_objects(data)
    assert_equal(out, []) 
Example #23
Source File: test_measurements.py    From Computable with MIT License 5 votes vote down vote up
def test_find_objects06():
    "find_objects 6"
    data = np.array([1, 0, 2, 2, 0, 3])
    out = ndimage.find_objects(data)
    assert_equal(out, [(slice(0, 1, None),),
                       (slice(2, 4, None),),
                       (slice(5, 6, None),)]) 
Example #24
Source File: test_measurements.py    From Computable with MIT License 5 votes vote down vote up
def test_find_objects07():
    "find_objects 7"
    data = np.array([[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 = ndimage.find_objects(data)
    assert_equal(out, []) 
Example #25
Source File: test_measurements.py    From Computable with MIT License 5 votes vote down vote up
def test_find_objects08():
    "find_objects 8"
    data = np.array([[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]])
    out = ndimage.find_objects(data)
    assert_equal(out, [(slice(0, 1, None), slice(0, 1, None)),
                       (slice(1, 3, None), slice(2, 5, None)),
                       (slice(3, 5, None), slice(0, 2, None)),
                       (slice(5, 6, None), slice(3, 5, None))]) 
Example #26
Source File: test_measurements.py    From Computable with MIT License 5 votes vote down vote up
def test_find_objects09():
    "find_objects 9"
    data = np.array([[1, 0, 0, 0, 0, 0],
                           [0, 0, 2, 2, 0, 0],
                           [0, 0, 2, 2, 2, 0],
                           [0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 4, 4, 0]])
    out = ndimage.find_objects(data)
    assert_equal(out, [(slice(0, 1, None), slice(0, 1, None)),
                       (slice(1, 3, None), slice(2, 5, None)),
                       None,
                       (slice(5, 6, None), slice(3, 5, None))]) 
Example #27
Source File: test_regression.py    From Computable with MIT License 5 votes vote down vote up
def test_ticket_742():
    def SE(img, thresh=.7, size=4):
        mask = img > thresh
        rank = len(mask.shape)
        la, co = ndimage.label(mask,
                               ndimage.generate_binary_structure(rank, rank))
        slices = ndimage.find_objects(la)

    if np.dtype(np.intp) != np.dtype('i'):
        shape = (3,1240,1240)
        a = np.random.rand(np.product(shape)).reshape(shape)
        # shouldn't crash
        SE(a) 
Example #28
Source File: test_measurements.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_label_default_dtype():
    test_array = np.random.rand(10, 10)
    label, no_features = ndimage.label(test_array > 0.5)
    assert_(label.dtype in (np.int32, np.int64))
    # Shouldn't raise an exception
    ndimage.find_objects(label) 
Example #29
Source File: test_measurements.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_find_objects01():
    data = np.ones([], dtype=int)
    out = ndimage.find_objects(data)
    assert_(out == [()]) 
Example #30
Source File: source_finder.py    From Aegean with Academic Free License v3.0 4 votes vote down vote up
def find_islands(im, bkg, rms,
                 seed_clip=5., flood_clip=4.,
                 log=log):
    """
    This function designed to be run as a stand alone process

    Parameters
    ----------
    im, bkg, rms : :class:`numpy.ndarray`
        Image, background, and rms maps

    seed_clip, flood_clip : float
        The seed clip which is used to create islands, and flood clip which is used to grow islands.
        The units are in SNR.

    log : `logging.Logger` or None
        For handling logs (or not)

    Returns
    -------
    islands : [:class:`AegeanTools.models.PixelIsland`, ...]
        a list of islands
    """
    # compute SNR image
    snr = abs(im - bkg) / rms

    # mask of pixles that are above the flood_clip
    a = snr >= flood_clip

    if not np.any(a):
        log.debug("There are no pixels above the clipping limit")
        return []

    # segmentation via scipy
    l, n = label(a)
    f = find_objects(l)

    log.debug("{1} Found {0} islands total above flood limit".format(n, im.shape))

    islands = []
    for i in range(n):
        xmin, xmax = f[i][0].start, f[i][0].stop
        ymin, ymax = f[i][1].start, f[i][1].stop
        if np.any(snr[xmin:xmax, ymin:ymax] > seed_clip):  # obey seed clip constraint
            data_box = copy.copy(im[xmin:xmax, ymin:ymax])  # copy so that we don't blank the master data
            data_box[np.where(
            snr[xmin:xmax, ymin:ymax] < flood_clip)] = np.nan  # blank pixels that are outside the outerclip
            data_box[np.where(l[xmin:xmax, ymin:ymax] != i + 1)] = np.nan  # blank out other summits
            # check if there are any pixels left unmasked
            if not np.any(np.isfinite(data_box)):
                # self.log.info("{1} Island {0} has no non-masked pixels".format(i,data.shape))
                continue
            island = PixelIsland()
            island.calc_bounding_box(np.array(np.nan_to_num(data_box), dtype=bool), offsets=[xmin, ymin])
            islands.append(island)

    return islands