How to use the skimage.morphology.disk function in skimage

To help you get started, we’ve selected a few skimage examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mpicbg-csbd / stardist / tests / _old_test_all.py View on Github external
def random_image(shape=(128,128)):
    from skimage.measure import label
    from skimage.morphology import binary_closing, binary_opening
    from skimage.morphology import disk
    img = np.random.normal(size=shape)
    img = img > -0.7
    img = binary_opening(img,disk(2))
    img = binary_closing(img,disk(1))
    img = label(img)
    return img
github MStarmans91 / WORC / WORC / plotting / plot_images.py View on Github external
def extract_boundary(contour, radius=2):
    returnitk = False
    if type(contour) is sitk.Image:
        contour = sitk.GetArrayFromImage(contour)
        returnitk = True

    disk = morphology.disk(radius)
    if len(contour.shape) == 3:
        for ind in range(contour.shape[0]):
            contour_d = morphology.binary_dilation(contour[ind, :, :], disk)
            contour_e = morphology.binary_erosion(contour[ind, :, :], disk)
            contour[ind, :, :] = np.bitwise_xor(contour_d, contour_e)
    else:
            contour_d = morphology.binary_dilation(contour, disk)
            contour_e = morphology.binary_erosion(contour, disk)
            contour = np.bitwise_xor(contour_d, contour_e)

    contour = contour.astype(np.uint16)  # To be compatible with SimpleITK
    if returnitk:
        return sitk.GetImageFromArray(contour)
    else:
        return contour
github EliasVansteenkiste / dsb3 / scripts / elias / segmentation_kernel.py View on Github external
areas = [r.area for r in regionprops(label_image)]
    areas.sort()
    if len(areas) > 2:
        for region in regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:                
                       label_image[coordinates[0], coordinates[1]] = 0
    binary = label_image > 0
    if plot == True:
        plots[3].axis('off')
        plots[3].imshow(binary, cmap=plt.cm.bone) 
    '''
    Step 5: Erosion operation with a disk of radius 2. This operation is 
    seperate the lung nodules attached to the blood vessels.
    '''
    selem = disk(2)
    binary = binary_erosion(binary, selem)
    if plot == True:
        plots[4].axis('off')
        plots[4].imshow(binary, cmap=plt.cm.bone) 
    '''
    Step 6: Closure operation with a disk of radius 10. This operation is 
    to keep nodules attached to the lung wall.
    '''
    selem = disk(10)
    binary = binary_closing(binary, selem)
    if plot == True:
        plots[5].axis('off')
        plots[5].imshow(binary, cmap=plt.cm.bone) 
    '''
    Step 7: Fill in the small holes inside the binary mask of lungs.
    '''
