Skip to main content

Threshold

Thresholding turns a gray picture into a mask: a picture whose pixels are 255 (yes) or 0 (no). It is the first step of most pipelines that count, measure or cut out things, because the next steps (morphology, components) work on masks.

import os

import libstb as stb

os.makedirs("out", exist_ok=True)
camera = stb.Image.open("camera.png")


def white(mask):
"""How many pixels of a mask are 255."""
return sum(1 for value in mask.tobytes() if value)


# A fixed level: 255 above it, 0 at or below it.
fixed = stb.threshold(camera, 128)
fixed.write("out/fixed.png")
print("level 128:", white(fixed), "white pixels")

# Otsu's method looks for the level that best separates two groups of pixels.
level = stb.otsu_threshold(camera)
otsu = stb.threshold(camera, level)
otsu.write("out/otsu.png")
print("otsu level:", level, "->", white(otsu), "white pixels")

# A local level: a pixel is white when it is above the mean of its 31 x 31 neighbourhood minus 5 levels.
local = stb.adaptive_threshold(camera, 15, 5.0, "mean")
local.write("out/adaptive.png")
print("adaptive:", white(local), "white pixels")

# invert flips the result.
inverted = stb.threshold(camera, level, invert=True)
print("otsu and its inverse add up to", white(otsu) + white(inverted), "pixels of", camera.width * camera.height)
Output
level 128: 167859 white pixels
otsu level: 102 -> 177984 white pixels
adaptive: 196819 white pixels
otsu and its inverse add up to 262144 pixels of 262144
fixed level 128
fixed level 128
Otsu level
Otsu level
adaptive, mean
adaptive, mean

Three ways to choose the level​

  • A fixed level. threshold(img, t) gives 255 where the value is above t and 0 where it is at or below it. It works when the lighting is even and you know the level.
  • Otsu's level. otsu_threshold(img) returns the level that best separates the pixels into a dark and a bright group, from the histogram of the picture. Use it when the level changes from picture to picture.
  • A local level. adaptive_threshold(img, radius, offset, method) compares each pixel with the mean (mean) or the Gaussian-weighted mean (gaussian, the default) of the square of side 2 * radius + 1 around it: white where the pixel is above that local level minus offset. It copes with uneven lighting, a shadow across a page, where no single level works.

All three take one channel, so convert a color picture to gray first (channels and alpha). invert swaps the result: 255 where it was 0.

API at a glance​

Fixed levelstb.threshold(img, t, invert=False)
Otsu levelstb.otsu_threshold(img), an int
Local levelstb.adaptive_threshold(img, radius, offset, method, invert)