Python scipy.ndimage.generate_binary_structure() Examples

The following are 30 code examples of scipy.ndimage.generate_binary_structure(). 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: test_ndimage.py    From Computable with MIT License 7 votes vote down vote up
def test_binary_dilation26(self):
        struct = ndimage.generate_binary_structure(2, 2)
        expected = [[1, 1, 1, 0, 0, 0, 0, 0],
                [1, 1, 1, 0, 0, 0, 0, 0],
                [1, 1, 1, 0, 1, 1, 1, 0],
                [0, 0, 1, 1, 1, 1, 1, 0],
                [0, 1, 1, 1, 1, 1, 1, 0],
                [0, 1, 1, 1, 1, 1, 1, 0],
                [0, 1, 1, 1, 1, 1, 1, 0],
                [0, 0, 0, 0, 0, 0, 0, 0]]

        for type in self.types:
            data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0],
                                   [0, 1, 0, 0, 0, 0, 0, 0],
                                   [0, 0, 0, 0, 0, 0, 0, 0],
                                   [0, 0, 0, 0, 0, 1, 0, 0],
                                   [0, 0, 0, 1, 1, 0, 0, 0],
                                   [0, 0, 1, 0, 0, 1, 0, 0],
                                   [0, 0, 0, 0, 0, 0, 0, 0],
                                   [0, 0, 0, 0, 0, 0, 0, 0]], type)
            out = ndimage.binary_dilation(data, struct)
            assert_array_almost_equal(out, expected) 
Example #2
Source File: image_process.py    From PyMIC with Apache License 2.0 7 votes vote down vote up
def get_largest_component(image):
    """
    get the largest component from 2D or 3D binary image
    image: nd array
    """
    dim = len(image.shape)
    if(image.sum() == 0 ):
        print('the largest component is null')
        return image
    if(dim == 2):
        s = ndimage.generate_binary_structure(2,1)
    elif(dim == 3):
        s = ndimage.generate_binary_structure(3,1)
    else:
        raise ValueError("the dimension number should be 2 or 3")
    labeled_array, numpatches = ndimage.label(image, s)
    sizes = ndimage.sum(image, labeled_array, range(1, numpatches + 1))
    max_label = np.where(sizes == sizes.max())[0] + 1
    output = np.asarray(labeled_array == max_label, np.uint8)
    return  output 
Example #3
Source File: test_ndimage.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_binary_dilation26(self):
        struct = ndimage.generate_binary_structure(2, 2)
        expected = [[1, 1, 1, 0, 0, 0, 0, 0],
                    [1, 1, 1, 0, 0, 0, 0, 0],
                    [1, 1, 1, 0, 1, 1, 1, 0],
                    [0, 0, 1, 1, 1, 1, 1, 0],
                    [0, 1, 1, 1, 1, 1, 1, 0],
                    [0, 1, 1, 1, 1, 1, 1, 0],
                    [0, 1, 1, 1, 1, 1, 1, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0]]

        for type_ in self.types:
            data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0],
                                [0, 1, 0, 0, 0, 0, 0, 0],
                                [0, 0, 0, 0, 0, 0, 0, 0],
                                [0, 0, 0, 0, 0, 1, 0, 0],
                                [0, 0, 0, 1, 1, 0, 0, 0],
                                [0, 0, 1, 0, 0, 1, 0, 0],
                                [0, 0, 0, 0, 0, 0, 0, 0],
                                [0, 0, 0, 0, 0, 0, 0, 0]], type_)
            out = ndimage.binary_dilation(data, struct)
            assert_array_almost_equal(out, expected) 
