本文整理汇总了Python中skimage.morphology.disk方法的典型用法代码示例。如果您正苦于以下问题:Python morphology.disk方法的具体用法?Python morphology.disk怎么用?Python morphology.disk使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类skimage.morphology
的用法示例。
在下文中一共展示了morphology.disk方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: addNoiseAndGray
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [as 别名]
def addNoiseAndGray(surf):
# https://stackoverflow.com/questions/34673424/how-to-get-numpy-array-of-rgb-colors-from-pygame-surface
imgdata = pygame.surfarray.array3d(surf)
imgdata = imgdata.swapaxes(0, 1)
# print('imgdata shape %s' % imgdata.shape) # shall be IMG_HEIGHT * IMG_WIDTH
imgdata2 = noise_generator('s&p', imgdata)
img2 = Image.fromarray(np.uint8(imgdata2))
# img2.save('/home/zhichyu/Downloads/2sp.jpg')
grayscale2 = ImageOps.grayscale(img2)
# grayscale2.save('/home/zhichyu/Downloads/2bw2.jpg')
# return grayscale2
array = np.asarray(np.uint8(grayscale2))
# print('array.shape %s' % array.shape)
selem = disk(random.randint(0, 1))
eroded = erosion(array, selem)
return eroded
示例2: dilation
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [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
示例3: dilate
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [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)
示例4: erode
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [as 别名]
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)
示例5: get_diffraction_test_image
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [as 别名]
def get_diffraction_test_image(self, dtype=np.float32):
image_x, image_y = self.image_x, self.image_y
cx, cy = image_x / 2, image_y / 2
image = np.zeros((image_y, image_x), dtype=np.float32)
iterator = zip(self._x_list, self._y_list, self._intensity_list)
for x, y, i in iterator:
if self.diff_intensity_reduction is not False:
dr = np.hypot(x - cx, y - cy)
i = self._get_diff_intensity_reduction(dr, i)
image[y, x] = i
disk = morphology.disk(self.disk_r, dtype=dtype)
image = convolve2d(image, disk, mode="same")
if self.rotation != 0:
image = rotate(image, self.rotation, reshape=False)
if self.blur != 0:
image = gaussian_filter(image, self.blur)
if self._background_lorentz_width is not False:
image += self._get_background_lorentz()
if self.intensity_noise is not False:
noise = np.random.random((image_y, image_x)) * self.intensity_noise
image += noise
return image
示例6: test_correct_disk_x_y_and_radius_random
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [as 别名]
def test_correct_disk_x_y_and_radius_random(self):
x, y, px, py = 56, 48, 4, 5
x, y = randint(45, 55, size=(py, px)), randint(45, 55, size=(py, px))
r = randint(20, 40, size=(py, px))
s = mdtd.generate_4d_data(
probe_size_x=px,
probe_size_y=py,
image_size_x=120,
image_size_y=100,
disk_x=x,
disk_y=y,
disk_r=5,
disk_I=20,
ring_x=x,
ring_y=y,
ring_r=r,
ring_I=5,
blur=True,
downscale=False,
)
s_com = s.center_of_mass()
s_r = s.radial_average(centre_x=s_com.inav[0].data, centre_y=s_com.inav[1].data)
s_r = s_r.isig[15:] # Do not include the disk
r -= 15 # Need to shift the radius, due to not including the disk
assert (s_r.data.argmax(axis=-1) == r).all()
示例7: masked
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [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
示例8: _get_blob_mask
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [as 别名]
def _get_blob_mask(ROI_image, thresh, thresh_block_size, is_light_background, analysis_type):
# get binary image,
if is_light_background:
## apply a median filter to reduce rough edges / sharpen the boundary btw worm and background
ROI_image_th = cv2.medianBlur(ROI_image, 3)
ROI_mask = ROI_image_th < thresh
else:
if analysis_type == "PHARYNX":
# for fluorescent pharynx labeled images, refine the threshold with a local otsu (http://scikit-image.org/docs/dev/auto_examples/plot_local_otsu.html)
# this compensates for local variations in brightness in high density regions, when many worms are close to each other
ROI_rank_otsu = skf.rank.otsu(ROI_image, skm.disk(thresh_block_size))
ROI_mask = (ROI_image>ROI_rank_otsu)
# as a local threshold introcudes artifacts at the edge of the mask, also use a global threshold to cut these out
ROI_mask &= (ROI_image>=thresh)
else:
# this case applies for example to worms where the whole body is fluorecently labeled
ROI_image_th = cv2.medianBlur(ROI_image, 3)
ROI_mask = ROI_image_th >= thresh
ROI_mask &= (ROI_image != 0)
ROI_mask = ROI_mask.astype(np.uint8)
return ROI_mask, thresh # returning thresh here seems redundant, as it isn't actually changed
示例9: get_dark_mask
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [as 别名]
def get_dark_mask(full_data):
#get darker objects that are unlikely to be worm
if full_data.shape[0] < 2:
#nothing to do here returning
return np.zeros((full_data.shape[1], full_data.shape[2]), np.uint8)
#this mask shoulnd't contain many worms
img_h = cv2.medianBlur(np.max(full_data, axis=0), 5)
#this mask is likely to contain a lot of worms
img_l = cv2.medianBlur(np.min(full_data, axis=0), 5)
#this is the difference (the tagged pixels should be mostly worms)
img_del = img_h-img_l
th_d = threshold_otsu(img_del)
#this is the maximum of the minimum pixels of the worms...
th = np.max(img_l[img_del>th_d])
#this is what a darkish mask should look like
dark_mask = cv2.dilate((img_h<th).astype(np.uint8), disk(11))
return dark_mask
示例10: local_max_roll
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [as 别名]
def local_max_roll(fm, k0, k1, diff):
max_ls = []
for ksize in range(k0, k1):
selem = disk(ksize)
fm_max = local_max(fm, selem, diff)
max_ls.append(fm_max)
lmax = (np.stack(max_ls, axis=0).sum(axis=0) > 0).astype(np.uint8)
nlab, max_lab = cv2.connectedComponents(lmax)
max_res = np.zeros_like(lmax)
for lb in range(1, nlab):
area = max_lab == lb
if np.sum(area) > 1:
crds = tuple(int(np.median(c)) for c in np.where(area))
max_res[crds] = 1
else:
max_res[np.where(area)] = 1
return max_res
示例11: finalProcessingSpur
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [as 别名]
def finalProcessingSpur(s, params):
logging.info(f"{s['filename']} - \tfinalProcessingSpur")
disk_radius = int(params.get("disk_radius", "25"))
selem = disk(disk_radius)
mask = s["img_mask_use"]
mask_opened = binary_opening(mask, selem)
mask_spur = ~mask_opened & mask
io.imsave(s["outdir"] + os.sep + s["filename"] + "_spur.png", img_as_ubyte(mask_spur))
prev_mask = s["img_mask_use"]
s["img_mask_use"] = mask_opened
s.addToPrintList("spur_pixels",
printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))
if len(s["img_mask_use"].nonzero()[0]) == 0: # add warning in case the final tissue is empty
logging.warning(
f"{s['filename']} - After BasicModule.finalProcessingSpur NO tissue remains detectable! Downstream modules likely to be incorrect/fail")
s["warnings"].append(
f"After BasicModule.finalProcessingSpur NO tissue remains detectable! Downstream modules likely to be incorrect/fail")
示例12: ps_disk
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [as 别名]
def ps_disk(radius):
r"""
Creates circular disk structuring element for morphological operations
Parameters
----------
radius : float or int
The desired radius of the structuring element
Returns
-------
strel : 2D-array
A 2D numpy bool array of the structring element
"""
rad = int(np.ceil(radius))
other = np.ones((2 * rad + 1, 2 * rad + 1), dtype=bool)
other[rad, rad] = False
disk = spim.distance_transform_edt(other) < radius
return disk
示例13: make_boundaries
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [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: save_array_as_image
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [as 别名]
def save_array_as_image(array, path, geotransform, projection, format = "GTiff"):
"""
Saves a given array as a geospatial image to disk in the format 'format'. The datatype will be of one corresponding
to
Array must be gdal format: [bands, y, x].
Parameters
----------
array
A Numpy array containing the values to be saved to a raster
path
The path to the location to save the output raster to
geotransform
The geotransform of the image to be saved. See note.
projection
The projection, as wkt, of the image to be saved. See note.
format
Returns
-------
"""
driver = gdal.GetDriverByName(format)
type_code = gdal_array.NumericTypeCodeToGDALTypeCode(array.dtype)
# If array is 2d, give it an extra dimension.
if len(array.shape) == 2:
array = np.expand_dims(array, axis=0)
out_dataset = driver.Create(
path,
xsize=array.shape[2],
ysize=array.shape[1],
bands=array.shape[0],
eType=type_code
)
out_dataset.SetGeoTransform(geotransform)
out_dataset.SetProjection(projection)
out_array = out_dataset.GetVirtualMemArray(eAccess=gdal.GA_Update).squeeze()
out_array[...] = array
out_array = None
out_dataset = None
return path
示例15: buffer_mask_in_place
# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import disk [as 别名]
def buffer_mask_in_place(mask_path, buffer_size):
"""Expands a mask in-place, overwriting the previous mask"""
log = logging.getLogger(__name__)
log.info("Buffering {} with buffer size {}".format(mask_path, buffer_size))
mask = gdal.Open(mask_path, gdal.GA_Update)
mask_array = mask.GetVirtualMemArray(eAccess=gdal.GA_Update)
cache = morph.binary_erosion(mask_array.squeeze(), selem=morph.disk(buffer_size))
np.copyto(mask_array, cache)
mask_array = None
mask = None