Python skimage.morphology.square() Examples
The following are 30
code examples of skimage.morphology.square().
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
skimage.morphology
, or try the search function
.
Example #1
Source File: math.py From spinalcordtoolbox with MIT License | 7 votes |
def dilate(data, size, shape, dim=None): """ Dilate data using ball structuring element :param data: Image or numpy array: 2d or 3d array :param size: int: If shape={'square', 'cube'}: Corresponds to the length of an edge (size=1 has no effect). If shape={'disk', 'ball'}: Corresponds to the radius, not including the center element (size=0 has no effect). :param shape: {'square', 'cube', 'disk', 'ball'} :param dim: {0, 1, 2}: Dimension of the array which 2D structural element will be orthogonal to. For example, if you wish to apply a 2D disk kernel in the X-Y plane, leaving Z unaffected, parameters will be: shape=disk, dim=2. :return: numpy array: data dilated """ if isinstance(data, Image): im_out = data.copy() im_out.data = dilate(data.data, size, shape, dim) return im_out else: return dilation(data, selem=_get_selem(shape, size, dim), out=None)
Example #2
Source File: getTerminationBifurcation.py From Fingerprint-Feature-Extraction with MIT License | 6 votes |
def getTerminationBifurcation(img, mask): img = img == 255; (rows, cols) = img.shape; minutiaeTerm = np.zeros(img.shape); minutiaeBif = np.zeros(img.shape); for i in range(1,rows-1): for j in range(1,cols-1): if(img[i][j] == 1): block = img[i-1:i+2,j-1:j+2]; block_val = np.sum(block); if(block_val == 2): minutiaeTerm[i,j] = 1; elif(block_val == 4): minutiaeBif[i,j] = 1; mask = convex_hull_image(mask>0) mask = erosion(mask, square(5)) # Structuing element for mask erosion = square(5) minutiaeTerm = np.uint8(mask)*minutiaeTerm return(minutiaeTerm, minutiaeBif)
Example #3
Source File: RankFilter.py From raster-functions with Apache License 2.0 | 6 votes |
def updateRasterInfo(self, **kwargs): kwargs['output_info']['statistics'] = () kwargs['output_info']['histogram'] = () self.window = square(int(kwargs.get('size', 3))) m = kwargs.get('measure', 'Mean').lower() if m == 'minimum': self.func = rank.minimum elif m == 'maximum': self.func = rank.maximum elif m == 'mean': self.func = rank.mean elif m == 'bilateral mean': self.func = rank.mean_bilateral elif m == 'median': self.func = rank.median elif m == 'sum': self.func = rank.sum elif m == 'entropy': self.func = rank.entropy elif m == 'threshold': self.func = rank.threshold elif m == 'autolevel': self.func = rank.autolevel return kwargs
Example #4
Source File: draw_ellipse.py From DeepVOG with GNU General Public License v3.0 | 6 votes |
def isolate_islands(prediction, threshold): bw = closing(prediction > threshold , square(3)) labelled = label(bw) regions_properties = regionprops(labelled) max_region_area = 0 select_region = 0 for region in regions_properties: if region.area > max_region_area: max_region_area = region.area select_region = region output = np.zeros(labelled.shape) if select_region == 0: return output else: output[labelled == select_region.label] = 1 return output # input: output from bwperim -- 2D image with perimeter of the ellipse = 1
Example #5
Source File: utils.py From DRFNS with MIT License | 6 votes |
def generate_wsl(ws): """ Generates watershed line. In particular, useful for seperating object in ground thruth as they are labeled by different intergers. """ se = square(3) ero = ws.copy() ero[ero == 0] = ero.max() + 1 ero = erosion(ero, se) ero[ws == 0] = 0 grad = dilation(ws, se) - ero grad[ws == 0] = 0 grad[grad > 0] = 255 grad = grad.astype(np.uint8) return grad
Example #6
Source File: math.py From spinalcordtoolbox with MIT License | 6 votes |
def erode(data, size, shape, dim=None): """ Dilate data using ball structuring element :param data: Image or numpy array: 2d or 3d array :param size: int: If shape={'square', 'cube'}: Corresponds to the length of an edge (size=1 has no effect). If shape={'disk', 'ball'}: Corresponds to the radius, not including the center element (size=0 has no effect). :param shape: {'square', 'cube', 'disk', 'ball'} :param dim: {0, 1, 2}: Dimension of the array which 2D structural element will be orthogonal to. For example, if you wish to apply a 2D disk kernel in the X-Y plane, leaving Z unaffected, parameters will be: shape=disk, dim=2. :return: numpy array: data dilated """ if isinstance(data, Image): im_out = data.copy() im_out.data = erode(data.data, size, shape, dim) return im_out else: return erosion(data, selem=_get_selem(shape, size, dim), out=None)
Example #7
Source File: input_pipeline.py From SketchySceneColorization with MIT License | 6 votes |
def thicken_drawings(image): """ :param image: [H, W, 3], np.float32 :return: """ img = np.array(image[:, :, 0], dtype=np.uint8) img = 255 - img dilated_img = sm.dilation(img, sm.square(2)) dilated_img = 255 - dilated_img # [H, W] rst_img3 = np.zeros([dilated_img.shape[0], dilated_img.shape[1], 3], dtype=np.uint8) for i in range(3): rst_img3[:, :, i] = dilated_img return rst_img3
Example #8
Source File: expt_utils.py From pyxem with GNU General Public License v3.0 | 6 votes |
def subtract_background_median(z, footprint): """Remove background using a median filter. Parameters ---------- footprint : int size of the window that is convoluted with the array to determine the median. Should be large enough that it is about 3x as big as the size of the peaks. Returns ------- Pattern with background subtracted as np.array """ selem = morphology.square(footprint) # skimage only accepts input image as uint16 bg_subtracted = z - filters.median(z.astype(np.uint16), selem).astype(z.dtype) return np.maximum(bg_subtracted, 0)
Example #9
Source File: pose_utils.py From Human-Pose-Transfer with MIT License | 5 votes |
def produce_ma_mask(kp_array, img_size, point_radius=4): from skimage.morphology import dilation, erosion, square mask = np.zeros(shape=img_size, dtype=bool) limbs = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], [1, 16], [16, 18], [2, 17], [2, 18], [9, 12], [12, 6], [9, 3], [17, 18]] limbs = np.array(limbs) - 1 for f, t in limbs: from_missing = kp_array[f][0] == MISSING_VALUE or kp_array[f][1] == MISSING_VALUE to_missing = kp_array[t][0] == MISSING_VALUE or kp_array[t][1] == MISSING_VALUE if from_missing or to_missing: continue norm_vec = kp_array[f] - kp_array[t] norm_vec = np.array([-norm_vec[1], norm_vec[0]]) norm_vec = point_radius * norm_vec / np.linalg.norm(norm_vec) vetexes = np.array([ kp_array[f] + norm_vec, kp_array[f] - norm_vec, kp_array[t] - norm_vec, kp_array[t] + norm_vec ]) yy, xx = polygon(vetexes[:, 0], vetexes[:, 1], shape=img_size) mask[yy, xx] = True for i, joint in enumerate(kp_array): if kp_array[i][0] == MISSING_VALUE or kp_array[i][1] == MISSING_VALUE: continue yy, xx = circle(joint[0], joint[1], radius=point_radius, shape=img_size) mask[yy, xx] = True mask = dilation(mask, square(5)) mask = erosion(mask, square(5)) return mask
Example #10
Source File: segmentation_labelling.py From kaggle-heart with MIT License | 5 votes |
def select_component_sqdist(labeled_regions, num_labels, center, distmat, opening_param = 3.5, do_diler = True): opening_param = int(opening_param) mshape = square(3) # select closest component xmindist = -1 contains_center = False bestcomponent = np.zeros_like(labeled_regions) for lidx in range(num_labels): reg = extract_region(labeled_regions, lidx+1) #smallfilter = ndi.binary_erosion(reg.copy(),structure = mshape,iterations = opening_param) smallfilter = reg # no smallfilter! if smallfilter[smallfilter>0].any(): # throw out tiny regions if do_diler: component=ndi.binary_dilation(reg.copy(),structure = mshape,iterations = opening_param) else: component = reg #dst = np.sum(component*distmat)/np.count_nonzero(component) dst = np.min(component*distmat) if xmindist < 0: xmindist = dst bestcomponent = component.copy() else: if (reg[center] == 1) & (contains_center == False) : contains_center = True xmindist = dst bestcomponent = component.copy() else: if (reg[center] == 1) & (contains_center == True) & (dst < xmindist): xmindist = dst bestcomponent = component.copy() return bestcomponent, labeled_regions
Example #11
Source File: __funcs__.py From porespy with MIT License | 5 votes |
def _get_axial_shifts(ndim=2, include_diagonals=False): r''' Helper function to generate the axial shifts that will be performed on the image to identify bordering pixels/voxels ''' if ndim == 2: if include_diagonals: neighbors = square(3) else: neighbors = diamond(1) neighbors[1, 1] = 0 x, y = np.where(neighbors) x -= 1 y -= 1 return np.vstack((x, y)).T else: if include_diagonals: neighbors = cube(3) else: neighbors = octahedron(1) neighbors[1, 1, 1] = 0 x, y, z = np.where(neighbors) x -= 1 y -= 1 z -= 1 return np.vstack((x, y, z)).T
Example #12
Source File: __funcs__.py From porespy with MIT License | 5 votes |
def reduce_peaks(peaks): r""" Any peaks that are broad or elongated are replaced with a single voxel that is located at the center of mass of the original voxels. Parameters ---------- peaks : ND-image An image containing True values indicating peaks in the distance transform Returns ------- image : ND-array An array with the same number of isolated peaks as the original image, but fewer total voxels. Notes ----- The center of mass of a group of voxels is used as the new single voxel, so if the group has an odd shape (like a horse shoe), the new voxel may *not* lie on top of the original set. """ if peaks.ndim == 2: strel = square else: strel = cube markers, N = spim.label(input=peaks, structure=strel(3)) inds = spim.measurements.center_of_mass(input=peaks, labels=markers, index=np.arange(1, N+1)) inds = np.floor(inds).astype(int) # Centroid may not be on old pixel, so create a new peaks image peaks_new = np.zeros_like(peaks, dtype=bool) peaks_new[tuple(inds.T)] = True return peaks_new
Example #13
Source File: mask_utils.py From SpaceNet_Off_Nadir_Solutions with Apache License 2.0 | 5 votes |
def create_separation(labels): tmp = dilation(labels > 0, square(12)) tmp2 = watershed(tmp, labels, mask=tmp, watershed_line=True) > 0 tmp = tmp ^ tmp2 tmp = dilation(tmp, square(3)) props = measure.regionprops(labels) msk1 = np.zeros_like(labels, dtype='bool') for y0 in range(labels.shape[0]): for x0 in range(labels.shape[1]): if not tmp[y0, x0]: continue if labels[y0, x0] == 0: sz = 5 else: sz = 7 if props[labels[y0, x0] - 1].area < 300: sz = 5 elif props[labels[y0, x0] - 1].area < 2000: sz = 6 uniq = np.unique(labels[max(0, y0 - sz):min(labels.shape[0], y0 + sz + 1), max(0, x0 - sz):min(labels.shape[1], x0 + sz + 1)]) if len(uniq[uniq > 0]) > 1: msk1[y0, x0] = True return msk1
Example #14
Source File: evaluate_curv.py From pytorch_connectomics with MIT License | 5 votes |
def compute_precision_recall(pred, gt): pred_skel = skeletonize(pred) pred_dil = dilation(pred_skel, square(5)) gt_skel = skeletonize(gt) gt_dil = dilation(gt_skel, square(5)) return compute_metrics([pred_skel], [gt_skel], [pred_dil], [gt_dil])
Example #15
Source File: diffraction2d.py From pyxem with GNU General Public License v3.0 | 5 votes |
def remove_background(self, method, **kwargs): """Perform background subtraction via multiple methods. Parameters ---------- method : str Specifies the method, from: {'h-dome','gaussian_difference','median','reference_pattern'} **kwargs: Keyword arguments to be passed to map(), including method specific ones, running a method with no kwargs will return help Returns ------- bg_subtracted : :obj:`ElectronDiffraction2D` A copy of the data with the background subtracted. Be aware that this function will only return inplace. """ method_dict = { "h-dome": regional_filter, "gaussian_difference": subtract_background_dog, "median": subtract_background_median, "reference_pattern": subtract_reference, } method_function = select_method_from_method_dict(method, method_dict, **kwargs) if method != "h-dome": bg_subtracted = self.map(method_function, inplace=False, **kwargs) elif method == "h-dome": scale = self.data.max() self.data = self.data / scale bg_subtracted = self.map(method_function, inplace=False, **kwargs) bg_subtracted.map(filters.rank.mean, selem=square(3)) bg_subtracted.data = bg_subtracted.data / bg_subtracted.data.max() return bg_subtracted
Example #16
Source File: math.py From spinalcordtoolbox with MIT License | 5 votes |
def _get_selem(shape, size, dim): """ Create structuring element of desired shape and radius :param shape: str: Shape of the structuring element. See available options below in the code :param size: int: size of the element. :param dim: {0, 1, 2}: Dimension of the array which 2D structural element will be orthogonal to. For example, if you wish to apply a 2D disk kernel in the X-Y plane, leaving Z unaffected, parameters will be: shape=disk, dim=2. :return: numpy array: structuring element """ # TODO: enable custom selem if shape == 'square': selem = square(size) elif shape == 'cube': selem = cube(size) elif shape == 'disk': selem = disk(size) elif shape == 'ball': selem = ball(size) else: ValueError("This shape is not a valid entry: {}".format(shape)) if not (len(selem.shape) in [2, 3] and selem.shape[0] == selem.shape[1]): raise ValueError("Invalid shape") # If 2d kernel, replicate it along the specified dimension if len(selem.shape) == 2: selem3d = np.zeros([selem.shape[0]]*3) imid = np.floor(selem.shape[0] / 2).astype(int) if dim == 0: selem3d[imid, :, :] = selem elif dim == 1: selem3d[:, imid, :] = selem elif dim == 2: selem3d[:, :, imid] = selem else: raise ValueError("dim can only take values: {0, 1, 2}") selem = selem3d return selem
Example #17
Source File: generate_pose_map_add_mask.py From Human-Pose-Transfer with MIT License | 5 votes |
def key_point_to_mask(key_points, img_size, radius=6): new_points = expand_key_points(key_points, radius) mask = np.zeros(shape=img_size, dtype=bool) for i, joint in enumerate(list(key_points) + new_points): if KEY_POINT_MISSING_VALUE in joint: continue yy, xx = circle(joint[0], joint[1], radius=radius, shape=img_size) mask[yy, xx] = True mask = dilation(mask, square(radius + 3)) mask = erosion(mask, square(radius + 3)) return mask
Example #18
Source File: image.py From PassportEye with MIT License | 5 votes |
def __call__(self, img_small): m = morphology.square(self.square_size) img_th = morphology.black_tophat(img_small, m) img_sob = abs(filters.sobel_v(img_th)) img_closed = morphology.closing(img_sob, m) threshold = filters.threshold_otsu(img_closed) return img_closed > threshold
Example #19
Source File: pose_utils.py From everybody_dance_now_pytorch with GNU Affero General Public License v3.0 | 5 votes |
def produce_ma_mask(kp_array, img_size, point_radius=4): from skimage.morphology import dilation, erosion, square mask = np.zeros(shape=img_size, dtype=bool) limbs = [[2,3], [2,6], [3,4], [4,5], [6,7], [7,8], [2,9], [9,10], [10,11], [2,12], [12,13], [13,14], [2,1], [1,15], [15,17], [1,16], [16,18], [2,17], [2,18], [9,12], [12,6], [9,3], [17,18]] limbs = np.array(limbs) - 1 for f, t in limbs: from_missing = kp_array[f][0] == MISSING_VALUE or kp_array[f][1] == MISSING_VALUE to_missing = kp_array[t][0] == MISSING_VALUE or kp_array[t][1] == MISSING_VALUE if from_missing or to_missing: continue norm_vec = kp_array[f] - kp_array[t] norm_vec = np.array([-norm_vec[1], norm_vec[0]]) norm_vec = point_radius * norm_vec / np.linalg.norm(norm_vec) vetexes = np.array([ kp_array[f] + norm_vec, kp_array[f] - norm_vec, kp_array[t] - norm_vec, kp_array[t] + norm_vec ]) yy, xx = polygon(vetexes[:, 0], vetexes[:, 1], shape=img_size) mask[yy, xx] = True for i, joint in enumerate(kp_array): if kp_array[i][0] == MISSING_VALUE or kp_array[i][1] == MISSING_VALUE: continue yy, xx = circle(joint[0], joint[1], radius=point_radius, shape=img_size) mask[yy, xx] = True mask = dilation(mask, square(5)) mask = erosion(mask, square(5)) return mask
Example #20
Source File: utils.py From pychubby with MIT License | 5 votes |
def points_to_rectangle_mask(shape, top_left, bottom_right, width=1): """Convert two points into a rectangle boolean mask. Parameters ---------- shape : tuple Represents the `(height, width)` of the final mask. top_left : tuple Two element tuple representing `(row, column)` of the top left corner of the inner rectangle. bottom_right : tuple Two element tuple representing `(row, column)` of the bottom right corner of the inner rectangle. width : int Width of the edge of the rectangle. Note that it is generated by dilation. Returns ------- rectangle_mask : np.ndarray Boolean mask of shape `shape` where True entries represent the edge of the rectangle. Notes ----- The output can be easily used for quickly visualizing a rectangle in an image. One simply does something like img[rectangle_mask] = 255. """ if len(shape) != 2: raise ValueError('Only works for 2 dimensional arrays') rectangle_mask = np.zeros(shape, dtype=np.bool) rr, cc = rectangle_perimeter(top_left, bottom_right) rectangle_mask[rr, cc] = True rectangle_mask = dilation(rectangle_mask, square(width)) return rectangle_mask
Example #21
Source File: segmentation_test.py From DRFNS with MIT License | 5 votes |
def get_rough_detection(self, img, bigsize=40.0, smallsize=4.0, thresh = 0): diff = self.difference_of_gaussian(-img, bigsize, smallsize) diff[diff>thresh] = 1 se = morphology.square(4) ero = morphology.erosion(diff, se) labimage = label(ero) #rec = morphology.reconstruction(ero, img, method='dilation').astype(np.dtype('uint8')) # connectivity=1 corresponds to 4-connectivity. morphology.remove_small_objects(labimage, min_size=600, connectivity=1, in_place=True) #res = np.zeros(img.shape) ero[labimage==0] = 0 ero = 1 - ero labimage = label(ero) morphology.remove_small_objects(labimage, min_size=400, connectivity=1, in_place=True) ero[labimage==0] = 0 res = 1 - ero res[res>0] = 255 #temp = 255 - temp #temp = morphology.remove_small_objects(temp, min_size=400, connectivity=1, in_place=True) #res = 255 - temp return res
Example #22
Source File: postprocessing.py From DRFNS with MIT License | 5 votes |
def generate_wsl(ws): """ Generates watershed line that correspond to areas of touching objects. """ se = square(3) ero = ws.copy() ero[ero == 0] = ero.max() + 1 ero = erosion(ero, se) ero[ws == 0] = 0 grad = dilation(ws, se) - ero grad[ws == 0] = 0 grad[grad > 0] = 255 grad = grad.astype(np.uint8) return grad
Example #23
Source File: train_inception_softmax.py From dsb2018_topcoders with MIT License | 4 votes |
def create_mask(labels): labels = measure.label(labels, neighbors=8, background=0) tmp = dilation(labels > 0, square(9)) tmp2 = watershed(tmp, labels, mask=tmp, watershed_line=True) > 0 tmp = tmp ^ tmp2 tmp = dilation(tmp, square(7)) msk = (255 * tmp).astype('uint8') props = measure.regionprops(labels) msk0 = 255 * (labels > 0) msk0 = msk0.astype('uint8') msk1 = np.zeros_like(labels, dtype='bool') max_area = np.max([p.area for p in props]) for y0 in range(labels.shape[0]): for x0 in range(labels.shape[1]): if not tmp[y0, x0]: continue if labels[y0, x0] == 0: if max_area > 4000: sz = 6 else: sz = 3 else: sz = 3 if props[labels[y0, x0] - 1].area < 300: sz = 1 elif props[labels[y0, x0] - 1].area < 2000: sz = 2 uniq = np.unique(labels[max(0, y0-sz):min(labels.shape[0], y0+sz+1), max(0, x0-sz):min(labels.shape[1], x0+sz+1)]) if len(uniq[uniq > 0]) > 1: msk1[y0, x0] = True msk0[y0, x0] = 0 msk1 = 255 * msk1 msk1 = msk1.astype('uint8') msk2 = np.zeros_like(labels, dtype='uint8') msk = np.stack((msk0, msk1, msk2)) msk = np.rollaxis(msk, 0, 3) return msk
Example #24
Source File: diffraction2d.py From pyxem with GNU General Public License v3.0 | 4 votes |
def center_direct_beam( self, method, half_square_width=None, return_shifts=False, align_kwargs={}, *args, **kwargs ): """Estimate the direct beam position in each experimentally acquired electron diffraction pattern and translate it to the center of the image square. Parameters ---------- method : str {'cross_correlate', 'blur', 'interpolate'} Method used to estimate the direct beam position half_square_width : int Half the side length of square that captures the direct beam in all scans. Means that the centering algorithm is stable against diffracted spots brighter than the direct beam. return_shifts : bool, default False If True, the values of applied shifts are returned align_kwargs : dict To be passed to .align2D() function **kwargs: To be passed to method function Returns ------- centered : ElectronDiffraction2D The centered diffraction data. """ nav_size = self.axes_manager.navigation_size signal_shape = self.axes_manager.signal_shape origin_coordinates = np.array(signal_shape) / 2 if half_square_width is not None: min_index = np.int(origin_coordinates[0] - half_square_width) # fails if non-square dp max_index = np.int(origin_coordinates[0] + half_square_width) cropped = self.isig[min_index:max_index, min_index:max_index] shifts = cropped.get_direct_beam_position(method=method, **kwargs) else: shifts = self.get_direct_beam_position(method=method, **kwargs) shifts = -1 * shifts.data shifts = shifts.reshape(nav_size, 2) # Preserve existing behaviour by overriding # crop & fill_value align_kwargs.pop("crop", None) align_kwargs.pop("fill_value", None) self.align2D(shifts=shifts, crop=False, fill_value=0, **align_kwargs) if return_shifts: return shifts
Example #25
Source File: __funcs__.py From porespy with MIT License | 4 votes |
def prune_branches(skel, branch_points=None, iterations=1): r""" Removes all dangling ends or tails of a skeleton. Parameters ---------- skel : ND-image A image of a full or partial skeleton from which the tails should be trimmed. branch_points : ND-image, optional An image the same size ``skel`` with True values indicating the branch points of the skeleton. If this is not provided it is calculated automatically. Returns ------- An ND-image containing the skeleton with tails removed. """ skel = skel > 0 if skel.ndim == 2: from skimage.morphology import square as cube else: from skimage.morphology import cube # Create empty image to house results im_result = np.zeros_like(skel) # If branch points are not supplied, attempt to find them if branch_points is None: branch_points = spim.convolve(skel*1.0, weights=cube(3)) > 3 branch_points = branch_points*skel # Store original branch points before dilating pts_orig = branch_points # Find arcs of skeleton by deleting branch points arcs = skel*(~branch_points) # Label arcs arc_labels = spim.label(arcs, structure=cube(3))[0] # Dilate branch points so they overlap with the arcs branch_points = spim.binary_dilation(branch_points, structure=cube(3)) pts_labels = spim.label(branch_points, structure=cube(3))[0] # Now scan through each arc to see if it's connected to two branch points slices = spim.find_objects(arc_labels) label_num = 0 for s in slices: label_num += 1 # Find branch point labels the overlap current arc hits = pts_labels[s]*(arc_labels[s] == label_num) # If image contains 2 branch points, then it's not a tail. if len(np.unique(hits)) == 3: im_result[s] += arc_labels[s] == label_num # Add missing branch points back to arc image to make complete skeleton im_result += skel*pts_orig if iterations > 1: iterations -= 1 im_temp = np.copy(im_result) im_result = prune_branches(skel=im_result, branch_points=None, iterations=iterations) if np.all(im_temp == im_result): iterations = 0 return im_result
Example #26
Source File: __funcs__.py From porespy with MIT License | 4 votes |
def find_disconnected_voxels(im, conn=None): r""" This identifies all pore (or solid) voxels that are not connected to the edge of the image. This can be used to find blind pores, or remove artifacts such as solid phase voxels that are floating in space. Parameters ---------- im : ND-image A Boolean image, with True values indicating the phase for which disconnected voxels are sought. conn : int For 2D the options are 4 and 8 for square and diagonal neighbors, while for the 3D the options are 6 and 26, similarily for square and diagonal neighbors. The default is max Returns ------- image : ND-array An ND-image the same size as ``im``, with True values indicating voxels of the phase of interest (i.e. True values in the original image) that are not connected to the outer edges. Notes ----- image : ND-array The returned array (e.g. ``holes``) be used to trim blind pores from ``im`` using: ``im[holes] = False`` """ if im.ndim != im.squeeze().ndim: warnings.warn('Input image conains a singleton axis:' + str(im.shape) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.') if im.ndim == 2: if conn == 4: strel = disk(1) elif conn in [None, 8]: strel = square(3) elif im.ndim == 3: if conn == 6: strel = ball(1) elif conn in [None, 26]: strel = cube(3) labels, N = spim.label(input=im, structure=strel) holes = clear_border(labels=labels) > 0 return holes
Example #27
Source File: utils.py From Pose-Guided-Person-Image-Generation with MIT License | 4 votes |
def _getPoseMask(peaks, height, width, radius=4, var=4, mode='Solid'): ## MSCOCO Pose part_str = [nose, neck, Rsho, Relb, Rwri, Lsho, Lelb, Lwri, Rhip, Rkne, Rank, Lhip, Lkne, Lank, Leye, Reye, Lear, Rear, pt19] # find connection in the specified sequence, center 29 is in the position 15 # limbSeq = [[2,3], [2,6], [3,4], [4,5], [6,7], [7,8], [2,9], [9,10], \ # [10,11], [2,12], [12,13], [13,14], [2,1], [1,15], [15,17], \ # [1,16], [16,18], [3,17], [6,18]] # limbSeq = [[2,3], [2,6], [3,4], [4,5], [6,7], [7,8], [2,9], [9,10], \ # [10,11], [2,12], [12,13], [13,14], [2,1], [1,15], [15,17], \ # [1,16], [16,18]] # , [9,12] # limbSeq = [[3,4], [4,5], [6,7], [7,8], [9,10], \ # [10,11], [12,13], [13,14], [2,1], [1,15], [15,17], \ # [1,16], [16,18]] # limbSeq = [[2,3], [2,6], [3,4], [4,5], [6,7], [7,8], [2,9], [9,10], \ [10,11], [2,12], [12,13], [13,14], [2,1], [1,15], [15,17], \ [1,16], [16,18], [2,17], [2,18], [9,12], [12,6], [9,3], [17,18]] # indices = [] values = [] for limb in limbSeq: p0 = peaks[limb[0] -1] p1 = peaks[limb[1] -1] if 0!=len(p0) and 0!=len(p1): r0 = p0[0][1] c0 = p0[0][0] r1 = p1[0][1] c1 = p1[0][0] ind, val = _getSparseKeypoint(r0, c0, 0, height, width, radius, var, mode) indices.extend(ind) values.extend(val) ind, val = _getSparseKeypoint(r1, c1, 0, height, width, radius, var, mode) indices.extend(ind) values.extend(val) distance = np.sqrt((r0-r1)**2 + (c0-c1)**2) sampleN = int(distance/radius) # sampleN = 0 if sampleN>1: for i in xrange(1,sampleN): r = r0 + (r1-r0)*i/sampleN c = c0 + (c1-c0)*i/sampleN ind, val = _getSparseKeypoint(r, c, 0, height, width, radius, var, mode) indices.extend(ind) values.extend(val) shape = [height, width, 1] ## Fill body dense = np.squeeze(_sparse2dense(indices, values, shape)) ## TODO # im = Image.fromarray((dense*255).astype(np.uint8)) # im.save('xxxxx.png') # pdb.set_trace() dense = dilation(dense, square(5)) dense = erosion(dense, square(5)) return dense
Example #28
Source File: ridge_map.py From ridge_map with MIT License | 4 votes |
def preprocess( self, *, values=None, water_ntile=10, lake_flatness=3, vertical_ratio=40 ): """Get map data ready for plotting. You can do this yourself, and pass an array directly to plot_map. This gathers all nan values, the lowest `water_ntile` percentile of elevations, and anything that is flat enough, and sets the values to `nan`, so no line is drawn. It also exaggerates the vertical scale, which can be nice for flat or mountainy areas. Parameters ---------- values : np.ndarray An array to process, or fetch the elevation data lazily here. water_ntile : float in [0, 100] Percentile below which to delete data. Useful for coasts or rivers. Set to 0 to not delete any data. lake_flatness : int How much the elevation can change within 3 squares to delete data. Higher values delete more data. Useful for rivers, lakes, oceans. vertical_ratio : float > 0 How much to exaggerate hills. Kind of arbitrary. 40 is reasonable, but try bigger and smaller values! Returns ------- np.ndarray Processed data. """ if values is None: values = self.get_elevation_data() nan_vals = np.isnan(values) values[nan_vals] = np.nanmin(values) values = (values - np.min(values)) / (np.max(values) - np.min(values)) is_water = values < np.percentile(values, water_ntile) is_lake = rank.gradient(img_as_ubyte(values), square(3)) < lake_flatness values[nan_vals] = np.nan values[np.logical_or(is_water, is_lake)] = np.nan values = vertical_ratio * values[-1::-1] # switch north and south return values # pylint: disable=too-many-arguments,too-many-locals
Example #29
Source File: convert_RCV.py From Pose-Guided-Person-Image-Generation with MIT License | 4 votes |
def _getPoseMask_COCO(RCV, height, width, radius=4, var=4, mode='Solid'): ## MSCOCO Pose part_str = [nose, neck, Rsho, Relb, Rwri, Lsho, Lelb, Lwri, Rhip, Rkne, Rank, Lhip, Lkne, Lank, Leye, Reye, Lear, Rear, pt19] # find connection in the specified sequence, center 29 is in the position 15 # limbSeq = [[2,3], [2,6], [3,4], [4,5], [6,7], [7,8], [2,9], [9,10], \ # [10,11], [2,12], [12,13], [13,14], [2,1], [1,15], [15,17], \ # [1,16], [16,18], [3,17], [6,18]] # limbSeq = [[2,3], [2,6], [3,4], [4,5], [6,7], [7,8], [2,9], [9,10], \ # [10,11], [2,12], [12,13], [13,14], [2,1], [1,15], [15,17], \ # [1,16], [16,18]] # , [9,12] # limbSeq = [[3,4], [4,5], [6,7], [7,8], [9,10], \ # [10,11], [12,13], [13,14], [2,1], [1,15], [15,17], \ # [1,16], [16,18]] # limbSeq = [[2,3], [2,6], [3,4], [4,5], [6,7], [7,8], [2,9], [9,10], \ [10,11], [2,12], [12,13], [13,14], [2,1], [1,15], [15,17], \ [1,16], [16,18], [2,17], [2,18], [9,12], [12,6], [9,3], [17,18]] # indices = [] values = [] for limb in limbSeq: r0,c0,v0 = RCV[limb[0]-1, :] r1,c1,v1 = RCV[limb[1]-1, :] if 0!=v0 and 0!=v1: ind, val = _getSparseKeypoint(r0, c0, 0, height, width, radius, var, mode) indices.extend(ind) values.extend(val) ind, val = _getSparseKeypoint(r1, c1, 0, height, width, radius, var, mode) indices.extend(ind) values.extend(val) distance = np.sqrt((r0-r1)**2 + (c0-c1)**2) sampleN = int(distance/radius) if sampleN>1: for i in xrange(1,sampleN): r = r0 + (r1-r0)*i/sampleN c = c0 + (c1-c0)*i/sampleN ind, val = _getSparseKeypoint(r, c, 0, height, width, radius, var, mode) indices.extend(ind) values.extend(val) shape = [height, width, 1] ## Fill body dense = np.squeeze(_sparse2dense(indices, values, shape)) dense = dilation(dense, square(5)) dense = erosion(dense, square(5)) return dense
Example #30
Source File: dsb_binary.py From dsb2018_topcoders with MIT License | 4 votes |
def create_mask(self, labels): labels = measure.label(labels, neighbors=8, background=0) tmp = dilation(labels > 0, square(9)) tmp2 = watershed(tmp, labels, mask=tmp, watershed_line=True) > 0 tmp = tmp ^ tmp2 tmp = dilation(tmp, square(7)) msk = (255 * tmp).astype('uint8') props = measure.regionprops(labels) msk0 = 255 * (labels > 0) msk0 = msk0.astype('uint8') msk1 = np.zeros_like(labels, dtype='bool') max_area = np.max([p.area for p in props]) for y0 in range(labels.shape[0]): for x0 in range(labels.shape[1]): if not tmp[y0, x0]: continue if labels[y0, x0] == 0: if max_area > 4000: sz = 6 else: sz = 3 else: sz = 3 if props[labels[y0, x0] - 1].area < 300: sz = 1 elif props[labels[y0, x0] - 1].area < 2000: sz = 2 uniq = np.unique(labels[max(0, y0 - sz):min(labels.shape[0], y0 + sz + 1), max(0, x0 - sz):min(labels.shape[1], x0 + sz + 1)]) if len(uniq[uniq > 0]) > 1: msk1[y0, x0] = True msk0[y0, x0] = 0 msk1 = 255 * msk1 msk1 = msk1.astype('uint8') msk2 = np.zeros_like(labels, dtype='uint8') msk = np.stack((msk0, msk1, msk2)) msk = np.rollaxis(msk, 0, 3) return msk