Example #4
Source File: postprocess0.py    From 2018DSB with MIT License 6 votes vote down vote up
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: data_process.py    From Brain-Tumor-Segmentation-using-Topological-Loss with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def remove_external_core(lab_main, lab_ext):
    """
    remove the core region that is outside of whole tumor
    """
    
    # for each component of lab_ext, compute the overlap with lab_main
    s = ndimage.generate_binary_structure(3,2) # iterate structure
    labeled_array, numpatches = ndimage.label(lab_ext,s) # labeling
    sizes = ndimage.sum(lab_ext,labeled_array,range(1,numpatches+1)) 
    sizes_list = [sizes[i] for i in range(len(sizes))]
    new_lab_ext = np.zeros_like(lab_ext)
    for i in range(len(sizes)):
        sizei = sizes_list[i]
        labeli =  np.where(sizes == sizei)[0] + 1
        componenti = labeled_array == labeli
        overlap = componenti * lab_main
        if((overlap.sum()+ 0.0)/sizei >= 0.5):
            new_lab_ext = np.maximum(new_lab_ext, componenti)
    return new_lab_ext 
Example #6
Source File: data_process.py    From brats17 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def remove_external_core(lab_main, lab_ext):
    """
    remove the core region that is outside of whole tumor
    """
    
    # for each component of lab_ext, compute the overlap with lab_main
    s = ndimage.generate_binary_structure(3,2) # iterate structure
    labeled_array, numpatches = ndimage.label(lab_ext,s) # labeling
    sizes = ndimage.sum(lab_ext,labeled_array,range(1,numpatches+1)) 
    sizes_list = [sizes[i] for i in range(len(sizes))]
    new_lab_ext = np.zeros_like(lab_ext)
    for i in range(len(sizes)):
        sizei = sizes_list[i]
        labeli =  np.where(sizes == sizei)[0] + 1
        componenti = labeled_array == labeli
        overlap = componenti * lab_main
        if((overlap.sum()+ 0.0)/sizei >= 0.5):
            new_lab_ext = np.maximum(new_lab_ext, componenti)
    return new_lab_ext 
Example #7
Source File: test_core.py    From dask-image with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_label(seed, prob, shape, chunks, connectivity):
    np.random.seed(seed)

    a = np.random.random(shape) < prob
    d = da.from_array(a, chunks=chunks)

    s = spnd.generate_binary_structure(a.ndim, connectivity)

    a_l, a_nl = spnd.label(a, s)
    d_l, d_nl = dask_image.ndmeasure.label(d, s)

    assert a_nl == d_nl.compute()

    assert a_l.dtype == d_l.dtype
    assert a_l.shape == d_l.shape
    _assert_equivalent_labeling(a_l, d_l.compute()) 
Example #8
Source File: anatomical.py    From mriqc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _prepare_mask(mask, label, erode=True):
    fgmask = mask.copy()

    if np.issubdtype(fgmask.dtype, np.integer):
        if isinstance(label, (str, bytes)):
            label = FSL_FAST_LABELS[label]

        fgmask[fgmask != label] = 0
        fgmask[fgmask == label] = 1
    else:
        fgmask[fgmask > 0.95] = 1.0
        fgmask[fgmask < 1.0] = 0

    if erode:
        # Create a structural element to be used in an opening operation.
        struc = nd.generate_binary_structure(3, 2)
        # Perform an opening operation on the background data.
        fgmask = nd.binary_opening(fgmask, structure=struc).astype(np.uint8)

    return fgmask 
Example #9
Source File: anatomical.py    From mriqc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _run_interface(self, runtime):

        in_file = nb.load(self.inputs.in_file)
        wm_mask = nb.load(self.inputs.wm_mask).get_data()
        wm_mask[wm_mask < 0.9] = 0
        wm_mask[wm_mask > 0] = 1
        wm_mask = wm_mask.astype(np.uint8)

        if self.inputs.erodemsk:
            # Create a structural element to be used in an opening operation.
            struc = nd.generate_binary_structure(3, 2)
            # Perform an opening operation on the background data.
            wm_mask = nd.binary_erosion(wm_mask, structure=struc).astype(np.uint8)

        data = in_file.get_data()
        data *= 1000.0 / np.median(data[wm_mask > 0])

        out_file = fname_presuffix(
            self.inputs.in_file, suffix="_harmonized", newpath="."
        )
        in_file.__class__(data, in_file.affine, in_file.header).to_filename(out_file)

        self._results["out_file"] = out_file

        return runtime 
