Module 1/15 · Weeks 1 · 9 h

Image-data preparation and image processing

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

About 90 minDraft, awaiting reviewLast updated 24 October 2026

Lesson

By the end of this module you will be able to

  1. Explain the pipeline of an intelligent image-analysis system from capture to reporting and monitoring
  2. Plan image-data preparation, including data scope, labelling policy, dataset documentation and privacy
  3. Compute object size in pixels and the number of overlapping tiles for small objects in drone images
  4. Balance colour and standardise pixel values without leaking test data into training
  5. Augment data by flipping and rotating images while transforming box coordinates correctly and verifiably

Prerequisites: UAT 306 Artificial Intelligence for UAS · UAT 307 Computer Vision and Perception Technology

Why this matters

A working image-analysis system is much more than one clever model. Models that score well in the lab often fail in the field because of things that look minor: shrinking the image until objects are a few pixels wide, morning colours that differ from midday, or label boxes that drift after an image is rotated. UAT 306 and UAT 307 taught the principles of machine learning and computer vision; this course builds on them to construct a whole image-analysis system, from raw data to a report users can trust.

Modules 1 to 5 of the course follow one fictional case through all of them: a beef cattle farm in north-eastern Thailand with several pasture paddocks and about 900 Brahman-cross cattle hires a university engineering team to build a system that uses drone images every morning to count cattle in each paddock, count animals passing through the pen gate, estimate pasture cover and flag animals behaving unusually. All numbers, names and data in this course are fictional. Work of this kind is backed by research, for example detecting cattle in drone images with convolutional neural networks (Barbedo et al., 2019). The Python code can be downloaded from /downloads/uat-456/.

The pipeline of an intelligent image-analysis system

An intelligent image-analysis system is a chain of steps that takes images in and puts out results someone can act on, such as “paddock 3 holds 152 cattle” or “cow 311 has been far from the herd and has not moved for 30 minutes”. The steps form a pipeline, as in Figure 1.

Six boxes joined by arrows: 1 Capture, 2 Prepare image data, 3 Process images, 4 Models, 5 Post-process, 6 Report and alert. The top row runs left to right and the bottom row right to left. Below is a long box, Evaluate and monitor the whole system, with a dashed arrow from the report box
Figure 1 Pipeline of an intelligent image-analysis system
StepMain workOn the cattle farm
CapturePlan flights, set the cameraFly every morning at 07:00, 180 stills per flight, plus video at the pen gate
Prepare image dataSelect images, label, split, tileBox every animal; split by date and paddock
Process imagesAdjust colour, reduce noise, resizeFix the yellow cast of morning images
ModelsClassify, detect, segment, find anomaliesDetect cattle; segment pasture
Post-processMerge tile results, track, countMerge duplicate boxes; count animals through the gate
Report and alertSummarise for decisionsHead count per paddock and a list of animals to check

The step most often forgotten is evaluating and monitoring the whole system: measuring whether the final outputs are right, then going back to fix the data or the model (module 5). Errors early in the chain always propagate, so the whole pipeline must be designed together rather than piece by piece.

Preparing image data

A model can learn only as much as its data and labels support. Image-data preparation has five main tasks.

  1. Define the data scope: write down the conditions the system must work in, such as flight height and GSD, time of day, season, coat colour and background (green grass in the wet season, dry grass in the dry season, bare soil), then collect images covering all of them. If only wet-season images are collected, the system will fail in the dry season
  2. Write a labelling policy, for example “box every animal with at least half its body visible; calves use the same class; animals under tree cover with less than half visible are labelled ‘uncertain’”. Have two annotators label the same images to measure agreement, as taught in UAT 306 module 3
  3. Split the data by similar groups: images taken seconds apart are nearly identical, so if one is in training and the other in testing, scores are inflated. Split by flight date and paddock, for example paddocks 1 to 4 for training, 5 for validation and 6 for testing
  4. Write a datasheet for the dataset recording why it was created, its composition, how it was collected, recommended uses and limitations (Gebru et al., 2021), for example “no images taken in rain; no images from below 60 m”
  5. Protect personal data: drone images may show farm workers or neighbours who can be identified. Identifiable data falls under Thailand’s Personal Data Protection Act B.E. 2562 (2019): state the purpose, collect only what is needed, and blur or crop people out before sending images to outside annotators

