Module 4/15 · Weeks 4 · 9 h

Image segmentation and anomaly detection

UAT 456 Artificial Intelligence, Machine Learning and Computer Vision for UAS

About 95 minDraft, awaiting reviewLast updated 1 October 2026

Lesson

By the end of this module you will be able to

  1. Distinguish semantic, instance and panoptic segmentation and choose a method that suits the task
  2. Segment surfaces with k-means clustering, compute areas in rai and evaluate with IoU and Dice
  3. Separate touching objects with the distance transform and watershed, and state the method's limits
  4. Explain the U-Net deep segmentation model and the use of foundation models to assist labelling
  5. Detect anomalies with the Mahalanobis distance and Isolation Forest from normal data, and set thresholds from an acceptable number of false alerts

Prerequisites: Modules 1 to 3 of this course

Why this matters

A box tells you where a cow is, but cannot answer some of the farm’s questions, such as how many rai of grass are left in this paddock, which decides when to move the herd, or how many animals are in this tight group. These need to know what every pixel is: image segmentation. Another question is which animal is abnormal. Sick cows, cows about to calve, or cattle that have got outside the fence are rare and look different every time, so training a classifier directly is hard. That calls for anomaly detection, which learns what is normal and flags whatever differs.

Image segmentation

Image segmentation labels every pixel, in three forms:

FormOutputOn the farm
SemanticEvery pixel has a class; objects are not separatedGrass, bare soil, water
InstanceEach object of the classes of interest is separatedCow 1, cow 2, cow 3
PanopticBoth in one imageWhole-paddock surfaces plus individual cattle

Methods range from simple to complex: thresholds such as Otsu’s method (UAT 307 module 1), colour clustering, morphology and watershed, and deep models (Szeliski, 2022). Real systems choose the simplest method that meets the requirement, because simple methods are easier to check and fix.

Segmentation is evaluated by comparing the predicted mask with the reference mask per class, using or . The two convert into each other as , so they rank results the same way, but Dice is always higher than IoU unless both are 0 or 1, so a report must say which it uses.

Segmenting with k-means colour clustering

k-means splits pixels into groups without labels: pick starting centres in colour space, assign each pixel to the nearest centre, move each centre to the mean of its group, and repeat until nothing changes (OpenCV). The result is only “cluster 0, 1, 2”; the developer must map each cluster to a surface type, for example by comparing cluster centre colours with reference colours for grass, soil and water. Each surface’s area is , and 1 rai is 1,600 square metres.

Example 1 How many rai of grass does this paddock have?

A synthetic orthomosaic of a paddock is 240 × 200 pixels at a GSD of 1 m, 30 rai in total. It contains a cattle track in front of the pen and a patch of dead grass, both bare soil, and one pond. The image is very noisy. The team compares k-means on the raw image with k-means after a 5 × 5 Gaussian blur (all assumed).

import numpy as np, cv2
from sklearn.cluster import KMeans
# synthetic orthomosaic of a paddock, 240 x 200 px, GSD 1 m per pixel (assumed), BGR colours
rng = np.random.default_rng(7)
truth = np.zeros((200, 240), np.uint8)                       # 0 grass, 1 bare soil, 2 water
cv2.ellipse(truth, (60, 150), (45, 25), 20, 0, 360, 1, -1)   # cattle track in front of the pen
cv2.ellipse(truth, (190, 50), (30, 18), -30, 0, 360, 1, -1)  # dead-grass patch
cv2.circle(truth, (165, 140), 22, 2, -1)                     # pond
colour = np.array([(60, 140, 75), (90, 130, 165), (95, 70, 45)], np.float32)
img = np.clip(colour[truth] + rng.normal(0, 18, (200, 240, 3)), 0, 255).astype(np.uint8)

