Morphology
Morphology changes the shape of the white parts of a mask. Every pixel looks at a small neighbourhood, the structuring element, and takes the smallest or the largest value in it. That is all there is to erosion (the smallest: white shrinks) and dilation (the largest: white grows), and the other operations are made from those two.
import os
import libstb as stb
os.makedirs("out", exist_ok=True)
camera = stb.Image.open("camera.png")
mask = stb.threshold(camera, stb.otsu_threshold(camera))
mask.write("out/mask.png")
def white(image):
return sum(1 for value in image.tobytes() if value)
# The structuring element is the neighbourhood every pixel looks at: here an ellipse, 7 pixels across.
se = stb.structuring_element("ellipse", 7)
results = {
"erode": stb.erode(mask, se), # white shrinks: small white specks disappear
"dilate": stb.dilate(mask, se), # white grows: small black holes disappear
"open": stb.morph_open(mask, se), # erode then dilate: removes specks, keeps the shape
"close": stb.morph_close(mask, se), # dilate then erode: fills holes, keeps the shape
"gradient": stb.morph_gradient(mask, se), # dilate minus erode: the outline
}
print("mask:", white(mask), "white pixels")
for name, result in results.items():
result.write(f"out/{name}.png")
print(f"{name}: {white(result)}")
# On a gray picture the same calls work on the levels: the top hat keeps what is brighter than its surroundings.
stb.top_hat(camera, stb.structuring_element("rect", 15)).write("out/top_hat.png")
Output
mask: 177984 white pixels
erode: 160557
dilate: 190129
open: 174343
close: 182887
gradient: 29572







The operations
- erode removes white specks smaller than the element and thins the shapes.
- dilate fills black holes smaller than the element and thickens the shapes.
- morph_open is erode and then dilate: it removes small specks and keeps the shapes at their size.
- morph_close is dilate and then erode: it fills small holes and keeps the shapes at their size.
- morph_gradient is dilate minus erode: the outline of every shape.
- top_hat is the picture minus its opening: the bright details smaller than the element. black_hat is the closing minus the picture: the dark details.
The structuring element
structuring_element(shape, width, height) makes one: a rect, an ellipse or a cross, with odd sides (the height is the width when you leave it out). Any odd-sized gray image with non-zero members works as an element too. A bigger element removes bigger specks and rounds the shapes more.
All of them work on masks and, with the same meaning, on the gray levels of a picture, and they take an edge mode like the filters.
API at a glance
| The element | stb.structuring_element("ellipse", w, h) |
|---|---|
| Erode, dilate | stb.erode(img, se), stb.dilate(img, se) |
| Open, close | stb.morph_open(img, se), stb.morph_close(img, se) |
| Gradient | stb.morph_gradient(img, se) |
| Hats | stb.top_hat(img, se), stb.black_hat(img, se) |