diff --git a/skimage/segmentation/_slic.pyx b/skimage/segmentation/_slic.pyx index d0e4c2a3..dfb37a7c 100644 --- a/skimage/segmentation/_slic.pyx +++ b/skimage/segmentation/_slic.pyx @@ -3,7 +3,7 @@ cimport numpy as np from time import time from scipy import ndimage from ..util import img_as_float -from ..color import rgb2lab +from ..color import rgb2lab, gray2rgb def slic(image, n_segments=100, ratio=10., max_iter=10, sigma=1, @@ -12,7 +12,7 @@ def slic(image, n_segments=100, ratio=10., max_iter=10, sigma=1, Parameters ---------- - image : (width, height, 3) ndarray + image : (width, height [, 3]) ndarray Input image. n_segments : int The (approximate) number of labels in the segmented output image. @@ -53,9 +53,10 @@ def slic(image, n_segments=100, ratio=10., max_iter=10, sigma=1, >>> # Increasing the ratio parameter yields more square regions >>> segments = slic(img, n_segments=100, ratio=20) """ - image = np.atleast_3d(image) - if image.shape[2] != 3: - ValueError("Only 3-channel 2D images are supported.") + if image.ndim == 2: + image = gray2rgb(image) + if image.ndim != 3 or image.shape[2] != 3: + ValueError("Only 1- or 3-channel 2D images are supported.") image = ndimage.gaussian_filter(img_as_float(image), [sigma, sigma, 0]) if convert2lab: image = rgb2lab(image) diff --git a/skimage/segmentation/tests/test_slic.py b/skimage/segmentation/tests/test_slic.py index f2d6698d..59088fcd 100644 --- a/skimage/segmentation/tests/test_slic.py +++ b/skimage/segmentation/tests/test_slic.py @@ -21,6 +21,22 @@ def test_color(): assert_array_equal(seg[:10, 10:], 1) assert_array_equal(seg[10:, 10:], 3) +def test_gray(): + rnd = np.random.RandomState(0) + img = np.zeros((20, 21)) + img[:10, :10] = 0.33 + img[10:, :10] = 0.67 + img[10:, 10:] = 1.00 + img += 0.0033 * rnd.normal(size=img.shape) + img[img > 1] = 1 + img[img < 0] = 0 + seg = slic(img, sigma=0, n_segments=4, ratio=50.0) + print(seg) + assert_equal(len(np.unique(seg)), 4) + assert_array_equal(seg[:10, :10], 0) + assert_array_equal(seg[10:, :10], 2) + assert_array_equal(seg[:10, 10:], 1) + assert_array_equal(seg[10:, 10:], 3) if __name__ == '__main__': from numpy import testing