RAI = 1600.0                                                 # 1 rai = 1,600 square metres
for title, src in (("raw", img), ("blurred 5x5", cv2.GaussianBlur(img, (5, 5), 0))):
    km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(src.reshape(-1, 3).astype(float))
    # map each cluster to the surface whose reference colour is nearest its centre
    to_class = [int(np.argmin(np.linalg.norm(colour - c, axis=1))) for c in km.cluster_centers_]
    pred = np.array(to_class)[km.labels_].reshape(truth.shape)
    print(f"{title}: clusters -> classes {to_class}")
    for k, name in enumerate(["grass", "bare soil", "water"]):
        t, p = truth == k, pred == k
        i, u = np.sum(t & p), np.sum(t | p)
        print(f"  {name:9s} {p.sum() / RAI:5.2f} rai  IoU {i / u:.3f}  Dice {2 * i / (t.sum() + p.sum()):.3f}")
raw: clusters -> classes [0, 0, 1]
  grass     26.55 rai  IoU 0.960  Dice 0.980
  bare soil  3.45 rai  IoU 0.966  Dice 0.983
  water      0.00 rai  IoU 0.000  Dice 0.000
blurred 5x5: clusters -> classes [0, 1, 2]
  grass     25.68 rai  IoU 0.999  Dice 1.000
  bare soil  3.38 rai  IoU 0.997  Dice 0.999
  water      0.95 rai  IoU 0.994  Dice 0.997

On the raw image two of the three clusters map to grass ([0, 0, 1]). Noise spreads out the grass, which covers 86% of the paddock, so k-means spends two clusters on bright and dark grass, and the pond, only 3% of the area, is absorbed into the dark grass. The result reports no water at all, even though grass IoU looks good at 0.960. Blurring first reduces the noise so each surface forms a tighter group, and the three clusters match the three surfaces: 25.68 rai of grass, 3.38 rai of bare soil and 0.95 rai of water, with every class IoU above 0.99. The example shows that image processing from module 1 can change the next step’s results a great deal, and that per-class results must always be checked, because a small class can vanish while the overall average barely moves.

Six horizontal bars of IoU: grass raw 0.960, grass blurred 0.999, bare soil raw 0.966, bare soil blurred 0.997, water raw 0.000 as a tiny pink bar, water blurred 0.994
Figure 1 IoU per surface class from k-means

Separating touching objects with morphology and watershed

Once there is a mask of the cattle (from a threshold or a segmentation model), counting by connected components counts touching animals as one blob. Two groups of tools help (OpenCV):

  • Morphology: erosion thins objects and cuts narrow necks; dilation thickens them; opening (erode then dilate) removes small specks; closing (dilate then erode) fills small holes in objects
  • The distance transform and watershed: the distance transform gives each pixel its distance to the nearest edge, so the middle of a cow’s body has the highest value. A high threshold leaves only each animal’s separate “core”, and these cores seed a watershed that grows outward until regions meet; the meeting lines are the boundaries between animals

Barbedo et al. (2020) used mathematical morphology to separate clustered animals and infer the number of individuals when counting cattle in drone images.

Example 2 How many cows are in this blob?

A cattle mask from one tile at a GSD of 2.5 cm holds two cows touching at an angle and one standing apart (assumed).

import numpy as np, cv2
# cattle mask (255 = cow), GSD 2.5 cm; two cows touching, one standing apart (assumed)
mask = np.zeros((120, 200), np.uint8)
cv2.ellipse(mask, (50, 50), (40, 16), 10, 0, 360, 255, -1)
cv2.ellipse(mask, (105, 65), (40, 16), -40, 0, 360, 255, -1)
cv2.ellipse(mask, (170, 60), (16, 40), 0, 0, 360, 255, -1)

n, _ = cv2.connectedComponents(mask)
print("connected components:", n - 1)

dist = cv2.distanceTransform(mask, cv2.DIST_L2, 5)          # distance to the nearest edge
core = (dist > 0.6 * dist.max()).astype(np.uint8)           # the core of each animal
n_core, markers = cv2.connectedComponents(core)
markers = markers + 1                                       # 1 = sure background
markers[(mask == 255) & (core == 0)] = 0                    # 0 = unknown, left for watershed to decide
labels = cv2.watershed(cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR), markers)
areas = [int(np.sum(labels == k)) for k in range(2, n_core + 1)]
print("after distance transform + watershed:", len(areas))
print("area per cow (m2):", [round(a * 0.025 ** 2, 2) for a in areas])
connected components: 2
after distance transform + watershed: 3
area per cow (m2): [1.21, 1.19, 1.21]

