Digital images and cameras
UAT 307 Computer Vision and Perception Technology
Lesson
By the end of this module you will be able to
- Explain a digital image as an array of intensity values and the effect of quantisation
- Write a Sobel edge filter with your own convolution
- Write Otsu's method to choose a threshold from a histogram
- Enhance contrast and remove noise with stretching, histogram equalisation and a median filter
- Explain model-based semantic segmentation and evaluate it with per-class IoU and mIoU
- Choose image-processing steps before AI to suit the task
Why this matters
UAT 205 covered the pinhole camera model and calibration. This course goes deeper into the algorithms behind frequently used functions, so that you can choose and adjust them when real drone images differ from sample images. The drone knowledge base’s unit on computer vision and Edge AI lays these foundations, and its OpenCV unit demonstrates colour, thresholding and edge detection. The textbooks by Szeliski and Corke explain these algorithms in detail. The examples use synthetic data so that answers can be checked.
An image is an array of numbers
An 8-bit greyscale image is a two-dimensional array of values 0–255; a colour image has three channels; a radiometric thermal image stores values that convert to temperature. Quantising to 8 bits loses detail in very dark or very bright areas, and lossy compression adds block noise. Every processing step must therefore know what kind of source data it has.
Edge detection with Sobel
An edge is where brightness changes quickly. The Sobel filter is a 3×3 kernel that approximates the horizontal derivative and vertical derivative , which combine into the gradient magnitude. In drone work it finds crack edges, road lines or roof edges. OpenCV provides cv2.Sobel; this example writes the convolution by hand to show the computation.
Example 1 An edge between dark and bright ground, and a noise pixel
A synthetic 12×12 image: the left half is 60, the right half 180, with one noise pixel of 200.
import numpy as np
img = np.full((12, 12), 60.0)
img[:, 6:] = 180.0
img[3, 2] = 200.0 # noise pixel
kx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
ky = kx.T
def conv(a, k):
out = np.zeros((a.shape[0] - 2, a.shape[1] - 2))
for i in range(out.shape[0]):
for j in range(out.shape[1]):
out[i, j] = (a[i:i + 3, j:j + 3] * k).sum()
return out
mag = np.hypot(conv(img, kx), conv(img, ky))
print(f"largest gradient {mag.max():.0f} at output columns {sorted({int(c) for c in np.argwhere(mag == mag.max())[:, 1]})}")
strong = mag > 200
print(f"pixels above 200: {strong.sum()} (edge columns {sorted({int(c) for c in np.argwhere(strong)[:, 1]})})")
largest gradient 480 at output columns [4, 5]
pixels above 200: 24 (edge columns [0, 1, 2, 4, 5])
The real edge gives the largest gradient in two columns down the whole image, but a single noise pixel also produces values above the threshold in several pixels. With real images, smooth first (for example a Gaussian blur) before finding edges, or use a method such as Canny that includes noise reduction and edge linking.
Choosing a threshold with Otsu’s method
Separating objects from background with a single threshold requires a good choice. Otsu’s method (1979) tries every threshold and chooses the one that maximises the between-class variance , which is equivalent to minimising the weighted within-class variance as the OpenCV tutorial explains. OpenCV applies it through cv2.threshold with the THRESH_OTSU flag.
Example 2 Separating bright roofs from dark ground
An image of 10,000 pixels, with ground averaging 70 and roofs averaging 170 (simulated data).
import numpy as np
rng = np.random.default_rng(3)
pix = np.r_[rng.normal(70, 15, 7000), rng.normal(170, 20, 3000)].clip(0, 255).astype(int)
p = np.bincount(pix, minlength=256) / pix.size
best_var, best_t = 0.0, 0
for t in range(1, 256):
w0, w1 = p[:t].sum(), p[t:].sum()
if w0 == 0 or w1 == 0:
continue
m0 = (np.arange(t) * p[:t]).sum() / w0
m1 = (np.arange(t, 256) * p[t:]).sum() / w1
var_b = w0 * w1 * (m0 - m1) ** 2
if var_b > best_var:
best_var, best_t = var_b, t
print(f"Otsu threshold {best_t}, bright fraction {(pix >= best_t).mean():.1%} (true roof fraction 30%)")
Otsu threshold 120, bright fraction 29.9% (true roof fraction 30%)
The threshold lies between the two histogram peaks, and the bright fraction is close to the true value. The method works well when the histogram has two clear peaks. If lighting is uneven, for example with cloud shadow over half the image, one threshold for the whole image fails, and a local (adaptive) threshold is needed instead.
Image enhancement
Image enhancement changes an image so that people or later algorithms can see what matters more easily. It adds no new information; it redistributes what is already there. Drone images often need it: haze and overcast light squeeze all values into a narrow band, and small sensors add noise in low light. Three basic tools cover most cases (Szeliski, 2022, chapter 3):
- Contrast stretching maps the range of values actually present (for example the 1st to 99th percentile) onto the full 0–255 range with a straight line.
- Histogram equalisation maps each value through the cumulative histogram, so the output values are spread roughly evenly. It helps most when the histogram is confined to a narrow region, as the OpenCV tutorial notes; its local variant CLAHE (contrast-limited adaptive histogram equalisation,
cv2.createCLAHE, default tiles of 8×8) works tile by tile and limits contrast so that noise is not amplified too much. - Denoising filters: a mean or Gaussian filter averages neighbours and blurs edges; a median filter replaces each pixel with the median of its neighbours, which the OpenCV smoothing tutorial describes as highly effective against salt-and-pepper noise (isolated black and white pixels) while keeping edges sharp.
Enhancement is for viewing and for classical steps such as thresholding. Measurements that depend on real values, such as temperature from a radiometric thermal image or reflectance for vegetation indices, must be taken from the original data, never from an enhanced copy.
Example 3 Enhancing a hazy image and removing salt-and-pepper noise
A 60×60 hazy image in which a roof is only about 14 levels brighter than the ground, and a clean edge image with 6% of its pixels turned black or white (simulated data).
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
rng = np.random.default_rng(8)
img = rng.normal(118, 6, (60, 60)) # hazy ground
img[20:40, 15:45] += 14 # a roof only slightly brighter
img = img.clip(0, 255).astype(np.uint8)
roof = np.zeros(img.shape, bool)
roof[20:40, 15:45] = True
lo, hi = np.percentile(img, [1, 99]) # contrast stretch
stretched = ((img.astype(float) - lo) / (hi - lo) * 255).clip(0, 255).astype(np.uint8)
cdf = np.bincount(img.ravel(), minlength=256).cumsum() / img.size
equalised = np.round(255 * cdf[img]).astype(np.uint8) # histogram equalisation
for name, a in (("original", img), ("stretched", stretched), ("equalised", equalised)):
print(f"{name:<9}: range {a.min():>3}-{a.max():>3}, roof minus ground {a[roof].mean() - a[~roof].mean():5.1f}")
noisy = np.full((60, 60), 120, np.uint8)
noisy[:, 30:] = 180 # a clean edge
salt = rng.random(noisy.shape)
noisy[salt < 0.03] = 0
noisy[salt > 0.97] = 255 # 6% salt-and-pepper pixels
windows = sliding_window_view(np.pad(noisy, 1, mode="edge"), (3, 3))
mean3 = windows.mean(axis=(2, 3))
median3 = np.median(windows, axis=(2, 3))
clean = np.where(np.arange(60) < 30, 120, 180)[None, :].repeat(60, axis=0)
for name, a in (("noisy", noisy), ("3x3 mean", mean3), ("3x3 median", median3)):
print(f"{name:<10}: pixels more than 20 from the clean value {np.mean(np.abs(a - clean) > 20):.1%}")
original : range 99-149, roof minus ground 14.1
stretched: range 0-255, roof minus ground 96.2
equalised: range 0-255, roof minus ground 111.1
noisy : pixels more than 20 from the clean value 6.1%
3x3 mean : pixels more than 20 from the clean value 5.1%
3x3 median: pixels more than 20 from the clean value 0.0%
The original uses only 99–149 of the 256 levels, and the roof stands out by just 14 levels. Stretching and equalisation spread the values over the full range and make the difference about seven to eight times larger, so a threshold or a person can separate the roof easily. Equalisation also stretches the noise, which is why CLAHE limits the contrast. For salt-and-pepper noise, a 3×3 mean hardly helps, because it spreads each bad pixel over its neighbours, while the 3×3 median removes it completely and keeps the edge where it was.
From thresholds to model-based segmentation
Image segmentation assigns a label to every pixel. Otsu’s threshold is the simplest form, but it uses brightness alone: a grey roof, a road and dry ground may have the same brightness. Semantic segmentation with a neural network labels every pixel with a class (ground, roof, water, road and so on) using the surrounding context learned from labelled examples. The fully convolutional network (FCN, Long et al., 2015) showed that a classification network can be turned into one that outputs a score map for every class; U-Net (Ronneberger et al., 2015) added an encoder–decoder shape with skip connections that recover fine boundaries. The output is one score map per class, and each pixel takes the class with the highest score.
Segmentation is evaluated per class with the IoU of the predicted and true pixel sets, averaged over classes as the mean IoU (mIoU). Pixel accuracy alone is misleading, because large classes such as ground dominate it. Drone datasets such as RescueNet, collected by UAV after Hurricane Michael, provide pixel-level labels for buildings, roads, pools, trees and other classes for training and testing such models.
Example 4 From score maps to a label map, and mIoU
A 40×40 scene with ground, one roof and a narrow canal. A segmentation model outputs a score map for each class; the model is less confident about water (simulated score maps).
import numpy as np
rng = np.random.default_rng(5)
CLASSES = ["ground", "roof", "water"]
truth = np.zeros((40, 40), int)
truth[5:20, 8:30] = 1 # a roof
truth[30:34, :] = 2 # a narrow canal
scores = np.zeros((3, 40, 40)) # the model's score maps, one per class
for c, strength in ((0, 2.0), (1, 2.0), (2, 1.0)): # the model is less sure about water
scores[c] = strength * (truth == c) + rng.normal(0, 0.8, truth.shape)
pred = scores.argmax(axis=0) # each pixel takes the highest-scoring class
print(f"pixel accuracy {np.mean(pred == truth):.3f}")
ious = []
for c, name in enumerate(CLASSES):
inter = np.sum((pred == c) & (truth == c))
union = np.sum((pred == c) | (truth == c))
ious.append(inter / union)
print(f"IoU {name:<6} {ious[-1]:.3f} (true pixels {np.sum(truth == c)})")
print(f"mIoU {np.mean(ious):.3f}")
pixel accuracy 0.907
IoU ground 0.903 (true pixels 1110)
IoU roof 0.782 (true pixels 330)
IoU water 0.534 (true pixels 160)
mIoU 0.740
Pixel accuracy is 0.907, which looks good, but water, the smallest class and the one a flood survey actually needs, has an IoU of only 0.534. The mIoU of 0.740 reveals this. When reporting segmentation, always give IoU for each class, and look at the classes that matter to the mission rather than the overall figure.
Module lab
Lab: from formula to OpenCV
- Run Example 1 and compare the result with
cv2.Sobelon the same image - Apply a Gaussian blur before finding edges and observe the effect on the noise pixel
- Run Example 2 and compare with
cv2.threshold(..., cv2.THRESH_OTSU) - Try a real drone image of roofs with cloud shadow, comparing a single threshold with an adaptive threshold
- Apply
cv2.createCLAHEandcv2.medianBlurto a hazy or noisy drone image and compare with Example 3 - Run a pretrained segmentation model on a few drone images supplied by the lecturer, hand-label one image and compute per-class IoU and mIoU as in Example 4
- Write a summary of which tasks suit classical image processing and which suit AI
Common mistakes
Watch out
- Finding edges on noisy images without smoothing first
- Using one threshold for the whole image when lighting is uneven
- Processing heavily compressed JPEGs and expecting fine detail
- Reading meaning into the colours of a non-radiometric thermal image
- Calling functions without knowing their parameters, such as kernel size
- Measuring temperature or reflectance on an enhanced image instead of the original data
- Reporting only pixel accuracy for segmentation, which hides poor small classes
Summary
- A digital image is an array of numbers; know the source data type before processing
- Sobel approximates the brightness derivative; high gradient magnitude marks edges but is sensitive to noise
- Otsu chooses the threshold that maximises between-class variance and suits two-peaked histograms
- Uneven lighting needs local methods
- Stretching and histogram equalisation spread values for viewing; a median filter removes salt-and-pepper noise and keeps edges
- Model-based segmentation labels every pixel from learned context; report IoU per class and mIoU
Check your understanding
- Which filter should remove isolated black and white pixels while keeping edges sharp, and why?
- With background 60 and edge value 180, what is the largest horizontal Sobel response at a vertical edge?
- A segmentation result has pixel accuracy 0.95 but water IoU 0.4. What does this mean?
- What criterion does Otsu’s method use to choose the threshold?
- If half the image has cloud shadow, which kind of threshold should be used?
Answers
- A median filter, because an isolated extreme value never becomes the median of its neighbourhood, while a mean spreads it over the neighbours
- The large classes are right, but the small water class is poorly found; judge by per-class IoU for the classes the mission needs
- Maximum between-class variance
- A local (adaptive) threshold
Key formulas
| Histogram equalisation | |
| Mean IoU over C classes | |
| Sobel gradient magnitude | |
| Otsu's criterion |
Key references
- Szeliski, R. (2022). Computer vision: Algorithms and applications (2nd ed.). Springer. link
- Corke, P. (2023). Robotics, vision and control: Fundamental algorithms in Python. Springer. link
- Otsu, N. (1979). A threshold selection method from gray-level histograms. IEEE Transactions on Systems, Man, and Cybernetics, 9(1), 62–66. link
- OpenCV. Image thresholding (Otsu's binarization). OpenCV 4.x tutorials. link
- OpenCV. OpenCV documentation. link
- OpenCV. Histograms 2: Histogram equalization. OpenCV 4.x Python tutorials. link
- OpenCV. Smoothing images. OpenCV 4.x Python tutorials. link
- Long, J., Shelhamer, E., & Darrell, T. (2015). Fully convolutional networks for semantic segmentation. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2015) (pp. 3431-3440). https://doi.org/10.1109/CVPR.2015.7298965 link
- Ronneberger, O., Fischer, P., & Brox, T. (2015). U-Net: Convolutional networks for biomedical image segmentation. In Medical Image Computing and Computer-Assisted Intervention (MICCAI 2015) (Lecture Notes in Computer Science, pp. 234-241). Springer. https://doi.org/10.1007/978-3-319-24574-4_28 link
- Rahnemoonfar, M., Chowdhury, T., & Murphy, R. (2023). RescueNet: A high resolution UAV semantic segmentation dataset for natural disaster damage assessment. Scientific Data, 10, 913. link
Further reading
Study the assigned knowledge units in advance, review media and take the module quiz
In class / field
Lecture, case discussion and in-class problem solving
Learning evidence: Quiz results and submitted exercises