SciPy Image Processing
To a computer, a grayscale image is just a 2-D array of brightness values, and a colour image is a 3-D array. That means array operations are image operations. The scipy.ndimage module ("n-dimensional image") provides filters, measurements and geometric transforms that work on arrays of any dimension — photos, microscope stacks, medical scans or simple grids of numbers.
In this lesson we'll use small arrays so you can see every value.
Smoothing filters
A Gaussian filter blurs an image by averaging each pixel with its neighbours, weighting closer ones more. A uniform filter uses equal weights. Both reduce noise; sigma and size control how much:
import numpy as np
from scipy import ndimage
img = np.zeros((7, 7))
img[3, 3] = 100 # one bright pixel
blurred = ndimage.gaussian_filter(img, sigma=1)
print(np.round(blurred, 1))
print("total brightness kept:", round(blurred.sum(), 1))[[ 0. 0. 0.1 0.2 0.1 0. 0. ]
[ 0. 0.3 1.3 2.2 1.3 0.3 0. ]
[ 0.1 1.3 5.9 9.7 5.9 1.3 0.1]
[ 0.2 2.2 9.7 15.9 9.7 2.2 0.2]
[ 0.1 1.3 5.9 9.7 5.9 1.3 0.1]
[ 0. 0.3 1.3 2.2 1.3 0.3 0. ]
[ 0. 0. 0.1 0.2 0.1 0. 0. ]]
total brightness kept: 100.0
The single bright pixel spreads into a smooth blob, and the total brightness is preserved.
| Filter | Function | Good for |
|---|---|---|
| Gaussian blur | gaussian_filter(img, sigma) |
general smoothing |
| Box blur | uniform_filter(img, size) |
quick averaging |
| Median | median_filter(img, size) |
salt-and-pepper noise, keeps edges |
| Sobel / Prewitt | sobel(img, axis) |
edge detection |
| Laplace | laplace(img) |
finding blobs and fine detail |
| Max / min | maximum_filter, minimum_filter |
local peaks, morphology |
Removing salt-and-pepper noise
Random black and white pixels ("salt and pepper") are handled best by the median filter, which ignores extreme values rather than averaging them in:
import numpy as np
from scipy import ndimage
img = np.full((6, 6), 50)
img[:, 3:] = 200 # a vertical edge
img[1, 1] = 255 # salt
img[4, 4] = 0 # pepper
print("noisy:")
print(img)
print("median 3x3:")
print(ndimage.median_filter(img, size=3))noisy:
[[ 50 50 50 200 200 200]
[ 50 255 50 200 200 200]
[ 50 50 50 200 200 200]
[ 50 50 50 200 200 200]
[ 50 50 50 200 0 200]
[ 50 50 50 200 200 200]]
median 3x3:
[[ 50 50 50 200 200 200]
[ 50 50 50 200 200 200]
[ 50 50 50 200 200 200]
[ 50 50 50 200 200 200]
[ 50 50 50 200 200 200]
[ 50 50 50 200 200 200]]
Both specks vanish and the edge between 50 and 200 stays perfectly sharp.
Edge detection
The Sobel filter estimates the brightness gradient along one axis. Combining both axes gives the edge strength at each pixel:
import numpy as np
from scipy import ndimage
img = np.zeros((8, 8))
img[2:6, 2:6] = 10 # a bright square
gx = ndimage.sobel(img, axis=1) # changes left-right
gy = ndimage.sobel(img, axis=0) # changes up-down
edges = np.hypot(gx, gy)
print(np.round(edges).astype(int))[[ 0 0 0 0 0 0 0 0]
[ 0 14 32 40 40 32 14 0]
[ 0 32 42 40 40 42 32 0]
[ 0 40 40 0 0 40 40 0]
[ 0 40 40 0 0 40 40 0]
[ 0 32 42 40 40 42 32 0]
[ 0 14 32 40 40 32 14 0]
[ 0 0 0 0 0 0 0 0]]
The middle of the square and the background far from it are both zero; only the pixels along the square's border light up.
Labelling objects and measuring them
label() finds connected groups of non-zero pixels and gives each a number. Then measurement functions such as sum, center_of_mass and find_objects work per label — this is how you count cells in a microscope image:
import numpy as np
from scipy import ndimage
mask = np.array([
[0, 1, 1, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 1, 1],
[1, 0, 0, 0, 0, 1, 0],
[1, 1, 0, 0, 0, 0, 0],
])
labels, count = ndimage.label(mask)
print("objects found:", count)
print(labels)
ids = np.arange(1, count + 1)
sizes = ndimage.sum_labels(mask, labels, index=ids)
centres = ndimage.center_of_mass(mask, labels, ids)
for i, size, (r, c) in zip(ids, sizes, centres):
print(f"object {i}: {int(size)} pixels, centre at row {r:.2f}, col {c:.2f}")objects found: 3
[[0 1 1 0 0 0 0]
[0 1 1 0 0 2 0]
[0 0 0 0 2 2 2]
[3 0 0 0 0 2 0]
[3 3 0 0 0 0 0]]
object 1: 4 pixels, centre at row 0.50, col 1.50
object 2: 5 pixels, centre at row 2.00, col 5.00
object 3: 3 pixels, centre at row 3.67, col 0.33
Morphology: erosion, dilation, filling
Binary morphology reshapes masks. Erosion shrinks objects (removing thin bits), dilation grows them, and opening (erode then dilate) deletes small specks while keeping big shapes. binary_fill_holes fills gaps inside shapes:
import numpy as np
from scipy import ndimage
shape = np.array([
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0, 1],
[0, 1, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 1, 0, 0],
[0, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
], dtype=bool)
filled = ndimage.binary_fill_holes(shape)
opened = ndimage.binary_opening(filled, structure=np.ones((2, 2)))
print("filled:")
print(filled.astype(int))
print("opened (speck at top right removed):")
print(opened.astype(int))filled:
[[0 0 0 0 0 0 0]
[0 1 1 1 1 0 1]
[0 1 1 1 1 0 0]
[0 1 1 1 1 0 0]
[0 1 1 1 1 0 0]
[0 0 0 0 0 0 0]]
opened (speck at top right removed):
[[0 0 0 0 0 0 0]
[0 1 1 1 1 0 0]
[0 1 1 1 1 0 0]
[0 1 1 1 1 0 0]
[0 1 1 1 1 0 0]
[0 0 0 0 0 0 0]]
Geometric transforms
rotate, zoom, shift and affine_transform move pixels around, interpolating new values. order=0 uses nearest-neighbour (no new values), higher orders give smoother results:
import numpy as np
from scipy import ndimage
arrow = np.array([
[0, 1, 0],
[1, 1, 1],
[0, 1, 0],
[0, 1, 0],
])
print("rotated 90 degrees:")
print(ndimage.rotate(arrow, 90, order=0))
print("zoomed x2 (nearest):")
print(ndimage.zoom(np.array([[1, 2], [3, 4]]), 2, order=0))
print("shifted one column right:")
print(ndimage.shift(np.array([[1, 2, 3]]), (0, 1), order=0))rotated 90 degrees:
[[0 1 0 0]
[1 1 1 1]
[0 1 0 0]]
zoomed x2 (nearest):
[[1 1 2 2]
[1 1 2 2]
[3 3 4 4]
[3 3 4 4]]
shifted one column right:
[[0 1 2]]
Tip: For full image-processing pipelines (reading files, colour spaces, segmentation algorithms), look at scikit-image, which builds on
scipy.ndimage. For quick filtering and measurement on arrays,ndimagealone is often enough.
Test yourself
Which filter is best for removing salt-and-pepper noise while keeping edges sharp?
- gaussian_filter
- uniform_filter
- median_filter
- sobel
What does ndimage.label(mask) return?
- The edges of the mask
- An array numbering each connected object, plus the number of objects
- The mask's histogram
- The centre of the image
What does a binary opening (erosion followed by dilation) typically do?
- Fills holes
- Removes small specks while keeping larger shapes
- Rotates the image
- Doubles the size of objects