Computer vision
UAT 315 Artificial Intelligence, Data Analytics and Computer Vision for Unmanned Aircraft Systems
Lesson
By the end of this module you will be able to
- Explain convolution and use OpenCV to segment objects by colour, count them and find their boxes
- Explain the structure of a convolutional neural network (CNN) and its development from LeNet to ResNet
- Distinguish image classification, object detection and segmentation, and explain the detection pipeline including NMS
- Track an object with a simple Kalman filter, and fuse GNSS with an IMU in a worked calculation
Why this matters
A camera is the cheapest, most informative sensor on a drone. Computer vision lets drones find disaster victims, count trees, inspect cracks or follow objects. The methods range from classical image processing, where every step can be explained, to deep learning, which is more accurate but needs careful data and evaluation. Users must know what each method can do and where it fails.
Convolution and image processing
Convolution slides a small filter (kernel) across the image, multiplying and summing values at each position. Different filters give different effects, such as blurring or edge finding. A horizontal Sobel filter responds strongly where brightness changes from left to right.
import numpy as np
image = np.array([[10, 10, 10, 200, 200],
[10, 10, 10, 200, 200],
[10, 10, 10, 200, 200],
[10, 10, 10, 200, 200]], dtype=float)
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=float)
out = np.zeros((image.shape[0] - 2, image.shape[1] - 2))
for i in range(out.shape[0]):
for j in range(out.shape[1]):
out[i, j] = np.sum(sobel_x * image[i:i + 3, j:j + 3])
print(out)
[[ 0. 760. 760.]
[ 0. 760. 760.]]
The response is zero where brightness is constant and high at the boundary between 10 and 200, which is the object’s edge. In a CNN, filters like this are not designed by people; they are learned from data.
Example 1 Finding orange boxes on grass with OpenCV
Build a synthetic 120 × 160 image with a noisy green background and three orange boxes, then isolate orange in the HSV colour space (hue, saturation, value), which separates colours more easily than BGR.
import cv2
rng = np.random.default_rng(345)
frame = np.full((120, 160, 3), (60, 130, 70), np.uint8)
frame = np.clip(frame.astype(int) + rng.integers(-15, 16, frame.shape), 0, 255).astype(np.uint8)
truth = [(20, 30, 16, 12), (90, 70, 20, 14), (130, 20, 10, 10)]
for x, y, w, h in truth:
frame[y:y + h, x:x + w] = (20, 120, 240)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (5, 150, 150), (25, 255, 255))
count, labels, stats, centroids = cv2.connectedComponentsWithStats(mask)
found = sorted(tuple(int(v) for v in s[:4]) for s in stats[1:])
print("objects found:", count - 1)
print("boxes (x, y, w, h):", found)
objects found: 3
boxes (x, y, w, h): [(20, 30, 16, 12), (90, 70, 20, 14), (130, 20, 10, 10)]
This method is simple and fully explainable, but it only works when objects have a distinctive colour and the light is steady. Shadows, evening light or similarly coloured objects break the fixed colour range at once, which is why real systems use deep learning.
Convolutional neural networks
A CNN (convolutional neural network) stacks many convolution layers. Early layers learn edges and colours; deeper layers learn shapes and objects. Pooling layers shrink the data, and fully connected layers decide the class.
| Year | Work | Key point |
|---|---|---|
| 1998 | LeNet (LeCun et al.) | A CNN reading handwritten digits |
| 2012 | AlexNet (Krizhevsky et al.) | A deep CNN on GPUs won the ImageNet challenge by a wide margin |
| 2016 | ResNet (He et al.) | Skip (residual) connections made very deep networks trainable |
| 2016 | YOLO (Redmon et al.) | Detects objects in the whole image in one pass, fast enough for real time |
| 2023 | Segment Anything (Kirillov et al.) | A segmentation model that works on varied images without retraining |
Classify, detect and segment
- Image classification says what the whole image is, e.g. “contains flooding”
- Object detection says which objects are where, as rectangular boxes with confidence scores
- Segmentation gives a class for every pixel, e.g. water, road, building
The YOLO family is a popular detector on drones. Ultralytics’ newest release at the time of writing is YOLO26 (January 2026). It is licensed AGPL-3.0; closed-source products need a paid Enterprise licence, as the drone knowledge hub’s unit on computer vision and edge AI warns.
A detector often outputs several overlapping boxes on one object. NMS (non-maximum suppression) keeps the highest-scoring box and removes others that overlap it beyond a threshold. Overlap is measured with IoU: the intersection area divided by the union area.
def iou(a, b):
ax, ay, aw, ah = a
bx, by, bw, bh = b
inter_w = max(0, min(ax + aw, bx + bw) - max(ax, bx))
inter_h = max(0, min(ay + ah, by + bh) - max(ay, by))
inter = inter_w * inter_h
return inter / (aw * ah + bw * bh - inter)
def nms(boxes, scores, iou_threshold=0.5):
order = sorted(range(len(boxes)), key=lambda i: scores[i], reverse=True)
keep = []
for i in order:
if all(iou(boxes[i], boxes[k]) < iou_threshold for k in keep):
keep.append(i)
return keep
candidates = [(88, 69, 22, 15), (90, 70, 20, 14), (92, 72, 19, 13), # three boxes stacked on one object
(20, 30, 16, 12), # a separate, isolated object
(40, 40, 20, 20), (55, 40, 20, 20)] # two adjacent objects
scores = [0.81, 0.93, 0.66, 0.88, 0.90, 0.85]
print("IoU of box 0 and box 1 (duplicates):", round(iou(candidates[0], candidates[1]), 3))
print("IoU of box 4 and box 5 (adjacent objects):", round(iou(candidates[4], candidates[5]), 3))
for t in (0.5, 0.1):
keep = nms(candidates, scores, t)
print(f"threshold {t}: kept {len(keep)} boxes, scores {[scores[i] for i in keep]}")
IoU of box 0 and box 1 (duplicates): 0.848
IoU of box 4 and box 5 (adjacent objects): 0.143
threshold 0.5: kept 4 boxes, scores [0.93, 0.9, 0.88, 0.85]
threshold 0.1: kept 3 boxes, scores [0.93, 0.9, 0.88]
Read the result group by group.
- Duplicate boxes. The first three boxes cover the same object. The IoU of box 0 and box 1 is as high as 0.848 (box 0 with box 2 is 0.598 and box 1 with box 2 is 0.695, also above 0.5). NMS keeps only the 0.93 box and removes the other two.
- An isolated object. Box 3 overlaps no other box, so its IoU is 0 and it is always kept.
- Two adjacent objects. Boxes 4 and 5 overlap only partly: the overlap is 5 wide and 20 high, which is 100, and the union is , so IoU . At a threshold of 0.5 this is below the threshold, so both boxes are kept (4 boxes remain). Lower the threshold to 0.1 and 0.143 exceeds it, so the 0.85 box is removed and a real object is lost (3 boxes remain).
The NMS IoU threshold must therefore lie between two values: above the IoU of different but adjacent objects (0.143 in this example) and below the IoU of duplicate boxes on one object (0.598 to 0.848 here). Set too low, two adjacent objects are cut down to one.
Tracking and data fusion
Frame-by-frame detection does not know whether a box in this frame and the last is the same object. Tracking links results across frames and uses a motion model to reduce noise. The Kalman filter, proposed by Kalman in 1960, blends predictions from a model with measurements, weighting each by its uncertainty. The same idea drives sensor fusion, such as combining GNSS with the IMU in a flight controller.
Example 2 Tracking a moving object
An object moves 2 m per frame, and positions measured from images have an error with standard deviation 1.5 m. Use a one-dimensional constant-velocity Kalman filter.
steps, speed, meas_sd = 30, 2.0, 1.5
truth_pos = speed * np.arange(steps)
measured = truth_pos + rng.normal(0, meas_sd, steps)
F = np.array([[1.0, 1.0], [0.0, 1.0]])
H = np.array([[1.0, 0.0]])
Q = np.diag([0.01, 0.01])
R = np.array([[meas_sd ** 2]])
x = np.array([measured[0], 0.0])
P = np.diag([R[0, 0], 4.0])
estimates = []
for z in measured:
x = F @ x
P = F @ P @ F.T + Q
K = P @ H.T @ np.linalg.inv(H @ P @ H.T + R)
x = x + (K @ (np.array([z]) - H @ x)).ravel()
P = (np.eye(2) - K @ H) @ P
estimates.append(x[0])
estimates = np.array(estimates)
rmse = lambda e: np.sqrt(np.mean(e ** 2))
print(f"RMSE of raw measurements (last 20 frames) {rmse(measured[10:] - truth_pos[10:]):.2f} m")
print(f"RMSE of Kalman estimates (last 20 frames) {rmse(estimates[10:] - truth_pos[10:]):.2f} m")
print(f"estimated speed {x[1]:.2f} m per frame")
RMSE of raw measurements (last 20 frames) 1.61 m
RMSE of Kalman estimates (last 20 frames) 0.68 m
estimated speed 1.97 m per frame
After a few frames the filter gives positions far closer to the truth than the raw measurements, and it also estimates the speed, which was never measured. The filter has not settled in the first frames, so both are compared over the same last 20 frames.
Example 3 Fusing GNSS with an IMU
A survey drone flies a straight line. The IMU (inertial measurement unit) measures acceleration 10 times a second but has a small constant error, called a bias; integrating it twice makes the position drift further and further. GNSS gives a position once a second that does not drift but scatters by about 1.5 m. The flight controllers of PX4 and ArduPilot fuse them with an extended Kalman filter that also estimates the IMU biases (PX4 lists accelerometer and gyro biases among its EKF states). Groves (2013) describes this loosely coupled GNSS/INS integration in detail.
One update by hand. From the IMU, the filter predicts a position of 105.0 m with variance m². A GNSS fix reads 102.5 m with variance m².
- Kalman gain
- Updated position m
- Updated variance m², a standard deviation of 1.2 m, smaller than either source alone (2.0 m and 1.5 m)
A whole flight. The code runs 60 s with the IMU at 10 Hz, GNSS at 1 Hz and a GNSS outage from 30 to 40 s, for example under a bridge. The state holds position, velocity and the accelerometer bias.
rng_f = np.random.default_rng(2569)
dt, n = 0.1, 600 # IMU at 10 Hz for 60 s
t = dt * np.arange(1, n + 1)
acc_true = np.where(t <= 10, 0.5, 0.0) # speed up for 10 s, then cruise at 5 m/s
vel_true = np.cumsum(acc_true) * dt
pos_true = np.cumsum(vel_true) * dt
acc_imu = acc_true + 0.05 + rng_f.normal(0, 0.1, n) # accelerometer: bias 0.05 m/s² plus noise
has_gnss = (np.arange(1, n + 1) % 10 == 0) & ((t < 30) | (t > 40)) # 1 Hz, outage from 30 to 40 s
gnss = pos_true + rng_f.normal(0, 1.5, n) # GNSS position error sd 1.5 m
# state x = [position, velocity, accelerometer bias]
F = np.array([[1.0, dt, -0.5 * dt ** 2], [0.0, 1.0, -dt], [0.0, 0.0, 1.0]])
B = np.array([0.5 * dt ** 2, dt, 0.0])
H = np.array([[1.0, 0.0, 0.0]])
Q = np.diag([1e-5, 1e-4, 1e-7])
R = np.array([[1.5 ** 2]])
x, P = np.zeros(3), np.diag([1.0, 1.0, 0.01])
dr = np.zeros(2) # IMU-only dead reckoning [position, velocity]
fused, deadr = [], []
for k in range(n):
dr = dr + np.array([dr[1] * dt + 0.5 * dt ** 2 * acc_imu[k], dt * acc_imu[k]])
x = F @ x + B * acc_imu[k] # predict with the IMU
P = F @ P @ F.T + Q
if has_gnss[k]: # correct with GNSS when a fix arrives
K = P @ H.T @ np.linalg.inv(H @ P @ H.T + R)
x = x + (K @ (np.array([gnss[k]]) - H @ x)).ravel()
P = (np.eye(3) - K @ H) @ P
fused.append(x[0]); deadr.append(dr[0])
fused, deadr = np.array(fused), np.array(deadr)
rms = lambda e: float(np.sqrt(np.mean(np.square(e))))
out = (t > 30) & (t < 40)
print(f"IMU only: error after 60 s {deadr[-1] - pos_true[-1]:+.1f} m")
print(f"GNSS only: RMS error {rms(gnss[has_gnss] - pos_true[has_gnss]):.2f} m at {int(has_gnss.sum())} fixes")
print(f"fused: RMS error {rms(fused - pos_true):.2f} m, worst during the outage {np.abs(fused - pos_true)[out].max():.2f} m")
print(f"estimated accelerometer bias {x[2]:.3f} m/s² (true 0.050)")
IMU only: error after 60 s +86.7 m
GNSS only: RMS error 1.49 m at 49 fixes
fused: RMS error 1.15 m, worst during the outage 2.89 m
estimated accelerometer bias 0.059 m/s² (true 0.050)
The IMU alone drifts 86.7 m in one minute because a bias of only 0.05 m/s² is integrated twice (about m). GNSS alone does not drift but is noisy and arrives only once a second. Fused, the error is smaller than GNSS alone, the position is available 10 times a second, and during the 10 s outage the error grows to only 2.89 m because the filter has learned the bias. Multisensor analysis therefore needs three things beyond the formula: common timestamps (each IMU sample must be matched to the right GNSS fix), the same frame and units, and honest noise values and ; wrong values make the filter trust the wrong sensor.
Class activity
Activity: matching vision methods to tasks
- For three tasks, counting oil palms, assessing flooded area and finding victims at night, choose classification, detection or segmentation, and which camera to use.
- In Example 1, add a shadow by halving the brightness of one box, and see how colour segmentation fails. Discuss why a CNN can cope.
- Lower the NMS IoU threshold to 0.1 for boxes on two adjacent objects (boxes 4 and 5 in the code) and explain the result. Then slide the boxes closer, a little at a time, and find the IoU at which NMS at 0.5 starts to remove one of them.
- Read the knowledge unit on AI for screening disaster imagery and summarise why model output should be a list for checking, not a verdict.
Common mistakes
Watch out
- Using fixed colour ranges where the light changes
- Using image classification when you need the positions of several objects
- Setting the NMS threshold too low, so adjacent objects vanish
- Treating confidence as the probability of being right without checking on test data
- Not checking model and data licences before commercial use
- Fusing sensors without aligning timestamps and frames, or with made-up noise values
Summary
- Convolution slides a filter over the image; classical processing is explainable but fragile under changing light
- CNNs learn their filters from data, evolving from LeNet to ResNet and detectors such as YOLO
- Classification, detection and segmentation answer different questions; detectors need a confidence threshold and NMS
- The Kalman filter blends predictions and measurements for tracking and sensor fusion; fusing GNSS with an IMU gives a fast, drift-free position and estimates the IMU bias
Check your understanding
- “Label every pixel as water or not” is which kind of task?
- Two boxes of 50 px² each overlap by 25 px². What is their IoU?
- A prediction of 50.0 m has variance 1.0 m² and a GNSS fix of 52.0 m has variance 3.0 m². What is the fused position?
- What does NMS do?
- When does a Kalman filter give more weight to the measurement?
Answers
- Semantic segmentation
- The union is , so IoU
- , so m, with variance m²
- It removes overlapping boxes on one object, keeping the highest-scoring box
- When the measurement uncertainty is small compared with the prediction uncertainty, making close to 1
Key formulas
| 2-D convolution (as used in CNNs) | |
| Intersection over union | |
| Kalman filter update step |
Key references
- Szeliski, R. (2022). Computer vision: Algorithms and applications (2nd ed.). Springer. link
- OpenCV. OpenCV documentation. link
- LeCun, Y., Bottou, L., Bengio, Y., & Haffner, P. (1998). Gradient-based learning applied to document recognition. Proceedings of the IEEE, 86(11), 2278–2324. link
- Krizhevsky, A., Sutskever, I., & Hinton, G. E. (2012). ImageNet classification with deep convolutional neural networks. Advances in Neural Information Processing Systems 25. link
- He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep residual learning for image recognition. In Proceedings of CVPR 2016 (pp. 770–778). link
- Redmon, J., Divvala, S., Girshick, R., & Farhadi, A. (2016). You only look once: Unified, real-time object detection. In Proceedings of CVPR 2016 (pp. 779–788). link
- Ultralytics. Models supported by Ultralytics (YOLO11, YOLO26). Ultralytics documentation. link
- Kirillov, A., et al. (2023). Segment anything. In Proceedings of ICCV 2023 (pp. 3992–4003). link
- Kalman, R. E. (1960). A new approach to linear filtering and prediction problems. Journal of Basic Engineering, 82(1), 35–45. link
- Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep learning. MIT Press. link
- Welch, G., & Bishop, G. (2004). An introduction to the Kalman filter (Tech. Rep. TR 95-041). Department of Computer Science, University of North Carolina at Chapel Hill. link
- Groves, P. D. (2013). Principles of GNSS, inertial, and multisensor integrated navigation systems (2nd ed.). Artech House. link
- PX4 Autopilot. Using PX4's navigation filter (EKF2). PX4 user guide (main). link
- ArduPilot Dev Team. Extended Kalman filter (EKF). ArduPilot Copter documentation. link
Further reading
Study the assigned knowledge units in advance, review media and take the module quiz
Computer vision and the path to edge AI
การเรียนรู้เชิงลึกและ CNN
GeoAI and publishing maps
AI for screening imagery and damage
In class / field
Lecture, case discussion and in-class problem solving
Learning evidence: Quiz results and submitted exercises