Small objects in large images, and tiling

Drone camera images are thousands of pixels wide, but most detection models take a fixed input such as 640 × 640 pixels. Shrinking the whole image to 640 pixels makes small objects disappear. The fix is to split the image into overlapping tiles and process each tile separately, which clearly improves detection of small objects (Akyon et al., 2022). An object’s size in pixels is , where is its real length. The number of tiles across is , where is the image width, the tile size and the overlap, with the last tile shifted to sit against the image edge.

Example 1 Shrink the whole image, or tile it?

The camera image is 5,472 × 3,648 pixels, flown at a height giving a GSD of 2.5 cm. Seen from above, a cow is about 2.0 m long and 0.8 m wide. The model takes 640-pixel input, and the team chooses a 128-pixel overlap (assumed).

import math
# image 5,472 x 3,648 px, GSD 2.5 cm; a cow seen from above is about 2.0 m by 0.8 m (assumed)
img_w, img_h, gsd = 5472, 3648, 0.025
cow_len, cow_wid = 2.0, 0.8
tile, overlap = 640, 128                  # tile size and overlap (px)

cow_px = cow_len / gsd
print(f"cow in the full image: {cow_px:.0f} x {cow_wid / gsd:.0f} px")
s = tile / img_w                          # shrink the whole image to 640 px wide
print(f"cow after shrinking the whole image to {tile} px: {cow_px * s:.1f} x {cow_wid / gsd * s:.1f} px")
stride = tile - overlap
nx = math.ceil((img_w - tile) / stride) + 1
ny = math.ceil((img_h - tile) / stride) + 1
print(f"stride {stride} px: {nx} x {ny} = {nx * ny} tiles per image")
print(f"overlap {overlap} px covers a whole cow ({cow_px:.0f} px): {overlap >= cow_px}")
print(f"pixels processed / pixels in image: {nx * ny * tile * tile / (img_w * img_h):.2f}")
cow in the full image: 80 x 32 px
cow after shrinking the whole image to 640 px: 9.4 x 3.7 px
stride 512 px: 11 x 7 = 77 tiles per image
overlap 128 px covers a whole cow (80 px): True
pixels processed / pixels in image: 1.58

In the full image a cow is 80 × 32 pixels, but shrinking the whole image to 640 pixels leaves it at 9.4 × 3.7 pixels, too small to tell from a termite mound or a rock. Tiling keeps the cow at 80 × 32 pixels and gives 77 tiles per image. The 128-pixel overlap is longer than a cow, so every animal appears whole in at least one tile. The price is 1.58 times as many pixels to process, plus duplicate boxes from overlapping tiles that must be merged (module 3).

A pale green rectangle stands for a 5,472 by 3,648 pixel image, overlaid by a blue grid of 11 columns and 7 rows of overlapping tiles. One tile is highlighted in pink and contains a small yellow ellipse showing one cow to scale
Figure 2 Splitting one image into 77 overlapping tiles

Image processing

Image processing transforms pixel values to suit the next step (Szeliski, 2022). Common tasks in real systems include colour balancing, brightness adjustment, noise reduction (used in module 4), resizing and standardising pixel values before the model. UAT 307 covered edge filters, Otsu thresholding and histogram equalisation; this section focuses on two issues that affect the whole pipeline: colour that changes with the light, and standardisation that does not leak data.

Gray-world colour balance assumes the whole image should average to grey, so each colour channel is multiplied by , where is the mean of channel and the mean of all three.

Standardisation converts pixel values to so the model trains stably. and must be computed from the training set only, then the same values applied to validation, test and every real image. Computing them from all data including the test set leaks test information into training.

Example 2 Fixing a yellow morning cast

Morning light gives the image a yellow cast; the channel means are R 142, G 128, B 96. The team tries gray-world balancing on pixels of a white cow, a red-brown cow and dry grass, then standardises with values from the training set (assumed).

