Skip to main content

Superpixels

A superpixel is a small compact region of a picture whose pixels look alike. A picture of a quarter of a million pixels becomes a few hundred regions that follow the edges of the objects, which is a much smaller thing to feed to a segmentation, a labelling tool or a classifier. libstb cuts a picture in about count such regions.

import os

import libstb as stb

os.makedirs("out", exist_ok=True)
img = stb.Image.open("astronaut.png").thumbnail(256, 256)

# About 150 compact regions of similar color. The default method is SLICO.
regions = stb.superpixels(img, count=150)
print("regions:", regions.count)
print("the region of the top-left pixel:", regions.label(0, 0))

# The borders drawn on the picture, and every region painted with its mean color.
regions.overlay(img).write("out/borders.png")
regions.mean_color(img).write("out/mean_color.png")

# A different method and a squarer shape: SLIC with a higher compactness.
squarer = stb.superpixels(img, count=150, compactness=30.0, method="slic")
squarer.overlay(img, color=(255, 255, 0)).write("out/squarer.png")
print("regions with SLIC:", squarer.count)
Output
regions: 136
the region of the top-left pixel: 0
regions with SLIC: 144
borders (SLICO)
borders (SLICO)
mean color of each region
mean color of each region
SLIC, compactness 30
SLIC, compactness 30

The methods​

  • slico, the default, is SLIC where every region adapts its own compactness, so there is nothing to tune.
  • slic is k-means on color and position, with one compactness for every region.
  • snic is one pass over the picture, with no iterations.
  • sicle starts from many more seeds than regions and drops the least relevant ones, run after run. It follows edges closely and gives exactly count regions.

compactness says how much position counts against color, in CIELAB units: 10 is usual and 1 to 40 is the useful range. A higher value gives squarer regions, a lower one follows the edges more closely. It is not used by sicle. The number of regions that comes out is about count, and exactly count for sicle.

The result​

The result is a map of which region every pixel is in, with:

  • count, the number of regions, and label(x, y), the region of a pixel;
  • boundaries(color), an RGBA image that is transparent except where a region ends;
  • overlay(img, color), the picture with the borders drawn in (red by default; a gray picture becomes RGB);
  • mean_color(img), the picture with every pixel replaced by the mean of its region, which is the picture rebuilt from the regions alone.

API at a glance​

Cut a picturestb.superpixels(img, count=, compactness=, method=)
The methods"slico", "slic", "snic", "sicle"
Count, label of a pixelregions.count, regions.label(x, y)
Bordersregions.overlay(img, color), regions.boundaries(color)
Mean colorsregions.mean_color(img)