精华内容
下载资源
问答
  • 切片代码matlab C++ 代码来自 Chuan Yang、Lihe Zhang、Huchuan Lu、Xiang Ruan ...SLIC 超像素代码。 *注:论文中的结果是由MATLAB代码生成的。 此 c++ 代码的结果可能与 MATLAB 代码的结果有些不同。
  • python 自带slic代码分析

    千次阅读 热门讨论 2018-12-01 15:09:57
    一.python中的slic函数 def slic(image, n_segments=100, compactness=10., max_iter=10, sigma=0, spacing=None, multichannel=True, convert2lab=None, enforce_connectivity=True, min_size_fact...

    一.python中的slic函数

    
    def slic(image, n_segments=100, compactness=10., max_iter=10, sigma=0,
             spacing=None, multichannel=True, convert2lab=None,
             enforce_connectivity=True, min_size_factor=0.5, max_size_factor=3,
             slic_zero=False):
        """Segments image using k-means clustering in Color-(x,y,z) space.
    
        Parameters
        ----------
        image : 2D, 3D or 4D ndarray
            Input image, which can be 2D or 3D, and grayscale or multichannel
            (see `multichannel` parameter).
        n_segments : int, optional
            The (approximate) number of labels in the segmented output image.
        compactness : float, optional
            控制颜色和空间之间的平衡,约高越方块,和图关系密切,最好先确定指数级别,再微调
            Balances color proximity and space proximity. Higher values give
            more weight to space proximity, making superpixel shapes more
            square/cubic. In SLICO mode, this is the initial compactness.
            This parameter depends strongly on image contrast and on the
            shapes of objects in the image. We recommend exploring possible
            values on a log scale, e.g., 0.01, 0.1, 1, 10, 100, before
            refining around a chosen value.
        max_iter : int, optional
            最大k均值迭代次数
            Maximum number of iterations of k-means.
        sigma : float or (3,) array-like of floats, optional
            图像每个维度进行预处理时的高斯平滑核宽。若给定为标量值,则同一个值运用到各个维度。0意味
            着不平滑。如果“sigma”是标量的,并且提供了手动体素间距,则自动缩放它(参见注释部分)。
            Width of Gaussian smoothing kernel for pre-processing for each
            dimension of the image. The same sigma is applied to each dimension in
            case of a scalar value. Zero means no smoothing.
            Note, that `sigma` is automatically scaled if it is scalar and a
            manual voxel spacing is provided (see Notes section).
        spacing : (3,) array-like of floats, optional
            代表沿着图像每个维度的体素空间。默认情况下,slic假定均匀的空间(沿x,y,z轴相同的体素分辨
            率),这个参数控制在k均值聚类中各轴距离的权重
            The voxel spacing along each image dimension. By default, `slic`
            assumes uniform spacing (same voxel resolution along z, y and x).
            This parameter controls the weights of the distances along z, y,
            and x during k-means clustering.
        multichannel : bool, optional
            二进制参数,代表图像的最后一个轴代表多通道还是另一个空间维度
            Whether the last axis of the image is to be interpreted as multiple
            channels or another spatial dimension.
        convert2lab : bool, optional
            二进制参数,判断输入需要在分割之前转到LAB颜色空间。输入必须是RGB。当多通道参数为True,
            输入图片的通道数为3时,该参数默认为True
            Whether the input should be converted to Lab colorspace prior to
            segmentation. The input image *must* be RGB. Highly recommended.
            This option defaults to ``True`` when ``multichannel=True`` *and*
            ``image.shape[-1] == 3``.
        enforce_connectivity: bool, optional
            二进制参数,控制生成的分割块连接或不连接
            Whether the generated segments are connected or not
        min_size_factor: float, optional
            与分割目标数有关的要删去的最小分割块比率,(大概是小于长*宽*高/目标数量 的分割结果会被融
            合掉)
            Proportion of the minimum segment size to be removed with respect
            to the supposed segment size ```depth*width*height/n_segments```
        max_size_factor: float, optional
            最大融合比率上限
            Proportion of the maximum connected segment size. A value of 3 works
            in most of the cases.
        slic_zero: bool, optional
            不知所谓的零参数
            Run SLIC-zero, the zero-parameter mode of SLIC. [2]_
    
        Returns
        -------
        labels : 2D or 3D array
            Integer mask indicating segment labels.
    
        Raises
        ------
        ValueError
            If ``convert2lab`` is set to ``True`` but the last array
            dimension is not of length 3.
    
        Notes
        -----
        * If `sigma > 0`, the image is smoothed using a Gaussian kernel prior to
          segmentation.
    
        * If `sigma` is scalar and `spacing` is provided, the kernel width is
          divided along each dimension by the spacing. For example, if ``sigma=1``
          and ``spacing=[5, 1, 1]``, the effective `sigma` is ``[0.2, 1, 1]``. This
          ensures sensible smoothing for anisotropic images.
          如果有平滑参数sigma和体素空间参数spacing,那么空间体素参数会对平滑参数有平分的影响,比如                
          1/[5,1,1]=[0.2,1,1]
    
        * The image is rescaled to be in [0, 1] prior to processing.
          图像在预处理之前会被处理为[0,1]之间的标量
    
        * Images of shape (M, N, 3) are interpreted as 2D RGB images by default. To
          interpret them as 3D with the last dimension having length 3, use
          `multichannel=False`.
          (M,N,3)的图像默认为2维(RGB的图像),要想被理解为3维图需要设置多通道参数=False
    
        References
        ----------
        .. [1] Radhakrishna Achanta, Appu Shaji, Kevin Smith, Aurelien Lucchi,
            Pascal Fua, and Sabine Süsstrunk, SLIC Superpixels Compared to
            State-of-the-art Superpixel Methods, TPAMI, May 2012.
        .. [2] http://ivrg.epfl.ch/research/superpixels#SLICO
    
        Examples
        --------
        >>> from skimage.segmentation import slic
        >>> from skimage.data import astronaut
        >>> img = astronaut()
        >>> segments = slic(img, n_segments=100, compactness=10)
    
        Increasing the compactness parameter yields more square regions:
    
        >>> segments = slic(img, n_segments=100, compactness=20)
    
        """
        ###############################################干正事啦
    
        image = img_as_float(image)
        is_2d = False
        #2D灰度图
        if image.ndim == 2:
            # 2D grayscale image
            image = image[np.newaxis, ..., np.newaxis]
            is_2d = True
    
        #比如2D RGB的图
        elif image.ndim == 3 and multichannel:
            # Make 2D multichannel image 3D with depth = 1
            image = image[np.newaxis, ...]
            is_2d = True
    
    
        #比如3D图
        elif image.ndim == 3 and not multichannel:
            # Add channel as single last dimension
            image = image[..., np.newaxis]
    
        #控制聚类时各轴权重
        if spacing is None:
            spacing = np.ones(3)
        elif isinstance(spacing, (list, tuple)):
            spacing = np.array(spacing, dtype=np.double)
    
        #高斯平滑
        if not isinstance(sigma, coll.Iterable):
            sigma = np.array([sigma, sigma, sigma], dtype=np.double)
            sigma /= spacing.astype(np.double)#有可能发生的体素除
        elif isinstance(sigma, (list, tuple)):
            sigma = np.array(sigma, dtype=np.double)
    
        #高斯滤波处
        if (sigma > 0).any():
            # add zero smoothing for multichannel dimension
            sigma = list(sigma) + [0]
            image = ndi.gaussian_filter(image, sigma)
    
        #多通道RGB图且需要转lab,用rab2lab即可实现
        if multichannel and (convert2lab or convert2lab is None):
            if image.shape[-1] != 3 and convert2lab:
                raise ValueError("Lab colorspace conversion requires a RGB image.")
            elif image.shape[-1] == 3:
                image = rgb2lab(image)
    
        depth, height, width = image.shape[:3]
    
        # initialize cluster centroids for desired number of segments
        #为实现目标分割块数,初始化聚类中心。
        #grid_* 相当于index
        #slices是根据目标数量分的块,有取整需要
        grid_z, grid_y, grid_x = np.mgrid[:depth, :height, :width]
        slices = regular_grid(image.shape[:3], n_segments)
        step_z, step_y, step_x = [int(s.step if s.step is not None else 1)
                                  for s in slices]
        segments_z = grid_z[slices]
        segments_y = grid_y[slices]
        segments_x = grid_x[slices]
    
        segments_color = np.zeros(segments_z.shape + (image.shape[3],))
        segments = np.concatenate([segments_z[..., np.newaxis],
                                   segments_y[..., np.newaxis],
                                   segments_x[..., np.newaxis],
                                   segments_color],
                                  axis=-1).reshape(-1, 3 + image.shape[3])
        segments = np.ascontiguousarray(segments)
    
        # we do the scaling of ratio in the same way as in the SLIC paper
        # so the values have the same meaning
        step = float(max((step_z, step_y, step_x)))
        ratio = 1.0 / compactness
    
        #我类个去,分割时方不方的骚操作
        image = np.ascontiguousarray(image * ratio)
    
        labels = _slic_cython(image, segments, step, max_iter, spacing, slic_zero)
    
        #把过小过小的处理一下
        if enforce_connectivity:
            segment_size = depth * height * width / n_segments
            min_size = int(min_size_factor * segment_size)
            max_size = int(max_size_factor * segment_size)
            labels = _enforce_label_connectivity_cython(labels,
                                                        min_size,
                                                        max_size)
    
        if is_2d:
            labels = labels[0]
    
        return labels

    二、注意事项

    1.要不要转化到LAB空间是可以调的,当然啦不转的结果就是方方正正的空间分割,和内容毫无关系,比如下图

    convert2lab or convert2lab is None  这段代码可以看出来,不传参数和传参数为True都是转到lab了,完美。

     

    2.分割结果比设置的少是因为做了一下后处理,调一下enforce_connectivity就变多啦,但不是一定分割结果和设置数量一样的。比如下图,设置分割20,参数设置为False结果为12块,参数设置为True就是3块

    分割目标数量恰当的话(比如100),是这样的:

     

    三、SLCI的使用

    from __future__ import division
    from skimage.segmentation import slic,mark_boundaries
    from skimage import io
    import matplotlib.pyplot as plt
    import numpy as np
    
    img = io.imread("imgs\style\DTD\\denoised_starry.jpg")
    print(img.shape)
    
    
    segments = slic(img, n_segments=100, compactness=20,enforce_connectivity=True,convert2lab=True)
    print(segments.shape)
    n_liantong=segments.max()+1
    print('n_liantong:',n_liantong)
    area=np.bincount(segments.flat)
    w,h=segments.shape
    print(area/(w*h))
    print((max(area/(w*h))),(min(area/(w*h))))
    
    out=mark_boundaries(img,segments)
    plt.subplot(111)
    plt.imshow(out)
    plt.show()

    四、参考一的代码做修改

    相对导入报错:

    ValueError: attempted relative import beyond top-level package

     

    调用关系需要做一下修改,

    原:

    from ..util import img_as_float, regular_grid
    from ..segmentation._slic import (_slic_cython,
                                      _enforce_label_connectivity_cython)
    from ..color import rgb2lab

    修改后:

    from skimage.util import img_as_float, regular_grid
    from skimage.segmentation._slic import (_slic_cython,
                                      _enforce_label_connectivity_cython)
    from skimage.color import rgb2lab

     

     

     

     

     

     

    展开全文
  • 一.python中的slic函数 def slic(image, n_segments=100, compactness=10., max_iter=10, sigma=0, spacing=None, multichannel=True, convert2lab=None, enforce_connectivity=True, min_size_fac...

    一.python中的slic函数

     
    def slic(image, n_segments=100, compactness=10., max_iter=10, sigma=0,
             spacing=None, multichannel=True, convert2lab=None,
             enforce_connectivity=True, min_size_factor=0.5, max_size_factor=3,
             slic_zero=False):
        """Segments image using k-means clustering in Color-(x,y,z) space.
        Parameters
        ----------
        image : 2D, 3D or 4D ndarray
            Input image, which can be 2D or 3D, and grayscale or multichannel
            (see `multichannel` parameter).
        n_segments : int, optional
            The (approximate) number of labels in the segmented output image.
        compactness : float, optional
            控制颜色和空间之间的平衡,约高越方块,和图关系密切,最好先确定指数级别,再微调
            Balances color proximity and space proximity. Higher values give
            more weight to space proximity, making superpixel shapes more
            square/cubic. In SLICO mode, this is the initial compactness.
            This parameter depends strongly on image contrast and on the
            shapes of objects in the image. We recommend exploring possible
            values on a log scale, e.g., 0.01, 0.1, 1, 10, 100, before
            refining around a chosen value.
        max_iter : int, optional
            最大k均值迭代次数
            Maximum number of iterations of k-means.
        sigma : float or (3,) array-like of floats, optional
            图像每个维度进行预处理时的高斯平滑核宽。若给定为标量值,则同一个值运用到各个维度。0意味
            着不平滑。如果“sigma”是标量的,并且提供了手动体素间距,则自动缩放它(参见注释部分)。
            Width of Gaussian smoothing kernel for pre-processing for each
            dimension of the image. The same sigma is applied to each dimension in
            case of a scalar value. Zero means no smoothing.
            Note, that `sigma` is automatically scaled if it is scalar and a
            manual voxel spacing is provided (see Notes section).
        spacing : (3,) array-like of floats, optional
            代表沿着图像每个维度的体素空间。默认情况下,slic假定均匀的空间(沿x,y,z轴相同的体素分辨
            率),这个参数控制在k均值聚类中各轴距离的权重
            The voxel spacing along each image dimension. By default, `slic`
            assumes uniform spacing (same voxel resolution along z, y and x).
            This parameter controls the weights of the distances along z, y,
            and x during k-means clustering.
        multichannel : bool, optional
            二进制参数,代表图像的最后一个轴代表多通道还是另一个空间维度
            Whether the last axis of the image is to be interpreted as multiple
            channels or another spatial dimension.
        convert2lab : bool, optional
            二进制参数,判断输入需要在分割之前转到LAB颜色空间。输入必须是RGB。当多通道参数为True,
            输入图片的通道数为3时,该参数默认为True
            Whether the input should be converted to Lab colorspace prior to
            segmentation. The input image *must* be RGB. Highly recommended.
            This option defaults to ``True`` when ``multichannel=True`` *and*
            ``image.shape[-1] == 3``.
        enforce_connectivity: bool, optional
            二进制参数,控制生成的分割块连接或不连接
            Whether the generated segments are connected or not
        min_size_factor: float, optional
            与分割目标数有关的要删去的最小分割块比率,(大概是小于长*宽*高/目标数量 的分割结果会被融
            合掉)
            Proportion of the minimum segment size to be removed with respect
            to the supposed segment size ```depth*width*height/n_segments```
        max_size_factor: float, optional
            最大融合比率上限
            Proportion of the maximum connected segment size. A value of 3 works
            in most of the cases.
        slic_zero: bool, optional
            不知所谓的零参数
            Run SLIC-zero, the zero-parameter mode of SLIC. [2]_
        Returns
        -------
        labels : 2D or 3D array
            Integer mask indicating segment labels.
        Raises
        ------
        ValueError
            If ``convert2lab`` is set to ``True`` but the last array
            dimension is not of length 3.
        Notes
        -----
        * If `sigma > 0`, the image is smoothed using a Gaussian kernel prior to
          segmentation.
        * If `sigma` is scalar and `spacing` is provided, the kernel width is
          divided along each dimension by the spacing. For example, if ``sigma=1``
          and ``spacing=[5, 1, 1]``, the effective `sigma` is ``[0.2, 1, 1]``. This
          ensures sensible smoothing for anisotropic images.
          如果有平滑参数sigma和体素空间参数spacing,那么空间体素参数会对平滑参数有平分的影响,比如                
          1/[5,1,1]=[0.2,1,1]
        * The image is rescaled to be in [0, 1] prior to processing.
          图像在预处理之前会被处理为[0,1]之间的标量
        * Images of shape (M, N, 3) are interpreted as 2D RGB images by default. To
          interpret them as 3D with the last dimension having length 3, use
          `multichannel=False`.
          (M,N,3)的图像默认为2维(RGB的图像),要想被理解为3维图需要设置多通道参数=False
        References
        ----------
        .. [1] Radhakrishna Achanta, Appu Shaji, Kevin Smith, Aurelien Lucchi,
            Pascal Fua, and Sabine Süsstrunk, SLIC Superpixels Compared to
            State-of-the-art Superpixel Methods, TPAMI, May 2012.
        .. [2] http://ivrg.epfl.ch/research/superpixels#SLICO
        Examples
        --------
        >>> from skimage.segmentation import slic
        >>> from skimage.data import astronaut
        >>> img = astronaut()
        >>> segments = slic(img, n_segments=100, compactness=10)
        Increasing the compactness parameter yields more square regions:
        >>> segments = slic(img, n_segments=100, compactness=20)
        """
        ###############################################干正事啦
     
        image = img_as_float(image)
        is_2d = False
        #2D灰度图
        if image.ndim == 2:
            # 2D grayscale image
            image = image[np.newaxis, ..., np.newaxis]
            is_2d = True
     
        #比如2D RGB的图
        elif image.ndim == 3 and multichannel:
            # Make 2D multichannel image 3D with depth = 1
            image = image[np.newaxis, ...]
            is_2d = True
     
     
        #比如3D图
        elif image.ndim == 3 and not multichannel:
            # Add channel as single last dimension
            image = image[..., np.newaxis]
     
        #控制聚类时各轴权重
        if spacing is None:
            spacing = np.ones(3)
        elif isinstance(spacing, (list, tuple)):
            spacing = np.array(spacing, dtype=np.double)
     
        #高斯平滑
        if not isinstance(sigma, coll.Iterable):
            sigma = np.array([sigma, sigma, sigma], dtype=np.double)
            sigma /= spacing.astype(np.double)#有可能发生的体素除
        elif isinstance(sigma, (list, tuple)):
            sigma = np.array(sigma, dtype=np.double)
     
        #高斯滤波处
        if (sigma > 0).any():
            # add zero smoothing for multichannel dimension
            sigma = list(sigma) + [0]
            image = ndi.gaussian_filter(image, sigma)
     
        #多通道RGB图且需要转lab,用rab2lab即可实现
        if multichannel and (convert2lab or convert2lab is None):
            if image.shape[-1] != 3 and convert2lab:
                raise ValueError("Lab colorspace conversion requires a RGB image.")
            elif image.shape[-1] == 3:
                image = rgb2lab(image)
     
        depth, height, width = image.shape[:3]
     
        # initialize cluster centroids for desired number of segments
        #为实现目标分割块数,初始化聚类中心。
        #grid_* 相当于index
        #slices是根据目标数量分的块,有取整需要
        grid_z, grid_y, grid_x = np.mgrid[:depth, :height, :width]
        slices = regular_grid(image.shape[:3], n_segments)
        step_z, step_y, step_x = [int(s.step if s.step is not None else 1)
                                  for s in slices]
        segments_z = grid_z[slices]
        segments_y = grid_y[slices]
        segments_x = grid_x[slices]
     
        segments_color = np.zeros(segments_z.shape + (image.shape[3],))
        segments = np.concatenate([segments_z[..., np.newaxis],
                                   segments_y[..., np.newaxis],
                                   segments_x[..., np.newaxis],
                                   segments_color],
                                  axis=-1).reshape(-1, 3 + image.shape[3])
        segments = np.ascontiguousarray(segments)
     
        # we do the scaling of ratio in the same way as in the SLIC paper
        # so the values have the same meaning
        step = float(max((step_z, step_y, step_x)))
        ratio = 1.0 / compactness
     
        #我类个去,分割时方不方的骚操作
        image = np.ascontiguousarray(image * ratio)
     
        labels = _slic_cython(image, segments, step, max_iter, spacing, slic_zero)
     
        #把过小过小的处理一下
        if enforce_connectivity:
            segment_size = depth * height * width / n_segments
            min_size = int(min_size_factor * segment_size)
            max_size = int(max_size_factor * segment_size)
            labels = _enforce_label_connectivity_cython(labels,
                                                        min_size,
                                                        max_size)
     
        if is_2d:
            labels = labels[0]
     
        return labels
    

    二、注意事项

    1.要不要转化到LAB空间是可以调的,当然啦不转的结果就是方方正正的空间分割,和内容毫无关系,比如下图

    convert2lab or convert2lab is None  这段代码可以看出来,不传参数和传参数为True都是转到lab了,完美。

     

    2.分割结果比设置的少是因为做了一下后处理,调一下enforce_connectivity就变多啦,但不是一定分割结果和设置数量一样的。比如下图,设置分割20,参数设置为False结果为12块,参数设置为True就是3块

    分割目标数量恰当的话(比如100),是这样的:

     

    三、SLCI的使用

    from __future__ import division
    from skimage.segmentation import slic,mark_boundaries
    from skimage import io
    import matplotlib.pyplot as plt
    import numpy as np
     
    img = io.imread("imgs\style\DTD\\denoised_starry.jpg")
    print(img.shape)
     
     
    segments = slic(img, n_segments=100, compactness=20,enforce_connectivity=True,convert2lab=True)
    print(segments.shape)
    n_liantong=segments.max()+1
    print('n_liantong:',n_liantong)
    area=np.bincount(segments.flat)
    w,h=segments.shape
    print(area/(w*h))
    print((max(area/(w*h))),(min(area/(w*h))))
     
    out=mark_boundaries(img,segments)
    plt.subplot(111)
    plt.imshow(out)
    plt.show()
    

    四、参考一的代码做修改

    相对导入报错:

    ValueError: attempted relative import beyond top-level package

    调用关系需要做一下修改,

    原:

    1. from ..util import img_as_float, regular_grid

    2. from ..segmentation._slic import (_slic_cython,

    3. _enforce_label_connectivity_cython)

    4. from ..color import rgb2lab

    修改后:

    1. from skimage.util import img_as_float, regular_grid

    2. from skimage.segmentation._slic import (_slic_cython,

    3. _enforce_label_connectivity_cython)

    4. from skimage.color import rgb2lab

    展开全文
  • slic实现代码

    2019-03-16 10:27:03
    实现slic代码 效果还行,可以试一下
  • SLIC超像素分割MATLAB代码SLIC 超像素 该存储库提供了带有 Python 和 Matlab 接口的简单线性迭代聚类 (SLIC) 算法的代码。 在这两种情况下,都提供了一个演示文件,应该很容易使用。 这两个版本都可以为灰色、彩色...
  • SLIC算法介绍及代码

    2016-02-14 14:54:56
    包括SLIC框架、相关论文介绍、关于SLIC的学习笔记、SLIC分割代码以及示例。
  • SLIC超像素代码

    2018-01-03 21:03:52
    matlab超像素代码,直接运行main函数可运行,k表示超像素块的个数
  • SLIC超像素分割matlab代码

    热门讨论 2015-05-10 10:54:07
    SLIC超像素分割matlab代码
  • SLIC超像素分割代码

    2018-05-12 14:45:36
    代码为C代码、需编译成MATLAB可执行文件后使用。经本人使用验证有效。。有问题的可以私信。。该代码确定可以实现相应的功能。。
  • SLIC超像素分割:将彩色图像转化为CIELAB颜色空间和XY坐标下的5维特征向量,然后对5维特征向量构造距离度量标准,对图像像素进行局部聚类的过程。
  • SLIC超像素分割算法MATLAB算法代码实现,超像素分割关键代码形式
  • SLIC 超像素分割 matlab 代码

    热门讨论 2014-08-28 11:07:48
    目前只看到SLIC的简介和C++代码,有兄弟评论需要matlab版,这里给大家找来了,记得给好评喔
  • SLIC超像素分割MATLAB代码
  • SLIC的matlab代码,可以更改自己的图片位置,生成结果,可以直接运行使用
  • SLIC Superpixels 算法代码学习笔记

    千次阅读 2015-01-14 14:13:43
    1.主程序入口 下面的程序就是超像素生成的函数入口: slic.DoSuperpixelSegmentation_ForGivenNumberOfSuperpixels(img, width, height, labels, numlabels, m_spcount, m_compactness);...slicSLIC slic; 是
    1.主程序入口
    • 下面的程序就是超像素生成的函数入口
    slic.DoSuperpixelSegmentation_ForGivenNumberOfSuperpixels(img, width, height, labels, numlabels, m_spcount, m_compactness);
    这里有几个特别的参数需要说明:
    1. slic:SLIC slic; 是一个SLIC类
    2. labels:int* labels = new int[sz];一张标签图,和图像大小一致,用于标记每个像素的标签值;sz=width*height,即一张图像的像素总数。
    3. numlabels:int numlabels(0);是图像最终分成的类数,即最终生成的超像素个数,在这里被初始化为0。
    4. m_spcount: 客户从界面输入的值,即初始化的种子个数,但是SLIC算法中不一定每个种子最终都能得一个超像素,由于某些因素可能被其他超像素合并。若种子数不符合规定,则通过(总像素值SZ)/(每个超像素默认大小200)获得种子数:if (m_spcount < 20 || m_spcount > sz/4) m_spcount = sz/200;
    5. m_compactness:if(m_compactness < 1.0 || m_compactness > 80.0) m_compactness = 20.0;这个值也是有用户设定的,是颜色特征和XY坐标特征之间的紧密度比例,20这个值效果往往不错。
    • 该函数的定义
    void SLIC::DoSuperpixelSegmentation_ForGivenNumberOfSuperpixels(
        unsigned int *                                   ubuff,//img
       const int                                         width,
        const int                                        height,
        int*&                                           klabels,//labels
        int&                                            numlabels, //
        const int &                                      K, //初始化的种子m_spcount
        const double &                                   compactness) //m_compactness空间参数转换的权重值
    {
        const int superpixelsize = 0.5+double(width*height)/ double(K);
        DoSuperpixelSegmentation_ForGivenSuperpixelSize(ubuff,width,height,klabels,numlabels,superpixelsize,compactness);
    }
    1. superpixelsize:超像素的大小,即每个超像素中包含的像素值
    2. DoSuperpixelSegmentation_ForGivenSuperpixelSize函数中完成了超像素生成的功能
    3. const int STEP = sqrt(double(superpixelsize))+0.5;这个变量很关键,是种子点的跨度。
    2.子程序流程
    DoSuperpixelSegmentation_ForGivenSuperpixelSize函数中主要包含以下函数:
    • DoRGBtoLABConversion(ubuff, m_lvec, m_avec, m_bvec); 
         将RGB图像转换为LAB图像。
    • GetLABXYSeeds_ForGivenStepSize(kseedsl, kseedsa, kseedsb, kseedsx, kseedsy, STEP, perturbseeds, edgemag);
              均匀分布种子点,将种子点的5维特征值LABXY作为分类的中心点特征值存入kseeds向量中。
    • PerformSuperpixelSLIC(kseedsl, kseedsa, kseedsb, kseedsx, kseedsy, klabels, STEP, edgemag,compactness);
              对整张图像进行局部的K-Means聚类,生成超像素。这是超像素生成的关键步骤,也耗时最多。
    • EnforceLabelConnectivity(klabels, m_width, m_height, nlabels, numlabels, double(sz)/double(STEP*STEP));
              对生成的初步超像素图像,进行合并孤立超像素,某些孤点像素与大小过小的超像素被合并到附近的超像素中。

    3.关键程序解析:这里只讲PerformSuperpixelSLIC与EnforceLabelConnectivity
    • PerformSuperpixelSLIC
    (1)核心就是局部的K-Means聚类

    局部顾名思义,就是只对种子点附近的像素进行聚类,这里种子是按照STEP=S的跨度分布的,稍微扩大一点聚类范围,选为边长为2S矩形。
     (2)特征值计算

    上面即像素到种子点的“距离”计算,距离中包括了LABXY5个特征值。方法就是,在局部区域内对每个像素点求其到中心的距离,若小于以前存放的距离,则将距离更新,且更新该像素点的类别标签。
       (3)种子点特征值更新

    上部分程序,将超像素中的特征值加在一起。

    上部分程序将各特征值的平均值作为中心点的特征值。
    整个KMeans聚类迭代次数为10,即上面的内容重复10次,每次的像素点所属的类都有可能变化。
    • EnforceLabelConnectivity
    函数定义与说明
    void SLIC::EnforceLabelConnectivity(
                     const int *                                                                              labels, //input labels that need to be corrected to remove stray labels
                     const int                                                                                 width,
                     const int                                                                                 height,
                     int*&                                                                                      nlabels, //new labels
                     int&                                                                                        numlabels, //the number of labels changes in the end if segments are removed
                     const int &                                                                             K) 
             const int dx8[8] = {-1, -1,  0,  1, 1, 1, 0, -1};
    //             const int dy8[8] = { 0, -1, -1, -1, 0, 1, 1,  1};

                     const int dx4[4] = {-1,  0,  1,  0};
                     const int dy4[4] = { 0, -1,  0,  1};

                     const int sz = width*height;
                     const int SUPSZ = sz/K;
                     //nlabels.resize(sz, -1);
                     for( int i = 0; i < sz; i++ ) nlabels[i] = -1;
                     int label(0);
                     int* xvec = new int[sz];
                     int* yvec = new int[sz];
                     int oindex(0);
                     int adjlabel(0);//adjacent label
                     for( int j = 0; j < height; j++ )
                    {
                                     for( int k = 0; k < width; k++ )
                                    {
                                                     if( 0 > nlabels[oindex] )
                                                    {
                                                                    nlabels[oindex] = label;
                                                                     //--------------------
                                                                     // Start a new segment
                                                                     //--------------------
                                                                    xvec[0] = k;
                                                                    yvec[0] = j;

                                                                     //在像素点4领域内找到被标记的标签,记为adjlabel (该点的邻域标签)
                                                                    { for( int n = 0; n < 4; n++ )
                                                                    {
                                                                                     int x = xvec[0] + dx4[n];
                                                                                     int y = yvec[0] + dy4[n];
                                                                                     if( (x >= 0 && x < width) && (y >= 0 && y < height) )
                                                                                    {
                                                                                                     int nindex = y*width + x;
                                                                                                     if(nlabels[nindex] >= 0) adjlabel = nlabels[nindex];
                                                                                    }
                                                                    }}

                                                                     int count(1);
                                                                     //整个过程就是在区域增长的标标签
                                                                     for( int c = 0; c < count; c++ )
                                                                    {
                                                                                     for( int n = 0; n < 4; n++ )
                                                                                    {
                                                                                                    //以4邻域区域增长的方式找和原始像素点标签相同的像素点的个数
                                                                                                      int x = xvec[c] + dx4[n];
                                                                                                     int y = yvec[c] + dy4[n];
                                                                                                      if( (x >= 0 && x < width) && (y >= 0 && y < height) )
                                                                                                    {
                                                                                                                     int nindex = y*width + x;
                                                                                                                  if( 0 > nlabels[nindex] && labels[oindex] == labels[nindex] )//是否和原点的标签一致,并且在区域增长过程中还未重新标记该点
                                                                                                                    {
                                                                                                                                    xvec[count] = x;
                                                                                                                                    yvec[count] = y;
                                                                                                                                    nlabels[nindex] = label;//将该点标记为何原始点一样的标签
                                                                                                                                    count++;
                                                                                                                    }
                                                                                                    }

                                                                                    }
                                                                    }
                                                                 //若区域小于超像素预定值的1/4,则与相邻的类进行合并,adjlabel。
                                                                     if(count <= SUPSZ >> 2)
                                                                    {
                                                                                     for( int c = 0; c < count; c++ )
                                                                                    {
                                                                                                     int ind = yvec[c]*width+xvec[c];
                                                                                                    nlabels[ind] = adjlabel;
                                                                                    }
                                                                                    label--; //标签复原-,从其他位置从新聚类
                                                                    }
                                                                    label++;
                                                    }
                                                    oindex++;
                                    }
                    }
                    numlabels = label;
                    if(xvec) delete [] xvec;
                    if(yvec) delete [] yvec;
    }
    展开全文
  • slic超像素分割方法源代码

    热门讨论 2015-10-15 08:45:25
    slic超像素分割方法源代码。c++实现,简洁明了
  • SLIC超像素分割代码实施

    千次阅读 2018-06-29 14:05:04
    1、网上下载SLIC超像素分割的代码以及GUI超像素分割结果图的代码,或者直接到我网盘通过提取码下载 链接链接:https://pan.baidu.com/s/1I8r6o6Pang44iMTqKUzObQ 提取码:ywtr 2、打开matlab(我用的matlab R2016a)...

     

    1、网上下载SLIC超像素分割的代码以及GUI超像素分割结果图的代码,或者直接到我网盘通过提取码下载
    链接链接:https://pan.baidu.com/s/1I8r6o6Pang44iMTqKUzObQ 
    提取码:ywtr
    2、打开matlab(我用的matlab R2016a),在“命令行窗口”输入 mex -setup换到C++/C编译器下面,如果出错说明没有安装C++/C编译器,需要安装,或者是有其他错误,这部分可以自行百度,网上都有解决办法;
    3、上步成功后,紧接着在“命令行窗口”输入 mex slicmex.c    成功后输入"SLICdemo",然后就可以出现结果图,此时的结果图不是分割好的一块块的超像素图,而是一幅有横纵坐标的黄绿蓝色的图;
    4、如果要实现下图所示的超像素图,就运行SLIC_Windows_GUI文件夹里的.exe程序。
    展开全文
  • SLIC: simple linear iterative clustering的简称,即简单的线性迭代聚类。 这是一个基于聚类算法的超像素分割,由LAB空间以及x、y像素坐标共5维空间来计算。不仅可以分割彩色图,也可以兼容分割灰度图,它还有一...
  • Slic3r填充代码解析

    2017-06-01 11:13:00
    Fill 首先通过new_from_type函数,将Infillpattern的类型与填充函数一一对应,对于不存在的类型默认返回null。 ...fill_surface函数,输入surface类型,生成每一区域的infills,polylines_out....
  • slic matlab 代码下载 superpixels SLIC超像素分割的算法介绍和源码分析 源码分析:作者上传的并不是纯粹的matlab代码,而是采用c写的生成的mex文件。 使用前提:我的电脑安装Matlab 2016ra和Vs2015 首先在下载源码...
  • 简单,可运行,代码只有几行,直接调用函数,图片都有。
  • 现在这个社会发展的太快,到处都充斥着各种各样的资源,各种开源的平台,如github,codeproject,pudn等等,加上一些大型的官方的开源软件,基本上能找到各个类型的代码。很多初创业的老板可能都曾经说过基本上我的...
  • 现在这个社会发展的太快,到处都充斥着各种各样的资源,各种开源的平台,如github,codeproject,pudn等等,加上一些大型的官方的开源软件,基本上能找到各个类型的代码。很多初创业的老板可能都曾经说过基本上我的...
  • 代码网址:http://ivrl.epfl.ch/research/superpixels#SLICO PS:上面的链接失效了,我搞了个代码托管,附链接:...里面的“SLIC_mex.zip”应该是作者官网上下载的。 下载了SLIC超像素分割的MATL...
  • 现在这个社会发展的太快,到处都充斥着各种各样的资源,各种开源的平台,如github,codeproject,pudn等等,加上一些大型的官方的开源软件,基本上能找到各个类型的代码。很多初创业的老板可能都曾经说过基本上我的...

空空如也

空空如也

1 2 3 4 5 ... 9
收藏数 174
精华内容 69
关键字:

slic代码