import numpy as np
# channel means (R, G, B) of a yellow-cast morning image, and sample pixels (assumed)
mean_rgb = np.array([142.0, 128.0, 96.0])
pixels = {"white Brahman cow": [228, 214, 168], "red-brown cow": [150, 92, 60],
          "dry grass": [170, 150, 100]}

gain = mean_rgb.mean() / mean_rgb         # gray-world: make every channel mean equal
print("gain R G B:", np.round(gain, 3))
for name, p in pixels.items():
    out = np.clip(np.array(p) * gain, 0, 255)
    print(f"{name:17s} {p} -> {np.round(out).astype(int).tolist()}")

train_mean, train_std = np.array([0.47, 0.49, 0.41]), np.array([0.21, 0.19, 0.18])   # from the training set only (assumed)
x = np.array([228, 214, 168]) * gain / 255
print("standardised white cow:", np.round((x - train_mean) / train_std, 2))
gain R G B: [0.859 0.953 1.271]
white Brahman cow [228, 214, 168] -> [196, 204, 214]
red-brown cow     [150, 92, 60] -> [129, 88, 76]
dry grass         [170, 150, 100] -> [146, 143, 127]
standardised white cow: [1.42 1.63 2.37]

The blue gain is 1.271 and the red 0.859, so the yellow cast disappears. But look at the white cow: before balancing (228, 214, 168) is yellowish, and after it is (196, 204, 214), now bluish instead. The gray-world assumption is wrong for a dry pasture: the scene really is yellow-brown, not grey. Better options are to lock the camera’s white balance for the whole flight or photograph a grey reference card at take-off, then use colour augmentation (next section) so the model tolerates colour changes. The white cow’s standardised values are 1.42 to 2.37 standard deviations above the training mean, which makes sense because white cattle are brighter than the grass that fills most of the image.

Six horizontal bars for the white-cow pixel: R before 228 and after 196 in pink, G before 214 and after 204 in green, B before 168 and after 214 in blue
Figure 3 White-cow pixel before and after gray-world balancing

Label-preserving augmentation

Data augmentation creates new training images from existing ones by transformations such as flips, rotations, crops, colour changes or added noise, to reduce memorisation when data are scarce (Shorten and Khoshgoftaar, 2019). A good transformation must preserve the meaning of the label: a rotated cat is still a cat, but a rotated 6 may become a 9. Drone images taken straight down have no up or down, so flips and 90-degree rotations are safe, provided the box coordinates are transformed correctly.

For a tile of width and height and a box :

  • Horizontal flip:
  • Rotate 90 degrees clockwise:

Example 3 Does the box still fit the cow after rotation?

A cow’s box in a 640 × 640 tile is (100, 200, 180, 232). The team transforms the coordinates by formula, then checks against a mask image actually rotated with OpenCV.

import numpy as np, cv2
# a cow's box in a 640 x 640 tile (x1, y1, x2, y2), checked against a really flipped or rotated mask
W = H = 640
box = (100, 200, 180, 232)

def flip_h(b):  return (W - b[2], b[1], W - b[0], b[3])
def rot90_cw(b): return (H - b[3], b[0], H - b[1], b[2])

mask = np.zeros((H, W), np.uint8)
mask[box[1]:box[3], box[0]:box[2]] = 255
def bbox(m):
    x, y, w, h = cv2.boundingRect(m)
    return (x, y, x + w, y + h)

print("original      ", box)
print("flip by rule  ", flip_h(box), " check", bbox(cv2.flip(mask, 1)))
print("rotate by rule", rot90_cw(box), " check", bbox(cv2.rotate(mask, cv2.ROTATE_90_CLOCKWISE)))
original       (100, 200, 180, 232)
flip by rule   (460, 200, 540, 232)  check (460, 200, 540, 232)
rotate by rule (408, 100, 440, 180)  check (408, 100, 440, 180)

The formulas match the really transformed image in both cases. After the 90-degree rotation the box changes from a horizontal 80 × 32 to a vertical 32 × 80, which is right because the cow now faces the other way. This check (make a mask from the box, transform the image, recover the new box) should be an automated test for every augmentation function, because a box shifted slightly does not crash the program; it silently teaches the model the wrong thing.