Connected components find 2 blobs because two cows touch. After the distance transform, a threshold at 60% of the maximum leaves three cores, and watershed splits the mask into 3 animals of about 1.2 square metres each, close to the area of an ellipse 2.0 m long and 0.8 m wide, square metres (the small shortfall is the boundary pixels watershed marks as −1). Area per animal also serves as a check: a blob of about 2.4 square metres split into only one animal is probably two that could not be separated. The key limitation is that cattle standing side by side along their whole length form a wide blob whose cores do not separate, so this method cannot split them; an instance segmentation model or detection is needed instead.

Two panels, each with three ellipses: two on the left touching at an angle and one upright on the right. Left panel, connected components, 2 blobs: both touching ellipses are pink. Right panel, distance transform plus watershed, 3 cows: the ellipses are separately pink, yellow and green
Figure 2 Separating touching cows with watershed

Segmenting with deep learning

When colour and shape are not enough, for example cattle in tree shade or dry grass the colour of soil, deep models are needed. U-Net (Ronneberger et al., 2015) has two halves: an encoder that shrinks the image step by step to grasp context, and a decoder that expands it back to full size to label every pixel, with skip connections passing detail straight from encoder to decoder so object edges stay sharp. U-Net and its descendants are therefore a standard choice for semantic segmentation of drone images.

The big problem with segmentation is that pixel-level labelling takes a long time. Foundation models such as Segment Anything take a point or a box as a prompt and return the object’s mask immediately (Kirillov et al., 2023), which speeds annotators up a lot. Annotators must still check and correct every mask, because the model does not know the farm’s labelling policy, such as whether to include the shadow.

Anomaly detection

An anomaly is data that differs significantly from the normal pattern. There are three kinds:

  • Point anomalies: a single value clearly differs from normal, such as a cow 46 m from any other
  • Contextual anomalies: a value normal in one context is abnormal in another; lying still at midday is normal, but lying still all morning while the herd grazes may not be
  • Collective anomalies: each value looks normal but together they are wrong, such as several cattle walking in a line along the same fence

Anomalies are rare and do not repeat, so methods usually learn from normal data and measure how far new data lie from normal. scikit-learn distinguishes outlier detection, where the training data may contain outliers, from novelty detection, where the training data are clean and new data must be judged (scikit-learn developers). Common methods:

MethodPrincipleStrengthWeakness
Per-feature z-scoreHow many standard deviations from the meanSimple and explainableBlind to relationships between features
Mahalanobis distanceDistance accounting for variance and correlation, Catches values abnormal in combination; statistical thresholdsAssumes data are roughly normally distributed
Isolation ForestRandom splitting trees; anomalies are isolated in few splits, so their paths are shortNo distribution assumption; works in many dimensionsThreshold depends on the set proportion; harder to explain
Image models trained on normal imagesLearn what normal images look like and score regions that differCan locate the anomaly in the imageNeeds enough normal images

The MVTec AD dataset, used to benchmark image anomaly detection, provides only normal images for training and images with more than 70 kinds of anomaly for testing, reflecting real work where every kind of anomaly can never be known in advance (Bergmann et al., 2019).

Example 3 Which animals should someone go and check?

From the module 3 tracks, the system computes behaviour features for each animal: distance to the nearest animal and distance walked in 30 minutes. The team uses 600 samples from the previous two weeks as normal data; cattle far from the herd usually walk more, so the two values are correlated. Five animals must be judged today (simulated data).

import numpy as np
from scipy.stats import chi2
from sklearn.ensemble import IsolationForest
# behaviour features from tracks: distance to nearest animal (m) and distance walked in 30 min (m)
rng = np.random.default_rng(42)
# 600 samples from the previous 2 weeks (simulated); cattle far from the herd walk more: correlation 0.7
normal = np.exp(rng.multivariate_normal(np.log([6, 60]), [[0.16, 0.098], [0.098, 0.1225]], 600))
today = {"cow 118": (5.5, 72), "cow 256": (11.0, 33), "cow 311": (46.0, 3),
         "cow 342": (4.8, 4), "cow 407": (38.0, 160)}

