Guided filter
A Gaussian blur smooths everything, edges included. The bilateral filter smooths without blurring edges, but its cost grows with the radius. The guided filter does the same job at a cost that does not depend on the radius at all, which makes it the one to use for a large radius: smoothing a photograph while its edges stay sharp, removing noise from a depth map along the edges of a photo, or making the detail layer for a local-contrast effect.
import os
import libstb as stb
os.makedirs("out", exist_ok=True)
img = stb.Image.open("astronaut.png").thumbnail(256, 256)
# guided_filter(img, radius, eps): smooths inside every (2 * radius + 1) square and keeps the edges of the guide.
# eps is in units of the full range squared: 1e-3 is gentle, and a larger value smooths more.
gentle = stb.guided_filter(img, 6, 0.001)
strong = stb.guided_filter(img, 6, 0.05)
blur = stb.gaussian_blur(img, 4.0)
gentle.write("out/gentle.png")
strong.write("out/strong.png")
blur.write("out/blur.png")
print(f"eps 0.001: mean absolute change {stb.mae(img, gentle):.2f}")
print(f"eps 0.05: mean absolute change {stb.mae(img, strong):.2f}")
print(f"gaussian blur, sigma 4: mean absolute change {stb.mae(img, blur):.2f}")
# The guide can be another picture of the same size, gray or color: here the edges of the gray version steer the smoothing.
guided = stb.guided_filter(img, 6, 0.01, img.convert(stb.PixelFormat.GRAY))
guided.write("out/gray_guide.png")
print("with a gray guide the result has", guided.channels, "channels")
# A radius of 0 changes nothing.
print("radius 0 changes the picture:", "no" if stb.guided_filter(img, 0, 0.01).tobytes() == img.tobytes() else "yes")
eps 0.001: mean absolute change 1.25
eps 0.05: mean absolute change 8.53
gaussian blur, sigma 4: mean absolute change 18.82
with a gray guide the result has 3 channels
radius 0 changes the picture: no




How it works
In every square of side 2 * radius + 1 the output is the straight-line function of the guide that fits the image best. Where the guide is flat, the line is flat and the output is the local mean: smooth. Where the guide has an edge, the line follows it and the edge stays. eps keeps the slope of the line down: a small value follows the guide closely, a large one flattens it, so a larger eps smooths more. It is in units of the full range squared, so 1e-3 is gentle.
The guide
By default the guide is the picture itself, which smooths it and keeps its own edges. A guide can also be another picture of the same size, gray or color: a color guide uses the covariance of its three channels. The edges of the guide then steer the smoothing of the image, as in the third picture, where the gray version of the photo does it. An alpha channel is copied, and a radius of 0 changes nothing.
API at a glance
| Smooth with its own edges | stb.guided_filter(img, radius, eps, edge=) |
|---|---|
| With a guide | stb.guided_filter(img, radius, eps, guide) |
| Compared with | stb.gaussian_blur(img, sigma) |