Sub topic 4
Pixel coordinates, origins and normalisation
Every box and polygon you draw ends up as numbers. If those numbers use a different origin, unit or ordering than the code that reads them, the labels are wrong and nothing warns you. This chapter covers what the numbers mean, how the common formats differ, and how to convert them safely.
This chapter assumes you can read and write Python lists and dictionaries, and that you know an image is a grid of pixels with a width and a height. The formats themselves are covered in a later chapter. Here the focus is on the coordinate conventions underneath them.
The image coordinate system
Image coordinates differ from the maths-class graph in two ways:
- The origin (0, 0) is the top-left corner of the image.
- The x axis grows to the right and the y axis grows downwards.
A point is written as (x, y), where x is the column and y is the row. Arrays reverse this order. NumPy, OpenCV and PIL's np.array(img) all index an image as [row, column], which is [y, x]. The shape is (height, width) or (height, width, channels).
import numpy as np
img = np.zeros((480, 640, 3), dtype=np.uint8) # height 480, width 640
height, width = img.shape[:2]
x, y = 50, 40
img[y, x] = (255, 0, 0) # row first, then column
print(width, height)PIL's Image.size returns (width, height), the opposite order from array.shape. Mixing these two is the most common source of boxes that are right on square images and wrong on everything else.
Pixel edges and pixel centres
There are two ways to read a coordinate such as x = 50:
- Continuous (edge) convention. Coordinates are positions on the grid lines between pixels. Pixel number 0 covers x from 0 to 1. A box from x = 0 to x = 640 covers an image of width 640 exactly, so
x_maxmay equal the width. - Discrete (index) convention. Coordinates are pixel indices. The last valid column is
width - 1.
COCO and YOLO follow the continuous convention, with floating-point values allowed. The original Pascal VOC format used 1-based, inclusive pixel indices, so the top-left pixel was (1, 1) and a box's width was xmax - xmin + 1. Many modern tools write VOC files with 0-based coordinates anyway, so check what your tool actually writes. A one-pixel shift rarely matters for a large car. For a 6-pixel-wide object it is a large change in IoU.
Because a box is a rectangle on the grid lines, a box with x = 600 and w = 40 on a 640-pixel-wide image ends exactly at the edge. That box is valid. A box that ends at 641 is not.
Normalisation
Normalisation divides pixel values by the image size, so each coordinate becomes a fraction between 0 and 1:
- x values (and widths) are divided by the image width.
- y values (and heights) are divided by the image height.
Normalised coordinates describe the same place on any resized copy of the image. A box centred at x = 0.5 is centred horizontally whether the image is 320 or 4000 pixels wide. The cost is that you must keep the image size to recover pixels, and that x and y are scaled by different numbers on non-square images. A normalised box with equal width and height values is not a square in pixels unless the image is square.
The three common box conventions
| Format | Box fields | Units | Origin of the box |
|---|---|---|---|
| COCO | `[x_min, y_min, width, height]` | pixels | top-left corner |
| YOLO | `x_center y_center width height` | fractions of the image | box centre |
| Pascal VOC | `xmin ymin xmax ymax` | pixels | two opposite corners |
The same object can look very different in each. A car whose top-left corner is at (50, 40), 100 pixels wide and 50 high, in a 640 × 480 image:
- COCO:
[50, 40, 100, 50] - VOC:
50 40 150 90 - YOLO:
0.15625 0.135417 0.15625 0.104167
Converting between conventions
The function below reuses the conversion from the topic's examples and adds the inverse. Converting both ways and checking that you get the original back is the quickest test of a converter.
def coco_bbox_to_yolo(bbox, img_w, img_h):
x, y, w, h = bbox
x_center = (x + w / 2) / img_w
y_center = (y + h / 2) / img_h
return x_center, y_center, w / img_w, h / img_h
def yolo_to_coco_bbox(box, img_w, img_h):
cx, cy, w, h = box
bw, bh = w * img_w, h * img_h
return [cx * img_w - bw / 2, cy * img_h - bh / 2, bw, bh]
def coco_to_voc(bbox):
x, y, w, h = bbox
return [x, y, x + w, y + h]
original = [50, 40, 100, 50]
yolo = coco_bbox_to_yolo(original, 640, 480)
back = yolo_to_coco_bbox(yolo, 640, 480)
print([round(v, 6) for v in yolo])
print([round(v, 6) for v in back])
print(coco_to_voc(original))Floating-point arithmetic means the round trip returns values like 49.99999999 rather than exactly 50. Compare with a tolerance, and round only when you write the final file.
Resizing, padding and flipping
Training pipelines almost always change the image size, and the boxes must follow. Three cases cover most situations.
Plain resize. Scale x and width by new_w / old_w, and y and height by new_h / old_h. Normalised YOLO values do not change, because the ratio stays the same.
Letterbox (resize with padding). Many detectors keep the aspect ratio by scaling until the image fits and padding the rest. The boxes need the same scale plus the padding offset. Normalised values do change here, because the padded canvas has a different size from the original image.
def letterbox_box(bbox, src_w, src_h, dst_w, dst_h):
scale = min(dst_w / src_w, dst_h / src_h)
pad_x = (dst_w - src_w * scale) / 2
pad_y = (dst_h - src_h * scale) / 2
x, y, w, h = bbox
return [x * scale + pad_x, y * scale + pad_y, w * scale, h * scale]
print(letterbox_box([50, 40, 100, 50], 640, 480, 640, 640))The output is [50.0, 120.0, 100.0, 50.0]. The scale is 1.0, and 80 pixels of padding are added above and below, so y moves from 40 to 120.
Horizontal flip. In COCO format the new x is img_w - x - w. The y values do not change. Applying img_w - x to a top-left corner is a common mistake, because after a flip the old right edge becomes the new left edge.
Orientation: the hidden source of shifted labels
Phone cameras often store pixels in the sensor's orientation and add an EXIF tag saying "rotate 90° when displaying". Viewers apply the tag. Many libraries do not. The result is that your annotation tool shows a portrait photo, while your training code loads a landscape array of the same pixels, and every box is wrong.
Pick one policy and apply it before annotation and before training. The safest is to bake the rotation into the pixels once:
from PIL import Image, ImageOps
img = Image.open("street_001.jpg")
img = ImageOps.exif_transpose(img) # applies the EXIF rotation, if any
print(img.size) # (width, height) after rotation
img.save("street_001_upright.jpg")Record width and height from the upright image, not from the original file. The width and height fields in a COCO file must match the pixels the model will actually see.
Polygons use the same coordinates
COCO stores a polygon as a flat list [x1, y1, x2, y2, ...] in pixels. Normalised YOLO segmentation lines use the same alternating order, with values divided by width and height. A flat list has no brackets around each pair, so a program that reads it as [y, x] pairs, or as [x1, x2, ..., y1, y2, ...], silently produces garbage. Reshape explicitly:
import numpy as np
flat = [50, 40, 150, 40, 150, 90, 50, 90]
points = np.array(flat, dtype=float).reshape(-1, 2) # rows of (x, y)
print(points)When you rasterise a polygon, the mask has shape (height, width), and indexing it uses [y, x]. Pillow's polygon drawing with outline=1 and fill=1 also marks the boundary pixels, so the mask area for a 100 × 50 rectangle comes out slightly more than 5000. Small differences between a stored area and a mask sum are expected and usually harmless.
Validating coordinates
Run a check on every converted file. These conditions catch most conversion errors:
- Width and height are positive.
- In pixel formats,
x >= 0,y >= 0,x + w <= img_wandy + h <= img_h. - In YOLO files, all four values are between 0 and 1, and there are five fields per line (class id plus four numbers).
- Boxes are not suspiciously tiny (for example, under 1 pixel) or the size of the whole image.
def check_yolo_line(line):
parts = line.split()
if len(parts) != 5:
return ["expected 5 fields"]
problems = []
cx, cy, w, h = map(float, parts[1:])
if not all(0 <= v <= 1 for v in (cx, cy, w, h)):
problems.append("value outside 0..1")
if w <= 0 or h <= 0:
problems.append("non-positive size")
if cx - w / 2 < 0 or cx + w / 2 > 1 or cy - h / 2 < 0 or cy + h / 2 > 1:
problems.append("box extends outside image")
return problems
print(check_yolo_line("0 0.15625 0.135417 0.15625 0.104167"))
print(check_yolo_line("0 0.98 0.5 0.1 0.2"))The first line passes and prints an empty list. The second has a box centred at x = 0.98 with width 0.1, which reaches x = 1.03, so it is flagged.
Common errors
- Swapped width and height. Boxes are fine on square images and shifted on others. Always unpack
array.shapeas(height, width). - Treating COCO
[x, y, w, h]as two corners. The box then looks far too large. - Using the YOLO centre as the top-left corner. Boxes appear shifted up and left by half their size.
- Normalising by the wrong image. If labels were drawn on the original image and the file was later resized, use the size of the image the labels were drawn on.
- Rounding too early. Converting to integer pixels and back repeatedly drifts small boxes by a pixel or more.
- Forgetting orientation. See the EXIF section above.
A callout worth remembering when you review a dataset:
Exercise
An image is 800 pixels wide and 600 pixels high. A YOLO line reads 2 0.5 0.25 0.2 0.1. What are the box's COCO [x_min, y_min, width, height] values in pixels, and what are its VOC corners?
Show answer
Width is 0.2 × 800 = 160 and height is 0.1 × 600 = 60. The centre is at x = 0.5 × 800 = 400 and y = 0.25 × 600 = 150. COCO xmin = 400 − 80 = 320 and ymin = 150 − 30 = 120, so the box is [320, 120, 160, 60]. VOC corners are (320, 120) and (480, 180), written as 320 120 480 180. The class id 2 is unchanged by the conversion.
Exercise
A 640 × 480 image is flipped horizontally. A COCO box is [50, 40, 100, 50]. What is the box after the flip, and which values change?
Show answer
The new x is img_w − x − w = 640 − 50 − 100 = 490, so the box is [490, 40, 100, 50]. Only x changes. The y value, width and height stay the same, because a horizontal flip does not move anything vertically or change the box's size.