本文整理汇总了Python中skimage.segmentation.slic方法的典型用法代码示例。如果您正苦于以下问题:Python segmentation.slic方法的具体用法?Python segmentation.slic怎么用?Python segmentation.slic使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类skimage.segmentation
的用法示例。
在下文中一共展示了segmentation.slic方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getSuperpixels
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def getSuperpixels(depth, normal, width, height, numPlanes=50, numGlobalPlanes = 10):
depth = np.expand_dims(depth, -1)
urange = (np.arange(width, dtype=np.float32) / (width + 1) - 0.5) / focalLength * 641
urange = np.tile(np.reshape(urange, [1, -1]), [height, 1])
vrange = (np.arange(height, dtype=np.float32) / (height + 1) - 0.5) / focalLength * 481
vrange = np.tile(np.reshape(vrange, [-1, 1]), [1, width])
ranges = np.stack([urange, np.ones([height, width]), -vrange], axis=2)
#ranges = np.expand_dims(ranges, 0)
planeImage = np.sum(normal * ranges, axis=2, keepdims=True) * depth * normal
planeImage = planeImage / 10 * 1000
superpixels = segmentation.slic(planeImage, compactness=30, n_segments=400)
g = graph.rag_mean_color(planeImage, superpixels, mode='similarity')
planeSegmentation = graph.cut_normalized(superpixels, g)
return planeSegmentation, superpixels
示例2: getSuperpixels
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def getSuperpixels(depth, normal, width, height, numPlanes=50, numGlobalPlanes = 10):
depth = np.expand_dims(depth, -1)
urange = (np.arange(width, dtype=np.float32) / (width + 1) - 0.5) / focalLength * 641
urange = np.tile(np.reshape(urange, [1, -1]), [height, 1])
vrange = (np.arange(height, dtype=np.float32) / (height + 1) - 0.5) / focalLength * 481
vrange = np.tile(np.reshape(vrange, [-1, 1]), [1, width])
ranges = np.stack([urange, np.ones([height, width]), -vrange], axis=2)
#ranges = np.expand_dims(ranges, 0)
planeImage = np.sum(normal * ranges, axis=2, keepdims=True) * depth * normal
planeImage = planeImage / 10 * 1000
superpixels = segmentation.slic(planeImage, compactness=30, n_segments=400)
g = graph.rag_mean_color(planeImage, superpixels, mode='similarity')
planeSegmentation = graph.cut_normalized(superpixels, g)
return planeSegmentation, superpixels
示例3: __call__
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def __call__(self, clip):
is_PIL = isinstance(clip[0], PIL.Image.Image)
if is_PIL:
clip = [np.asarray(img) for img in clip]
# TODO this results in an error when n_segments is 0
replace_samples = np.tile(np.array([self.p_replace]), self.n_segments)
avg_image = np.mean(clip, axis=0)
segments = segmentation.slic(avg_image, n_segments=self.n_segments,
compactness=10)
if not np.max(replace_samples) == 0:
print("Converting")
clip = [self._apply_segmentation(img, replace_samples, segments) for img in clip]
if is_PIL:
return [PIL.Image.fromarray(img) for img in clip]
else:
return clip
示例4: _apply_segmentation
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def _apply_segmentation(self, image, replace_samples, segments):
nb_channels = image.shape[2]
image_sp = np.copy(image)
for c in range(nb_channels):
# segments+1 here because otherwise regionprops always misses
# the last label
regions = measure.regionprops(segments + 1,
intensity_image=image[..., c])
for ridx, region in enumerate(regions):
# with mod here, because slic can sometimes create more
# superpixel than requested. replace_samples then does
# not have enough values, so we just start over with the
# first one again.
if replace_samples[ridx % len(replace_samples)] == 1:
mean_intensity = region.mean_intensity
image_sp_c = image_sp[..., c]
image_sp_c[segments == ridx] = mean_intensity
return image_sp
示例5: spectral_cluster
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def spectral_cluster(filename, compactness_val=30, n=6):
'''
Apply spectral clustering to a given image using k-means clustering and
display results.
Args:
filename: name of the image to segment.
compactness_val: Controls the "boxyness" of each segment. Higher values
mean a more boxed shape.
n = number of clusters.
'''
img = misc.imread(filename)
labels1 = segmentation.slic(img, compactness=compactness_val, n_segments=n)
out1 = color.label2rgb(labels1, img, kind='overlay', colors=['red','green','blue','cyan','magenta','yellow'])
fig, ax = plt.subplots()
ax.imshow(out1, interpolation='nearest')
ax.set_title("Compactness: {} | Segments: {}".format(compactness_val, n))
plt.show()
示例6: experiment_with_parameters
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def experiment_with_parameters():
'''
Apply spectral clustering to test wheat image using k-means clustering with
different values of k and different compactness values.
Saves the results to the Clusters folder for inspection.
'''
img = misc.imread("../Assets/wheat.png")
compactness_values = [30, 50, 70, 100, 200, 300, 500, 700, 1000]
n_segments_values = [3,4,5,6,7,8,9,10]
for compactness_val in compactness_values:
for n in n_segments_values:
labels1 = segmentation.slic(img, compactness=compactness_val, n_segments=n)
out1 = color.label2rgb(labels1, img, kind='overlay')
fig, ax = plt.subplots()
ax.imshow(out1, interpolation='nearest')
ax.set_title("Compactness: {} | Segments: {}".format(compactness_val, n))
plt.savefig("../Clusters/c{}_k{}.png".format(compactness_val, n))
plt.close(fig)
示例7: experiment_with_parameters
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def experiment_with_parameters():
img = misc.imread("wheat.png")
compactness_values = [30, 50, 70, 100, 200, 300, 500, 700, 1000]
n_segments_values = [3,4,5,6,7,8,9,10]
for compactness_val in compactness_values:
for n in n_segments_values:
labels1 = segmentation.slic(img, compactness=compactness_val, n_segments=n)
out1 = color.label2rgb(labels1, img, kind='overlay')
fig, ax = plt.subplots()
ax.imshow(out1, interpolation='nearest')
ax.set_title("Compactness: {} | Segments: {}".format(compactness_val, n))
plt.savefig("RAG/c{}_k{}.png".format(compactness_val, n))
plt.close(fig)
示例8: __init__
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def __init__(self, add_seg=False, add_img=False, **kwargs):
if slic is None:
raise ImportError('`ToSlic` requires `scikit-image`.')
self.add_seg = add_seg
self.add_img = add_img
self.kwargs = kwargs
示例9: __call__
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def __call__(self, img):
img = img.permute(1, 2, 0)
h, w, c = img.size()
seg = slic(img.to(torch.double).numpy(), **self.kwargs)
seg = torch.from_numpy(seg)
x = scatter_mean(img.view(h * w, c), seg.view(h * w), dim=0)
pos_y = torch.arange(h, dtype=torch.float)
pos_y = pos_y.view(-1, 1).repeat(1, w).view(h * w)
pos_x = torch.arange(w, dtype=torch.float)
pos_x = pos_x.view(1, -1).repeat(h, 1).view(h * w)
pos = torch.stack([pos_x, pos_y], dim=-1)
pos = scatter_mean(pos, seg.view(h * w), dim=0)
data = Data(x=x, pos=pos)
if self.add_seg:
data.seg = seg.view(1, h, w)
if self.add_img:
data.img = img.permute(2, 0, 1).view(1, c, h, w)
return data
示例10: slic
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def slic(image, num_segments=NUM_SEGMENTS, compactness=COMPACTNESS,
max_iterations=MAX_ITERATIONS, sigma=SIGMA,
min_size_factor=MIN_SIZE_FACTOR, max_size_factor=MAX_SIZE_FACTOR,
enforce_connectivity=CONNECTIVITY):
"""Segments an image using k-means clustering in Color-(x,y,z) space.
Args:
image: The image.
num_segments: The (approiximate) number of segments in the segmented
output image (optional).
compactness: Balances color-space proximity and image-space-proximity.
Higher values give more weight to image-space proximity (optional).
max_iterations: Maximum number of iterations of k-means.
sigma: Width of Gaussian kernel used in preprocessing (optional).
min_size_factor: Proportion of the minimum segment size to be removed
with respect to the supposed segment size
`depth*width*height/num_segments` (optional).
max_size_factor: Proportion of the maximum connected segment size
(optional).
enforce_connectivitiy: Whether the generated segments are connected or
not (optional).
Returns:
Integer mask indicating segment labels.
"""
image = tf.cast(image, tf.uint8)
def _slic(image):
segmentation = skimage_slic(image, num_segments, compactness,
max_iterations, sigma,
min_size_factor=min_size_factor,
max_size_factor=max_size_factor,
enforce_connectivity=enforce_connectivity,
slic_zero=False)
return segmentation.astype(np.int32)
return tf.py_func(_slic, [image], tf.int32, stateful=False, name='slic')
示例11: slico
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def slico(image, num_segments=NUM_SEGMENTS, compactness=COMPACTNESS,
max_iterations=MAX_ITERATIONS, sigma=SIGMA,
min_size_factor=MIN_SIZE_FACTOR, max_size_factor=MAX_SIZE_FACTOR,
enforce_connectivity=CONNECTIVITY):
"""Segments an image using k-means clustering in Color-(x,y,z) space.
Args:
image: The image.
num_segments: The (approiximate) number of segments in the segmented
output image (optional).
compactness: Initial value to balance color-space proximity and
image-space-proximity. Higher values give more weight to image-space
proximity (optional).
max_iterations: Maximum number of iterations of k-means.
sigma: Width of Gaussian kernel used in preprocessing (optional).
min_size_factor: Proportion of the minimum segment size to be removed
with respect to the supposed segment size
`depth*width*height/num_segments` (optional).
max_size_factor: Proportion of the maximum connected segment size
(optional).
enforce_connectivitiy: Whether the generated segments are connected or
not (optional).
Returns:
Segmentation algorithm that takes a single image as argument.
"""
image = tf.cast(image, tf.uint8)
def _slico(image):
segmentation = skimage_slic(image, num_segments, compactness,
max_iterations, sigma,
min_size_factor=min_size_factor,
max_size_factor=max_size_factor,
enforce_connectivity=enforce_connectivity,
slic_zero=True)
return segmentation.astype(np.int32)
return tf.py_func(_slico, [image], tf.int32, stateful=False, name='slico')
示例12: extract_roi
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def extract_roi(img, labels_to_keep=[1,2]):
'''
Given a wheat image, this method returns an image containing only the region
of interest.
Args:
img: input image.
labels_to_keep: cluster labels to be kept in image while pixels
belonging to clusters besides these ones are removed.
Return:
roi_img: Input image containing only the region
of interest.
'''
label_img = segmentation.slic(img, compactness=30, n_segments=6)
labels = np.unique(label_img);print(labels)
gray = rgb2gray(img);
for label in labels:
if(label not in labels_to_keep):
logicalIndex = (label_img == label)
gray[logicalIndex] = 0;
#Display.show_image(gray)
return gray
示例13: main
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def main():
img = misc.imread("wheat.png")
# labels1 = segmentation.slic(img, compactness=100, n_segments=9)
labels1 = segmentation.slic(img, compactness=50, n_segments=4)
out1 = color.label2rgb(labels1, img, kind='overlay')
print(labels1.shape)
g = graph.rag_mean_color(img, labels1)
labels2 = graph.cut_threshold(labels1, g, 29)
out2 = color.label2rgb(labels2, img, kind='overlay')
# get roi
# logicalIndex = (labels2 != 1)
# gray = rgb2gray(img);
# gray[logicalIndex] = 0;
plt.figure()
io.imshow(out1)
plt.figure()
io.imshow(out2)
io.show()
示例14: extract_roi
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def extract_roi(img, labels_to_keep=[1,2]):
label_img = segmentation.slic(img, compactness=30, n_segments=6)
labels = np.unique(label_img);print(labels)
gray = rgb2gray(img);
for label in labels:
if(label not in labels_to_keep):
logicalIndex = (label_img == label)
gray[logicalIndex] = 0;
Display.show_image(gray)
io.imsave("grayy.png", gray)
示例15: set_superpixel_mask
# 需要导入模块: from skimage import segmentation [as 别名]
# 或者: from skimage.segmentation import slic [as 别名]
def set_superpixel_mask(self):
"""Use Simple Linear Iterative Clustering (SLIC) to get superpixels."""
# Get superpixel size and number
spixel_size = self.cd.spixel_size_baseMag * (
self.cd.MAG / self.cd.slide_info['magnification'])
n_spixels = int(
self.tissue_rgb.shape[0] * self.tissue_rgb.shape[1] / spixel_size)
# get superpixel mask
# optionally use grayscale instead of RGB -- seems more robust to
# color variations and sometimes gives better results
if self.cd.use_grayscale:
self.spixel_mask = slic(
rgb2gray(self.tissue_rgb), n_segments=n_spixels,
compactness=self.cd.compactness)
else:
self.spixel_mask = slic(
self.tissue_rgb, n_segments=n_spixels,
compactness=self.cd.compactness)
# restrict to tissue mask
tmask = resize(
self.tissue_mask, output_shape=self.spixel_mask.shape,
order=0, preserve_range=True, anti_aliasing=False)
self.spixel_mask[tmask == 0] = 0
# =========================================================================