Letterbox or stretch? Resizing inputs for detection models
Why the same weights lose four points of mAP when the resize step changes, and how to check which one you have.
A detector that was trained on letterboxed images and then fed stretched ones still produces boxes. They are just slightly wrong, everywhere, and that is what makes the bug so durable: nothing crashes.
Letterboxing keeps the aspect ratio and pads the short side. Stretching resamples each axis independently. For a 1920×1080 frame going to 640×640 the difference is a vertical scale factor of 1.78, which turns pedestrians into something the network has rarely seen.
def letterbox(img, size=640, pad=114):
h, w = img.shape[:2]
r = min(size / h, size / w)
nh, nw = round(h * r), round(w * r)
out = np.full((size, size, 3), pad, np.uint8)
top, left = (size - nh) // 2, (size - nw) // 2
out[top:top + nh, left:left + nw] = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_LINEAR)
return out, r, (left, top)The return values matter as much as the image. Every box coming out of the model has to be shifted by the padding and divided by the ratio, in that order. Getting the order wrong gives boxes that are right in the centre of the frame and drift towards the edges.
A quick test that needs no ground truth: run the pipeline on an image and on its horizontally flipped copy. After flipping the predictions back, the two sets of boxes should overlap almost perfectly. If they do not, preprocessing and postprocessing disagree somewhere.
The interpolation mode is the second place to look. Area interpolation when shrinking, linear when enlarging, and whatever the training code used above all else.