Z = np.log(normal)                                          # right-skewed data, so use logarithms
mu, cov_inv = Z.mean(0), np.linalg.inv(np.cov(Z.T))
limit = np.sqrt(chi2.ppf(0.99, df=2))                       # 99 % limit of a 2-D normal distribution
iso = IsolationForest(n_estimators=200, contamination=0.01, random_state=0).fit(Z)
print(f"Mahalanobis limit {limit:.2f}, single-feature limit |z| > 2.58")
sd = Z.std(0)
for name, x in today.items():
    z = np.log(x)
    d = np.sqrt((z - mu) @ cov_inv @ (z - mu))
    zs = (z - mu) / sd
    flag_iso = iso.predict([z])[0] == -1
    print(f"{name}: nn {x[0]:4.1f} m, moved {x[1]:5.1f} m | z {zs[0]:+5.2f} {zs[1]:+5.2f} | D {d:4.2f} {'ALERT' if d > limit else 'ok':5s} | IsoForest {'ALERT' if flag_iso else 'ok'}")
Mahalanobis limit 3.03, single-feature limit |z| > 2.58
cow 118: nn  5.5 m, moved  72.0 m | z -0.24 +0.55 | D 1.02 ok    | IsoForest ok
cow 256: nn 11.0 m, moved  33.0 m | z +1.44 -1.87 | D 4.24 ALERT | IsoForest ALERT
cow 311: nn 46.0 m, moved   3.0 m | z +4.90 -9.30 | D 18.31 ALERT | IsoForest ALERT
cow 342: nn  4.8 m, moved   4.0 m | z -0.57 -8.40 | D 11.14 ALERT | IsoForest ALERT
cow 407: nn 38.0 m, moved 160.0 m | z +4.44 +3.02 | D 4.44 ALERT | IsoForest ALERT

Cow 118 is normal by every method. Cow 256 is the most interesting: its per-feature z-scores, +1.44 and −1.87, are both inside ±2.58, so checking one feature at a time raises no alert, but its Mahalanobis distance is 4.24, above the 3.03 limit. Cattle far from the herd normally walk a lot; this one is far but walks little, so the combination is abnormal. Cow 311 is 46 m from the others and barely moves (); it may be sick or about to calve and should be checked first. Cow 342 is in the herd but not moving and may simply be lying down, which depends on the time of day. Cow 407 is far away and walking a lot, perhaps along a broken fence. Isolation Forest agrees in these cases. All data are log-transformed because distances are positive and right-skewed. An alert is only a prompt for a person to check, not a diagnosis.

Scatter plot on log axes: horizontal, distance to nearest animal; vertical, distance moved in 30 minutes. Six hundred faint blue points form a rising band enclosed by a pink dashed ellipse at Mahalanobis distance 3.03. A green circle, 118, lies inside; pink circles mark 256 just below the ellipse, 311 at bottom right, 342 at bottom left and 407 at top right
Figure 3 Normal cattle behaviour and the Mahalanobis 3.03 boundary

Setting thresholds from an acceptable number of false alerts

A 99% limit means that about 1 in 100 normal animals will be falsely flagged. With 900 cattle checked once a day, that is about false alerts a day, which stock workers may not cope with and will stop trusting. Options are a stricter threshold (99.9% gives about 0.9 a day but misses more borderline cases), alerting only when an animal is abnormal two rounds in a row, or ranking and sending only the top 3 each day. The right threshold therefore comes from agreeing with users how many false alerts they can accept and how many misses they can tolerate, not from statistics alone.

Module lab

Lab: surface maps, counting touching animals and anomaly alerts

  1. Using an orthomosaic of a pasture or a university field, label part of it by hand as a reference, then segment it with k-means as in Example 1, both before and after filtering
  2. Compute each surface’s area in rai and report per-class IoU and Dice
  3. Make a mask of touching objects from a real or synthetic image, try separating them with morphology and watershed as in Example 2, and record the cases that cannot be separated
  4. If time allows, have a foundation model make masks from point clicks and time it against drawing by hand
  5. Using tracks from module 3 or the simulated data in Example 3, detect anomalies with the Mahalanobis distance and Isolation Forest, then compute the false alerts per day for your chosen threshold