Annotating images: shapes, formats and agreement

Annotation turns the labelling policy above into training and test data. Choose the label shape from the question: a box for finding and counting, a polygon or mask when area or outline matters (pasture cover in module 4), a point when only the position matters, and an image-level tag when the whole image gets one class. A tool such as CVAT supports rectangles, polygons, polylines, points, masks and tags, and exports to COCO, Pascal VOC, YOLO and other formats (CVAT, n.d.). The formats are not interchangeable. The same cow can be stored as two corners, as one corner with a width and height, or as a centre with a width and height (Torchvision, n.d.), and the Ultralytics YOLO text format stores one row per object as class, x centre, y centre, width and height, each divided by the image width or height so that every value lies between 0 and 1, with classes counted from 0 (Ultralytics, n.d.). Mixing up two of these still runs and silently moves every box.

Quality needs measuring too. Two annotators label the same sample, and the team computes the IoU of paired boxes (module 3) and, for class labels, Cohen’s kappa , the agreement beyond what chance alone would give (scikit-learn, n.d.).

Example 4 Do two annotators agree?

Annotators A and B boxed the same cow in the 640 × 640 tile of Example 3 and labelled 12 animals as cow, calf or unsure (assumed). The team converts A’s box to a YOLO row, checks that it converts back to pixels, and measures both kinds of agreement.

w = h = 640
a = (100, 200, 180, 232)                 # annotator A: x1, y1, x2, y2 in pixels
b = (104, 198, 186, 234)                 # annotator B, same cow

def iou(p, q):
    ix = max(0, min(p[2], q[2]) - max(p[0], q[0]))
    iy = max(0, min(p[3], q[3]) - max(p[1], q[1]))
    inter = ix * iy
    area = lambda r: (r[2] - r[0]) * (r[3] - r[1])
    return inter / (area(p) + area(q) - inter)

def to_yolo(box):                        # centre x, centre y, width, height, divided by the tile size
    x1, y1, x2, y2 = box
    return ((x1 + x2) / 2 / w, (y1 + y2) / 2 / h, (x2 - x1) / w, (y2 - y1) / h)

def from_yolo(v):
    xc, yc, bw, bh = v[0] * w, v[1] * h, v[2] * w, v[3] * h
    return (xc - bw / 2, yc - bh / 2, xc + bw / 2, yc + bh / 2)

row = to_yolo(a)
print(f"IoU between annotators {iou(a, b):.3f}")
print("YOLO row: 0 " + " ".join(f"{x:.6f}" for x in row))
print("round trip ok:", all(abs(p - q) < 1e-9 for p, q in zip(from_yolo(row), a)))

# class labels of the same 12 animals from two annotators
la = ["cow"] * 7 + ["calf"] * 3 + ["unsure"] * 2
lb = ["cow"] * 6 + ["calf", "calf", "calf", "cow", "unsure", "cow"]
n = len(la)
po = sum(x == y for x, y in zip(la, lb)) / n
pe = sum(la.count(c) / n * lb.count(c) / n for c in set(la) | set(lb))
print(f"agreement {po:.2f}, expected by chance {pe:.2f}, kappa {(po - pe) / (1 - pe):.2f}")
IoU between annotators 0.790
YOLO row: 0 0.218750 0.337500 0.125000 0.050000
round trip ok: True
agreement 0.75, expected by chance 0.47, kappa 0.53

Two careful people boxed the same cow with an IoU of only 0.79, so scoring a detector at an IoU of 0.9 would ask for more than humans give each other; choose the evaluation threshold with this in mind. The YOLO row for A’s box converts back exactly. Class agreement looks fine at 75%, but kappa is only 0.53, because “cow” is so common that chance alone explains 47%. The disagreements are calf against cow and the “unsure” class, so the labelling policy needs a measurable rule (for example, a calf is shorter than half an adult in the image) before more images are labelled.

Module lab

