pythonimage-processingcomputer-visionscikit-image

Issue about the number of superpixel result returned by skimage.segmentation.slic function


Why the number of superpixel result returned by skimage.segmentation.slic function is not equal to parameter n_segments. The API says that n_segments: The (approximate) number of labels in the segmented output image. So, what the reason behind this that can't return the exact number of superpixel?

from skimage.segmentation import slic
import numpy as np
from torchvision import datasets
dataset = datasets.MNIST(root='../dataset', train=True, download=False)

n_segments = 50
for i in range(len(dataset)):
    segments = slic(dataset[i][0], n_segments=50, compactness=0.25)
    n_sp = len(np.unique(segments))
    print('image={}/{}, n_sp={}'.format(i + 1, len(dataset), n_sp))

the slice of output:

image=3938/60000, n_sp=41
image=3939/60000, n_sp=41
image=3940/60000, n_sp=43
image=3941/60000, n_sp=44
image=3942/60000, n_sp=42
image=3943/60000, n_sp=44
image=3944/60000, n_sp=41
image=3945/60000, n_sp=46
image=3946/60000, n_sp=44
image=3947/60000, n_sp=43
image=3948/60000, n_sp=44
image=3949/60000, n_sp=42
image=3950/60000, n_sp=43
image=3951/60000, n_sp=41
image=3952/60000, n_sp=42
image=3953/60000, n_sp=44
image=3954/60000, n_sp=43
image=3955/60000, n_sp=48
image=3956/60000, n_sp=47
image=3957/60000, n_sp=45
image=3958/60000, n_sp=44
image=3959/60000, n_sp=45
image=3960/60000, n_sp=42
image=3961/60000, n_sp=43
image=3962/60000, n_sp=46
image=3963/60000, n_sp=47
image=3964/60000, n_sp=46

Solution

  • The SLIC algorithm is not able to produce an exact number of segments. It’s just how it is defined. The algorithm starts with a regular grid of seed points, and you just can’t make a regular grid covering the image with an exact number of points.

    You could use SLIC to find a slightly larger number of superpixels than you need, and then merge similar superpixels until you have your exact number left.

    You’d have to find all neighboring superpixel pairs, compare them, and list the pairs in order of similarity. Now work your way down the list merging pairs.