Example #10
Source File: test_ndimage.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_binary_closing02(self):
        struct = ndimage.generate_binary_structure(2, 2)
        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 1, 1, 0, 0, 0, 0, 0],
                    [0, 1, 1, 1, 1, 1, 1, 0],
                    [0, 1, 1, 1, 1, 1, 1, 0],
                    [0, 1, 1, 1, 1, 1, 1, 0],
                    [0, 1, 1, 1, 1, 1, 1, 0],
                    [0, 1, 1, 1, 1, 1, 1, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0]]
        for type_ in self.types:
            data = numpy.array([[1, 1, 1, 0, 0, 0, 0, 0],
                                [1, 1, 1, 0, 0, 0, 0, 0],
                                [1, 1, 1, 1, 1, 1, 1, 0],
                                [0, 0, 1, 1, 1, 1, 1, 0],
                                [0, 1, 1, 1, 0, 1, 1, 0],
                                [0, 1, 1, 1, 1, 1, 1, 0],
                                [0, 1, 1, 1, 1, 1, 1, 0],
                                [0, 0, 0, 0, 0, 0, 0, 0]], type_)
            out = ndimage.binary_closing(data, struct)
            assert_array_almost_equal(out, expected) 
Example #11
Source File: test_ndimage.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_binary_opening02(self):
        struct = ndimage.generate_binary_structure(2, 2)
        expected = [[1, 1, 1, 0, 0, 0, 0, 0],
                    [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, 1, 1, 1, 0, 0, 0, 0],
                    [0, 1, 1, 1, 0, 0, 0, 0],
                    [0, 1, 1, 1, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0]]
        for type_ in self.types:
            data = numpy.array([[1, 1, 1, 0, 0, 0, 0, 0],
                                [1, 1, 1, 0, 0, 0, 0, 0],
                                [1, 1, 1, 1, 1, 1, 1, 0],
                                [0, 0, 1, 1, 1, 1, 1, 0],
                                [0, 1, 1, 1, 0, 1, 1, 0],
                                [0, 1, 1, 1, 1, 1, 1, 0],
                                [0, 1, 1, 1, 1, 1, 1, 0],
                                [0, 0, 0, 0, 0, 0, 0, 0]], type_)
            out = ndimage.binary_opening(data, struct)
            assert_array_almost_equal(out, expected) 
Example #12
Source File: util.py    From DeepFloorplan with GNU General Public License v3.0 6 votes vote down vote up
def flood_fill(test_array, h_max=255):
	"""
	fill in the hole 
	"""
	input_array = np.copy(test_array) 
	el = ndimage.generate_binary_structure(2,2).astype(np.int)
	inside_mask = ndimage.binary_erosion(~np.isnan(input_array), structure=el)
	output_array = np.copy(input_array)
	output_array[inside_mask]=h_max
	output_old_array = np.copy(input_array)
	output_old_array.fill(0)   
	el = ndimage.generate_binary_structure(2,1).astype(np.int)
	while not np.array_equal(output_old_array, output_array):
		output_old_array = np.copy(output_array)
		output_array = np.maximum(input_array,ndimage.grey_erosion(output_array, size=(3,3), footprint=el))
	return output_array 
Example #13
Source File: test_ndimage.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_binary_erosion23(self):
        struct = ndimage.generate_binary_structure(2, 2)
        expected = [[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, 1, 1, 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]]
        for type_ in self.types:
            data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0],
                                [0, 1, 0, 0, 0, 0, 0, 0],
                                [0, 0, 0, 0, 0, 1, 1, 1],
                                [0, 0, 1, 1, 1, 1, 1, 1],
                                [0, 0, 1, 1, 1, 1, 0, 0],
                                [0, 1, 1, 1, 1, 1, 1, 0],
                                [0, 1, 1, 0, 0, 1, 1, 0],
                                [0, 0, 0, 0, 0, 0, 0, 0]], type_)
            out = ndimage.binary_erosion(data, struct, border_value=1)
            assert_array_almost_equal(out, expected) 