Lab: preparing a drone image dataset for training

  1. Using the sample images provided by the department (drone images of animals or objects you have the right to use), write a one-page data scope and labelling policy
  2. Label 30 images in CVAT, two people working separately, then compare agreement
  3. Split the data by date or paddock and write a datasheet following the headings of Gebru et al.
  4. Compute object size in pixels and the number of tiles for the camera used with the code in Example 1, then tile the images
  5. Try gray-world balancing on morning and midday images with the code in Example 2 and explain when it fails
  6. Write flip and rotate functions that transform boxes, and test them with the method in Example 3

Common mistakes

Watch out

  • Shrinking the whole image to the model’s input size until small objects are a few pixels
  • Using a tile overlap shorter than the object, so objects cut at an edge are never whole in any tile
  • Splitting data randomly by image, putting near-identical images in different sets and inflating scores
  • Computing the mean and standard deviation from all data, including the test set
  • Using gray-world on scenes that do not average to grey, such as dry pasture
  • Rotating images but forgetting to transform boxes, or transforming the wrong axis, without a test
  • Sending images with clearly visible people to outside annotators without blurring or informing the data owner

Summary

  • An image-analysis system is a pipeline: capture, data preparation, image processing, models, post-processing, reporting, with evaluation of the whole chain
  • Image-data preparation covers data scope, labelling policy, group-wise splits, a datasheet and personal-data protection
  • An object is pixels long; use tiles overlapping by at least the object length instead of shrinking the whole image
  • Gray-world balancing works only when the scene averages to grey; standardisation values must come from the training set only
  • Augmentation must preserve label meaning, and box coordinates must be transformed with it and tested

Check your understanding

  1. GSD is 2 cm and a cow is 2.2 m long. How many pixels long is it in the image?
  2. An image is 4,000 pixels wide, tiles are 640 with 160 overlap. How many tiles across?
  3. Channel means are R 150, G 120, B 90. What is the gray-world gain for B?
  4. Why must standardisation means be computed from the training set only?
  5. In a 640 × 640 tile, what is box (50, 300, 130, 340) after a horizontal flip?
Answers
  1. pixels
  2. tiles
  3. Overall mean ; B gain
  4. If test data help compute it, test information leaks into training, so test results look better than they are and do not reflect new images the system will meet

Key formulas

Object size in pixels
Number of tiles across
Gray-world colour balance
Pixel standardisation

Key references

  1. Szeliski, R. (2022). Computer vision: Algorithms and applications (2nd ed.). Springer. link
  2. Gebru, T., Morgenstern, J., Vecchione, B., Vaughan, J. W., Wallach, H., Daumé III, H., & Crawford, K. (2021). Datasheets for datasets. Communications of the ACM, 64(12), 86–92. https://doi.org/10.1145/3458723 link
  3. Akyon, F. C., Altinuc, S. O., & Temizel, A. (2022). Slicing aided hyper inference and fine-tuning for small object detection. In 2022 IEEE International Conference on Image Processing (ICIP) (pp. 966–970). IEEE. https://doi.org/10.1109/ICIP46576.2022.9897990 link
  4. Shorten, C., & Khoshgoftaar, T. M. (2019). A survey on image data augmentation for deep learning. Journal of Big Data, 6, 60. https://doi.org/10.1186/s40537-019-0197-0 link
  5. Barbedo, J. G. A., Koenigkan, L. V., Santos, T. T., & Santos, P. M. (2019). A study on the detection of cattle in UAV images using deep learning. Sensors, 19(24), 5436. https://doi.org/10.3390/s19245436 link
  6. พระราชบัญญัติคุ้มครองข้อมูลส่วนบุคคล พ.ศ. 2562. ราชกิจจานุเบกษา, 136(69 ก), 52–95. link
  7. OpenCV. OpenCV documentation. link
  8. CVAT.ai. (n.d.). CVAT documentation. link
  9. PyTorch. (n.d.). torchvision.tv_tensors.BoundingBoxFormat. torchvision documentation. link
  10. Ultralytics. (n.d.). Object detection datasets overview (YOLO label format). Ultralytics documentation. link
  11. scikit-learn developers. (n.d.). sklearn.metrics.cohen_kappa_score. scikit-learn documentation. 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: Artificial intelligence and computer vision