github AngryCai / Research / Toolbox / Preprocessing.py View on Github external
:param components:
        :param disk_radius:
        :return:2-dim emp
        """
        rows, cols, bands = components.shape
        n = disk_radius.__len__()
        import numpy as np
        emp = np.zeros((rows * cols, bands * (2 * n + 1)))
        from skimage.morphology import opening, closing, disk
        for band in range(bands):
            position = band * (n * 2 + 1) + n
            emp_ = np.zeros((rows, cols, 2 * n + 1))
            emp_[:, :, n] = components[:, :, band]
            i = 1
            for r in disk_radius:
                closed = closing(components[:, :, band], selem=disk(r))
                opened = opening(components[:, :, band], selem=disk(r))
                emp_[:, :, n - i] = closed
                emp_[:, :, n + i] = opened
                i += 1
            emp[:, position - n:position + n + 1] = emp_.reshape((rows * cols, 2 * n + 1))
        return emp.reshape(rows, cols, bands * (2 * n + 1))
github deworrall92 / harmonicConvolutions / visualize.py View on Github external
import caffe
	root_dir = '../caffe/'
	net = caffe.Net(root_dir+'models/vgg/VGG_ILSVRC_16_daniel_deploy.prototxt',
					root_dir+'models/vgg/VGG_ILSVRC_16_layers.caffemodel',
					caffe.TEST)
	
	# load input and configure preprocessing
	net.blobs['data'].reshape(10,3,481,481)
	
	transposed = False
	if im.shape[0] > im.shape[1]:
		im = np.transpose(im, (1,0,2))
		transposed = True
	im = (im - np.mean(im, axis=(0,1)))/np.std(im, axis=(0,1))
	im = np.pad(im, ((80,80),(0,0),(0,0)), 'constant')
	mask = skmo.disk(im.shape[0]/2 - 5)
	mask = np.pad(mask, ((5,5),(5,5)), 'constant')
	
	#plt.ion()
	#plt.show()
	save_dir = './video/cnn_rot_conv2_2/'
	im = sktr.resize(im, (481,481,3))
	angle_array = np.linspace(0., 360., num=721)
	angle_list = []
	for i in xrange(0,len(angle_array),10):
		angle_list.append(angle_array[i:i+10])
	j = 0
	for angles in angle_list:
		images = []
		for angle in angles:
			offset_x = int(100.*np.sin(2*np.pi*angle/360.))
			#offset_y = int(100.*np.sin(2*np.pi*angle/360.))
github EliasVansteenkiste / dsb3 / scripts / elias / stats_rois_with_ls4.py View on Github external
mask = x

    # detect if additional borders were added.
    corner = 0
    for i in xrange(0,min(mask.shape[0],mask.shape[1])):
       if mask[i, i] == 0:
           corner = i
           break

    # select inner part
    part = mask[corner:-corner-1,corner:-corner-1]
    binary_part = part > 0.5

    # fill the body part
    filled = scipy.ndimage.binary_fill_holes(binary_part) # fill body
    selem = skimage.morphology.disk(5) # clear details outside of major body part
    filled_borders = skimage.morphology.erosion(filled, selem)
    filled_borders = 1 - filled_borders # flip mask

    # put mask back
    full_mask = np.ones((mask.shape[0],mask.shape[1]))
    full_mask[corner:-corner-1,corner:-corner-1] = filled_borders

    full_mask = np.asarray(full_mask,dtype=np.bool)

    # set outside to grey
    filled_borders = mask
    filled_borders[full_mask]=0.75


    # finally do the normal segmentation operations
github kvos / CoastSat / coastsat / SDS_shoreline.py View on Github external
ncols = cloud_mask.shape[1]

    # calculate Normalized Difference Modified Water Index (SWIR - G)
    im_mwi = SDS_tools.nd_index(im_ms[:,:,4], im_ms[:,:,1], cloud_mask)
    # calculate Normalized Difference Modified Water Index (NIR - G)
    im_wi = SDS_tools.nd_index(im_ms[:,:,3], im_ms[:,:,1], cloud_mask)
    # stack indices together
    im_ind = np.stack((im_wi, im_mwi), axis=-1)
    vec_ind = im_ind.reshape(nrows*ncols,2)

    # reshape labels into vectors
    vec_sand = im_labels[:,:,0].reshape(ncols*nrows)
    vec_water = im_labels[:,:,2].reshape(ncols*nrows)

    # create a buffer around the sandy beach
    se = morphology.disk(buffer_size)
    im_buffer = morphology.binary_dilation(im_labels[:,:,0], se)
    vec_buffer = im_buffer.reshape(nrows*ncols)

    # select water/sand/swash pixels that are within the buffer
    int_water = vec_ind[np.logical_and(vec_buffer,vec_water),:]
    int_sand = vec_ind[np.logical_and(vec_buffer,vec_sand),:]

    # make sure both classes have the same number of pixels before thresholding
    if len(int_water) > 0 and len(int_sand) > 0:
        if np.argmin([int_sand.shape[0],int_water.shape[0]]) == 1:
            int_sand = int_sand[np.random.choice(int_sand.shape[0],int_water.shape[0], replace=False),:]
        else:
            int_water = int_water[np.random.choice(int_water.shape[0],int_sand.shape[0], replace=False),:]

    # threshold the sand/water intensities
    int_all = np.append(int_water,int_sand, axis=0)
github albertomontesg / davis-interactive / davisinteractive / robot / interactive_robot.py View on Github external
Returns:
            skel: Numpy Array. Skeleton mask
        """
        mask = np.asarray(mask, dtype=np.uint8)
        side = np.sqrt(np.sum(mask > 0))

        mask_ = mask
        # kernel_size = int(self.kernel_size * side)
        kernel_radius = self.kernel_size * side * .5
        kernel_radius = min(kernel_radius, self.max_kernel_radius)
        logging.verbose(
            'Erosion and dilation with kernel radius: {:.1f}'.format(
                kernel_radius), 2)
        compute = True
        while kernel_radius > 1. and compute:
            kernel = disk(kernel_radius)
            mask_ = rank.minimum(mask.copy(), kernel)
            mask_ = rank.maximum(mask_, kernel)
            compute = False
            if mask_.astype(np.bool).sum() == 0:
                compute = True
                prev_kernel_radius = kernel_radius
                kernel_radius *= .9
                logging.verbose('Reducing kernel radius from {:.1f} '.format(
                    prev_kernel_radius) +
                                'pixels to {:.1f}'.format(kernel_radius), 1)

        mask_ = np.pad(
            mask_, ((1, 1), (1, 1)), mode='constant', constant_values=False)
        skel = medial_axis(mask_.astype(np.bool))
        skel = skel[1:-1, 1:-1]
        return skel
github gzuidhof / luna16 / src / deep / dataset.py View on Github external
if os.path.isfile(truth_filename):
        with gzip.open(truth_filename,'rb') as f:
            truth = np.array(pickle.load(f),dtype=np.float32)
    else:
        truth = np.zeros_like(lung)

    if os.path.isfile(segmentation_filename):
        with gzip.open(segmentation_filename,'rb') as f:
            outside = np.where(pickle.load(f)>0,0,1)
    else:
        outside = np.where(lung==0,1,0)
        print 'lung not found'

    if P.ERODE_SEGMENTATION > 0:
        kernel = skimage.morphology.disk(P.ERODE_SEGMENTATION)
        outside = skimage.morphology.binary_erosion(outside, kernel)

    outside = np.array(outside, dtype=np.float32)

    if P.AUGMENT and not deterministic:
        lung, truth, outside = augment([lung, truth, outside])

    if P.RANDOM_CROP > 0:
        im_x = lung.shape[0]
        im_y = lung.shape[1]
        x = np.random.randint(0, max(1,im_x-P.RANDOM_CROP))
        y = np.random.randint(0, max(1,im_y-P.RANDOM_CROP))

        lung = lung[x:x+P.RANDOM_CROP, y:y+P.RANDOM_CROP]
        truth = truth[x:x+P.RANDOM_CROP, y:y+P.RANDOM_CROP]
        outside = outside[x:x+P.RANDOM_CROP, y:y+P.RANDOM_CROP]