Example #14
Source File: test_measurements.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_label09():
    data = np.array([[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]])
    struct = ndimage.generate_binary_structure(2, 2)
    out, n = ndimage.label(data, struct)
    assert_array_almost_equal(out, [[1, 0, 0, 0, 0, 0],
                               [0, 0, 2, 2, 0, 0],
                               [0, 0, 2, 2, 2, 0],
                               [2, 2, 0, 0, 0, 0],
                               [2, 2, 0, 0, 0, 0],
                               [0, 0, 0, 3, 3, 0]])
    assert_equal(n, 3) 
Example #15
Source File: test_measurements.py    From Computable with MIT License 6 votes vote down vote up
def test_label09():
    "label 9"
    data = np.array([[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]])
    struct = ndimage.generate_binary_structure(2, 2)
    out, n = ndimage.label(data, struct)
    assert_array_almost_equal(out, [[1, 0, 0, 0, 0, 0],
                               [0, 0, 2, 2, 0, 0],
                               [0, 0, 2, 2, 2, 0],
                               [2, 2, 0, 0, 0, 0],
                               [2, 2, 0, 0, 0, 0],
                               [0, 0, 0, 3, 3, 0]])
    assert_equal(n, 3) 
Example #16
Source File: test_ndimage.py    From Computable with MIT License 6 votes vote down vote up
def test_binary_closing02(self):
        struct = ndimage.generate_binary_structure(2, 2)
        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
                [0, 1, 1, 0, 0, 0, 0, 0],
                [0, 1, 1, 1, 1, 1, 1, 0],
                [0, 1, 1, 1, 1, 1, 1, 0],
                [0, 1, 1, 1, 1, 1, 1, 0],
                [0, 1, 1, 1, 1, 1, 1, 0],
                [0, 1, 1, 1, 1, 1, 1, 0],
                [0, 0, 0, 0, 0, 0, 0, 0]]
        for type in self.types:
            data = numpy.array([[1, 1, 1, 0, 0, 0, 0, 0],
                                   [1, 1, 1, 0, 0, 0, 0, 0],
                                   [1, 1, 1, 1, 1, 1, 1, 0],
                                   [0, 0, 1, 1, 1, 1, 1, 0],
                                   [0, 1, 1, 1, 0, 1, 1, 0],
                                   [0, 1, 1, 1, 1, 1, 1, 0],
                                   [0, 1, 1, 1, 1, 1, 1, 0],
                                   [0, 0, 0, 0, 0, 0, 0, 0]], type)
            out = ndimage.binary_closing(data, struct)
            assert_array_almost_equal(out, expected) 
Example #17
Source File: test_ndimage.py    From Computable with MIT License 6 votes vote down vote up
def test_binary_opening02(self):
        struct = ndimage.generate_binary_structure(2, 2)
        expected = [[1, 1, 1, 0, 0, 0, 0, 0],
                [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, 1, 1, 1, 0, 0, 0, 0],
                [0, 1, 1, 1, 0, 0, 0, 0],
                [0, 1, 1, 1, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0]]
        for type in self.types:
            data = numpy.array([[1, 1, 1, 0, 0, 0, 0, 0],
                                   [1, 1, 1, 0, 0, 0, 0, 0],
                                   [1, 1, 1, 1, 1, 1, 1, 0],
                                   [0, 0, 1, 1, 1, 1, 1, 0],
                                   [0, 1, 1, 1, 0, 1, 1, 0],
                                   [0, 1, 1, 1, 1, 1, 1, 0],
                                   [0, 1, 1, 1, 1, 1, 1, 0],
                                   [0, 0, 0, 0, 0, 0, 0, 0]], type)
            out = ndimage.binary_opening(data, struct)
            assert_array_almost_equal(out, expected) 
Example #18
Source File: test_ndimage.py    From Computable with MIT License 6 votes vote down vote up
def test_binary_erosion23(self):
        struct = ndimage.generate_binary_structure(2, 2)
        expected = [[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, 1, 1, 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]]
        for type in self.types:
            data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0],
                                   [0, 1, 0, 0, 0, 0, 0, 0],
                                   [0, 0, 0, 0, 0, 1, 1, 1],
                                   [0, 0, 1, 1, 1, 1, 1, 1],
                                   [0, 0, 1, 1, 1, 1, 0, 0],
                                   [0, 1, 1, 1, 1, 1, 1, 0],
                                   [0, 1, 1, 0, 0, 1, 1, 0],
                                   [0, 0, 0, 0, 0, 0, 0, 0]], type)
            out = ndimage.binary_erosion(data, struct,
                                                   border_value=1)
            assert_array_almost_equal(out, expected) 
