mirror of
https://github.com/wassname/scikit-image.git
synced 2026-07-13 17:45:20 +08:00
Allow grayscale input images to SLIC segmentation
There is no reason for SLIC to be restricted to colour/RGB images. I have added a few lines that allow single-channel input.
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user