當前位置: 首頁>>代碼示例>>Python>>正文


Python segmentation.slic方法代碼示例

本文整理匯總了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 
開發者ID:art-programmer,項目名稱:PlaneNet,代碼行數:20,代碼來源:utils.py

示例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 
開發者ID:art-programmer,項目名稱:PlaneNet,代碼行數:20,代碼來源:utils_backup.py

示例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 
開發者ID:okankop,項目名稱:vidaug,代碼行數:21,代碼來源:geometric.py

示例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 
開發者ID:okankop,項目名稱:vidaug,代碼行數:21,代碼來源:geometric.py

示例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() 
開發者ID:oduwa,項目名稱:Pic-Numero,代碼行數:23,代碼來源:spectral_roi.py

示例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) 
開發者ID:oduwa,項目名稱:Pic-Numero,代碼行數:24,代碼來源:spectral_roi.py

示例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) 
開發者ID:oduwa,項目名稱:Pic-Numero,代碼行數:18,代碼來源:RAG_threshold.py

示例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 
開發者ID:rusty1s,項目名稱:pytorch_geometric,代碼行數:10,代碼來源:to_superpixels.py

示例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 
開發者ID:rusty1s,項目名稱:pytorch_geometric,代碼行數:28,代碼來源:to_superpixels.py

示例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') 
開發者ID:rusty1s,項目名稱:graph-based-image-classification,代碼行數:40,代碼來源:slic.py

示例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') 
開發者ID:rusty1s,項目名稱:graph-based-image-classification,代碼行數:41,代碼來源:slico.py

示例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 
開發者ID:oduwa,項目名稱:Pic-Numero,代碼行數:28,代碼來源:spectral_roi.py

示例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() 
開發者ID:oduwa,項目名稱:Pic-Numero,代碼行數:25,代碼來源:RAG_threshold.py

示例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) 
開發者ID:oduwa,項目名稱:Pic-Numero,代碼行數:14,代碼來源:RAG_threshold.py

示例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

    # ========================================================================= 
開發者ID:DigitalSlideArchive,項目名稱:HistomicsTK,代碼行數:29,代碼來源:cellularity_detection_superpixels.py


注:本文中的skimage.segmentation.slic方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。