Example #19
Source File: test_ndimage.py    From Computable with MIT License 5 votes vote down vote up
def test_generate_structure02(self):
        struct = ndimage.generate_binary_structure(1, 1)
        assert_array_almost_equal(struct, [1, 1, 1]) 
Example #20
Source File: postprocess_utils.py    From coded with MIT License 5 votes vote down vote up
def raster_buffer(raster_filepath, in_array, dist=1):

    """ Binary dilation using scikit image """

    struct = ndimage.generate_binary_structure(2, 2)
    out_array = ndimage.binary_dilation(in_array, structure=struct,
                                        iterations=dist).astype(in_array.dtype)
    return out_array 
Example #21
Source File: postprocess0.py    From 2018DSB with MIT License 5 votes vote down vote up
def modify_w_unet(base_label, preds, thres=0.25):
    base_label = base_label.copy()
    vals = np.unique(base_label[base_label>0])
    struct = generate_binary_structure(2,2)
    for nb_dilation in range(3):    
        for val in vals:
            label_mask = base_label==val
            base_label[binary_dilation(label_mask,struct)&(preds[:,:,0]>thres)&(base_label==0)]=val
    return base_label 
Example #22
Source File: cca.py    From segmentation_uncertainty with MIT License 5 votes vote down vote up
def get_unc_labels(x, unc, metric, xy):
    x_big = ndimage.binary_dilation(x, structure=ndimage.generate_binary_structure(3, 2))
    labels, nles = ndimage.label(x_big)
    unc_labels = np.zeros_like(unc)
    for i in range(1, nles + 1):
        unc_labels[labels == i] = np.sum(np.log(unc[labels == i] + 1e-5))

    unc_labels[unc_labels != 0] = (unc_labels[unc_labels != 0] - _LESION_UNC_VA[metric][xy + 'min']) / (
        _LESION_UNC_VA[metric][xy + 'max'] - _LESION_UNC_VA[metric][xy + 'min'])
    return unc_labels 
Example #23
Source File: data_process.py    From Brain-Tumor-Segmentation-using-Topological-Loss with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fill_holes(img):
    """
    filling small holes of a binary volume with morphological operations
    """
    neg = 1 - img
    s = ndimage.generate_binary_structure(3,1) # iterate structure
    labeled_array, numpatches = ndimage.label(neg,s) # labeling
    sizes = ndimage.sum(neg,labeled_array,range(1,numpatches+1)) 
    sizes_list = [sizes[i] for i in range(len(sizes))]
    sizes_list.sort()
    max_size = sizes_list[-1]
    max_label = np.where(sizes == max_size)[0] + 1
    component = labeled_array == max_label
    return 1 - component 
Example #24
Source File: data_process.py    From Brain-Tumor-Segmentation-using-Topological-Loss with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_largest_two_component(img, print_info = False, threshold = None):
    """
    Get the largest two components of a binary volume
    inputs:
        img: the input 3D volume
        threshold: a size threshold
    outputs:
        out_img: the output volume 
    """
    s = ndimage.generate_binary_structure(3,2) # iterate structure
    labeled_array, numpatches = ndimage.label(img,s) # labeling
    sizes = ndimage.sum(img,labeled_array,range(1,numpatches+1)) 
    sizes_list = [sizes[i] for i in range(len(sizes))]
    sizes_list.sort()
    if(print_info):
        print('component size', sizes_list)
    if(len(sizes) == 1):
        out_img = img
    else:
        if(threshold):
            out_img = np.zeros_like(img)
            for temp_size in sizes_list:
                if(temp_size > threshold):
                    temp_lab = np.where(sizes == temp_size)[0] + 1
                    temp_cmp = labeled_array == temp_lab
                    out_img = (out_img + temp_cmp) > 0
            return out_img
        else:    
            max_size1 = sizes_list[-1]
            max_size2 = sizes_list[-2]
            max_label1 = np.where(sizes == max_size1)[0] + 1
            max_label2 = np.where(sizes == max_size2)[0] + 1
            component1 = labeled_array == max_label1
            component2 = labeled_array == max_label2
            if(max_size2*10 > max_size1):
                component1 = (component1 + component2) > 0
            out_img = component1
    return out_img 
