本文整理匯總了Python中skimage.morphology.dilation方法的典型用法代碼示例。如果您正苦於以下問題:Python morphology.dilation方法的具體用法?Python morphology.dilation怎麽用?Python morphology.dilation使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類skimage.morphology
的用法示例。
在下文中一共展示了morphology.dilation方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: dilation
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
def dilation(x, radius=3):
""" Return greyscale morphological dilation of an image,
see `skimage.morphology.dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.dilation>`_.
Parameters
-----------
x : 2D array image.
radius : int for the radius of mask.
"""
from skimage.morphology import disk, dilation
mask = disk(radius)
x = dilation(x, selem=mask)
return x
## Sequence
示例2: threshold_segmentation
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
def threshold_segmentation(img):
# calculate the overview level size and retrieve the image
img_hsv = img.convert('HSV')
img_hsv_np = np.array(img_hsv)
# dilate image and then threshold the image
schannel = img_hsv_np[:, :, 1]
mask = np.zeros(schannel.shape)
schannel = dilation(schannel, star(3))
schannel = ndimage.gaussian_filter(schannel, sigma=(5, 5), order=0)
threshold_global = threshold_otsu(schannel)
mask[schannel > threshold_global] = FOREGROUND
mask[schannel <= threshold_global] = BACKGROUND
return mask
示例3: generate_wsl
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
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
示例4: dilate
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
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)
示例5: thicken_drawings
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
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
示例6: smooth_edge
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
def smooth_edge(self, data):
smoothed_label = data['label'].copy()
for z in range(smoothed_label.shape[0]):
temp = smoothed_label[z].copy()
for idx in np.unique(temp):
if idx != 0:
binary = (temp==idx).astype(np.uint8)
for _ in range(2):
binary = dilation(binary)
binary = gaussian(binary, sigma=2, preserve_range=True)
binary = dilation(binary)
binary = (binary > 0.8).astype(np.uint8)
temp[np.where(temp==idx)]=0
temp[np.where(binary==1)]=idx
smoothed_label[z] = temp
data['label'] = smoothed_label
return data
示例7: overlay_cut_masks
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
def overlay_cut_masks(images_dir, subdir_name, target_dir, cut_size=1):
train_dir = os.path.join(images_dir, subdir_name)
for mask_dirname in tqdm(glob.glob('{}/*/masks'.format(train_dir))):
masks = []
for ind, image_filepath in enumerate(glob.glob('{}/*'.format(mask_dirname))):
image = np.asarray(Image.open(image_filepath))
image = np.where(image > 0, ind + 1, 0)
masks.append(image)
labeled_masks = np.sum(masks, axis=0)
overlayed_masks = np.where(labeled_masks, 1, 0)
watershed_mask = watershed(overlayed_masks.astype(np.bool), labeled_masks, watershed_line=True)
if watershed_mask.max() == watershed_mask.min():
cut_masks = overlayed_masks
else:
borders = (watershed_mask == 0) & overlayed_masks
selem = rectangle(cut_size, cut_size)
dilated_borders = dilation(borders, selem=selem)
cut_masks = np.where(dilated_borders, 0, overlayed_masks)
target_filepath = '/'.join(mask_dirname.replace(images_dir, target_dir).split('/')[:-1]) + '.png'
os.makedirs(os.path.dirname(target_filepath), exist_ok=True)
imwrite(target_filepath, cut_masks)
示例8: masked
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
def masked(img, gt, mask, alpha=1):
"""Returns image with GT lung field outlined with red, predicted lung field
filled with blue."""
rows, cols = img.shape[:2]
color_mask = np.zeros((rows, cols, 3))
boundary = morphology.dilation(gt, morphology.disk(3)) ^ gt
color_mask[mask == 1] = [0, 0, 1]
color_mask[boundary == 1] = [1, 0, 0]
img_hsv = color.rgb2hsv(img)
color_mask_hsv = color.rgb2hsv(color_mask)
img_hsv[..., 0] = color_mask_hsv[..., 0]
img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha
img_masked = color.hsv2rgb(img_hsv)
return img_masked
示例9: dilate_image
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
def dilate_image(mask, dilate_selem_size):
"""Dilate mask.
Args:
mask (numpy.ndarray): Mask of shape (H x W) or multiple masks of shape (C x H x W).
dilate_selem_size (int): Size of rectangle structuring element used for dilation.
Returns:
numpy.ndarray: dilated Mask of shape (H x W) or multiple masks of shape (C x H x W).
"""
if not dilate_selem_size > 0:
return mask
selem = rectangle(dilate_selem_size, dilate_selem_size)
if mask.ndim == 2:
dilated_image = dilation(mask, selem=selem)
else:
dilated_image = []
for category_mask in mask:
dilated_image.append(dilation(category_mask, selem=selem))
dilated_image = np.stack(dilated_image)
return dilated_image
示例10: get_mask_from_prob
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
def get_mask_from_prob(self, cloud_probs, threshold=None):
"""
Returns cloud mask by applying morphological operations -- convolution and dilation --
to input cloud probabilities.
:param cloud_probs: cloud probability map
:type cloud_probs: numpy array of cloud probabilities (shape n_images x n x m)
:param threshold: A float from [0,1] specifying threshold
:type threshold: float
:return: raster cloud mask
:rtype: numpy array (shape n_images x n x m)
"""
threshold = self.threshold if threshold is None else threshold
if self.average_over:
cloud_masks = np.asarray([convolve(cloud_prob, self.conv_filter) > threshold
for cloud_prob in cloud_probs], dtype=np.int8)
else:
cloud_masks = (cloud_probs > threshold).astype(np.int8)
if self.dilation_size:
cloud_masks = np.asarray([dilation(cloud_mask, self.dilation_filter) for cloud_mask in cloud_masks],
dtype=np.int8)
return cloud_masks
示例11: masked
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
def masked(img, gt, mask, alpha=1):
"""Returns image with GT lung field outlined with red, predicted lung field
filled with blue."""
rows, cols = img.shape
color_mask = np.zeros((rows, cols, 3))
boundary = morphology.dilation(gt, morphology.disk(3)) - gt
color_mask[mask == 1] = [0, 0, 1]
color_mask[boundary == 1] = [1, 0, 0]
img_color = np.dstack((img, img, img))
img_hsv = color.rgb2hsv(img_color)
color_mask_hsv = color.rgb2hsv(color_mask)
img_hsv[..., 0] = color_mask_hsv[..., 0]
img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha
img_masked = color.hsv2rgb(img_hsv)
return img_masked
示例12: save_prediction_image
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
def save_prediction_image(_, panoptic_pred, img_info, out_dir, colors, num_stuff):
msk, cat, obj, iscrowd = panoptic_pred
img = Image.open(img_info["abs_path"])
# Prepare folders and paths
folder, img_name = path.split(img_info["rel_path"])
img_name, _ = path.splitext(img_name)
out_dir = path.join(out_dir, folder)
ensure_dir(out_dir)
out_path = path.join(out_dir, img_name + ".jpg")
# Render semantic
sem = cat[msk].numpy()
crowd = iscrowd[msk].numpy()
sem[crowd == 1] = 255
sem_img = Image.fromarray(colors[sem])
sem_img = sem_img.resize(img_info["original_size"][::-1])
# Render contours
is_background = (sem < num_stuff) | (sem == 255)
msk = msk.numpy()
msk[is_background] = 0
contours = find_boundaries(msk, mode="outer", background=0).astype(np.uint8) * 255
contours = dilation(contours)
contours = np.expand_dims(contours, -1).repeat(4, -1)
contours_img = Image.fromarray(contours, mode="RGBA")
contours_img = contours_img.resize(img_info["original_size"][::-1])
# Compose final image and save
out = Image.blend(img, sem_img, 0.5).convert(mode="RGBA")
out = Image.alpha_composite(out, contours_img)
out.convert(mode="RGB").save(out_path)
示例13: make_boundaries
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
def make_boundaries(label, thickness=None):
"""
Input is an image label, output is a numpy array mask encoding the boundaries of the objects
Extract pixels at the true boundary by dilation - erosion of label.
Don't just pick the void label as it is not exclusive to the boundaries.
"""
assert(thickness is not None)
import skimage.morphology as skm
void = 255
mask = np.logical_and(label > 0, label != void)[0]
selem = skm.disk(thickness)
boundaries = np.logical_xor(skm.dilation(mask, selem),
skm.erosion(mask, selem))
return boundaries
示例14: key_point_to_mask
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
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
示例15: produce_ma_mask
# 需要導入模塊: from skimage import morphology [as 別名]
# 或者: from skimage.morphology import dilation [as 別名]
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