Common mistakes

Watch out

  • Assuming k-means clusters are classes without checking the mapping, so small classes disappear
  • Reporting only the overall average IoU or Dice, not per class, or not saying which metric is used
  • Counting cattle by connected components alone, so touching animals count as one
  • Setting the core threshold too low, so the cores of touching animals join, or too high, so small animals vanish
  • Checking for anomalies one feature at a time, missing values that are abnormal only in combination
  • Training an anomaly detector on data that unknowingly contain anomalies, so abnormal becomes normal
  • Setting thresholds from statistics alone without considering how many false alerts a day users can accept

Summary

  • Segmentation comes in three forms (semantic, instance and panoptic) and is evaluated per class with IoU or Dice, where
  • k-means groups pixels by colour without labels, but clusters must be mapped to classes and it is sensitive to noise
  • The distance transform with watershed separates partly touching objects but not objects lying side by side along their length
  • U-Net uses an encoder, a decoder and skip connections; foundation models speed up pixel-level labelling
  • Anomaly detection learns from normal data; the Mahalanobis distance catches values abnormal in combination, and thresholds must reflect the false alerts users can accept

Check your understanding

  1. A reference mask has 1,000 pixels, a predicted mask 900, and they overlap by 800. What are IoU and Dice?
  2. At a GSD of 0.5 m, a pasture covers 25,600 pixels. How many rai is that?
  3. Why does blurring before k-means in Example 1 make the pond appear?
  4. Why is cow 256 not flagged when features are checked one at a time, but flagged by the Mahalanobis distance?
  5. A farm of 900 cattle uses a 99.5% limit once a day. How many false alerts a day should it expect?
Answers
  1. IoU and Dice
  2. square metres rai
  3. Noise spreads out the large grass class, so k-means spends two clusters on grass and absorbs the small water area into dark grass; filtering reduces the noise, each surface forms a tighter group, and the three clusters match the three surfaces
  4. Each value is within its normal range on its own, but normal data are correlated: cattle far from the herd walk a lot. Cow 256 is far but walks little; the Mahalanobis distance accounts for that correlation and so sees it as abnormal
  5. a day

Key formulas

Mask IoU and Dice
Area from a pixel count
Mahalanobis distance
99% limit in 2 dimensions

Key references

  1. OpenCV. K-means clustering in OpenCV. OpenCV 4.x Python tutorials. link
  2. OpenCV. Morphological transformations. OpenCV 4.x Python tutorials. link
  3. OpenCV. Image segmentation with watershed algorithm. OpenCV 4.x Python tutorials. link
  4. Barbedo, J. G. A., Koenigkan, L. V., Santos, P. M., & Ribeiro, A. R. B. (2020). Counting cattle in UAV images: Dealing with clustered animals and animal/background contrast changes. Sensors, 20(7), 2126. https://doi.org/10.3390/s20072126 link
  5. 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
  6. Kirillov, A., et al. (2023). Segment anything. In Proceedings of ICCV 2023 (pp. 3992–4003). link
  7. scikit-learn developers. Novelty and outlier detection (scikit-learn 1.9). scikit-learn user guide. link
  8. Bergmann, P., Fauser, M., Sattlegger, D., & Steger, C. (2019). MVTec AD: A comprehensive real-world dataset for unsupervised anomaly detection. In 2019 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) (pp. 9584–9592). https://doi.org/10.1109/CVPR.2019.00982 link
  9. Szeliski, R. (2022). Computer vision: Algorithms and applications (2nd ed.). Springer. link

Further reading

Study the assigned knowledge units in advance, review media and take the module quiz

In class / field

Lab or field practice from worksheets with a safety checklist

Learning evidence: Checked worksheets and quiz results

Module quiz

This is a formative self-check, not a graded exam

Knowledge domain: Inspection, industry and surveillance · Artificial intelligence and computer vision · Surveying, mapping and geoinformatics