Example #25
Source File: test_measurements.py    From Computable with MIT License 5 votes vote down vote up
def test_label10():
    "label 10"
    data = np.array([[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) 
Example #26
Source File: data_process.py    From brats17 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fill_holes(img):
    """
    filling small holes of a binary volume with morphological operations
    """
    neg = 1 - img
    s = ndimage.generate_binary_structure(3,1) # iterate structure
    labeled_array, numpatches = ndimage.label(neg,s) # labeling
    sizes = ndimage.sum(neg,labeled_array,range(1,numpatches+1)) 
    sizes_list = [sizes[i] for i in range(len(sizes))]
    sizes_list.sort()
    max_size = sizes_list[-1]
    max_label = np.where(sizes == max_size)[0] + 1
    component = labeled_array == max_label
    return 1 - component 
Example #27
Source File: data_process.py    From brats17 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_largest_two_component(img, print_info = False, threshold = None):
    """
    Get the largest two components of a binary volume
    inputs:
        img: the input 3D volume
        threshold: a size threshold
    outputs:
        out_img: the output volume 
    """
    s = ndimage.generate_binary_structure(3,2) # iterate structure
    labeled_array, numpatches = ndimage.label(img,s) # labeling
    sizes = ndimage.sum(img,labeled_array,range(1,numpatches+1)) 
    sizes_list = [sizes[i] for i in range(len(sizes))]
    sizes_list.sort()
    if(print_info):
        print('component size', sizes_list)
    if(len(sizes) == 1):
        out_img = img
    else:
        if(threshold):
            out_img = np.zeros_like(img)
            for temp_size in sizes_list:
                if(temp_size > threshold):
                    temp_lab = np.where(sizes == temp_size)[0] + 1
                    temp_cmp = labeled_array == temp_lab
                    out_img = (out_img + temp_cmp) > 0
            return out_img
        else:    
            max_size1 = sizes_list[-1]
            max_size2 = sizes_list[-2]
            max_label1 = np.where(sizes == max_size1)[0] + 1
            max_label2 = np.where(sizes == max_size2)[0] + 1
            component1 = labeled_array == max_label1
            component2 = labeled_array == max_label2
            if(max_size2*10 > max_size1):
                component1 = (component1 + component2) > 0
            out_img = component1
    return out_img 
Example #28
Source File: test_ndimage.py    From Computable with MIT License 5 votes vote down vote up
def test_generate_structure01(self):
        struct = ndimage.generate_binary_structure(0, 1)
        assert_array_almost_equal(struct, 1) 
Example #29
Source File: image_utils.py    From visualqc with Apache License 2.0 5 votes vote down vote up
def background_mask(mri, thresh_perc=1):
    """Creates the background mask from an MRI"""

    grad_magnitude = gradient_magnitude(mri)
    nonzero_grad_mag = grad_magnitude[grad_magnitude > 0]

    thresh_val = np.percentile(nonzero_grad_mag.flatten(), thresh_perc)
    background_mask = grad_magnitude < thresh_val

    se36 = ndimage.generate_binary_structure(3, 6)
    closed = ndimage.binary_closing(background_mask, se36, iterations=6)
    final_mask = ndimage.binary_erosion(closed, se36, iterations=5)

    return final_mask 
Example #30
Source File: evaluation.py    From PyMIC with Apache License 2.0 5 votes vote down vote up
def get_edge_points(img):
    """
    get edge points of a binary segmentation result
    """
    dim = len(img.shape)
    if(dim == 2):
        strt = ndimage.generate_binary_structure(2,1)
    else:
        strt = ndimage.generate_binary_structure(3,1)
    ero  = ndimage.morphology.binary_erosion(img, strt)
    edge = np.asarray(img, np.uint8) - np.asarray(ero, np.uint8) 
    return edge