Sub topic 7
Resizing without distortion
This chapter assumes you can call cv2.imread and cv2.resize, know that img.shape is (height, width, channels), and are comfortable with NumPy slicing. You have already seen that cv2.resize takes its size as (width, height). Here you will keep the aspect ratio when you change an image's size, and handle the cases where the target shape does not match the source shape.
What distortion is
The aspect ratio is width divided by height. If you resize a 400x300 image to 200x200, the horizontal scale is 0.5 and the vertical scale is about 0.67. The scales differ, so circles become ellipses and faces look narrow. To avoid this, apply one scale factor s to both axes:
- new width =
w * s - new height =
h * s
Everything below follows from this rule. The real question is what to do when the target box has a different ratio than the image. There are three options.
| Strategy | Result | Loses content? | Typical use |
|---|---|---|---|
| Fit within a box | One side matches the box, the other is smaller | No | Thumbnails, display |
| Letterbox | Fit, then pad to the exact box size | No | Model inputs that need a fixed size |
| Fill and crop | Scale to cover the box, then cut the overflow | Yes, edges | Square avatars, fixed-size tiles |
Resizing by one dimension
When you know only the width or only the height, compute the other from the ratio. This helper accepts either one and picks an interpolation method from the direction of the change.
import cv2
import numpy as np
def pick_interpolation(old_size, new_size):
"""INTER_AREA for shrinking, INTER_CUBIC for enlarging."""
return cv2.INTER_AREA if new_size < old_size else cv2.INTER_CUBIC
def resize_keep_ratio(image, width=None, height=None):
h, w = image.shape[:2]
if width is None and height is None:
return image.copy()
if width is None:
scale = height / h
width = round(w * scale)
elif height is None:
scale = width / w
height = round(h * scale)
else:
raise ValueError("Give width or height, not both")
width = max(1, width)
height = max(1, height)
interpolation = pick_interpolation(w, width)
return cv2.resize(image, (width, height), interpolation=interpolation)
image = np.zeros((300, 400, 3), dtype=np.uint8)
print(resize_keep_ratio(image, width=200).shape) # (150, 200, 3)
print(resize_keep_ratio(image, height=600).shape) # (600, 800, 3)Three details matter here.
cv2.resizeneeds integer sizes.roundis better thanint, which truncates, because truncation shifts the ratio slightly more often and in one direction.max(1, ...)prevents a zero-sized dimension. A very wide, short image resized to a tiny width can produce a height that rounds to 0, andcv2.resizethen raises an error.- The output shape is
(height, width, 3), but the size you pass in is(width, height). Mixing these up is the most common bug in this area.
Fitting inside a box
Often you have a maximum size, such as 800x600, and want the largest image that fits. Compute the scale for each axis and take the smaller one. The smaller scale guarantees neither side exceeds the box.
import cv2
import numpy as np
def fit_within(image, max_width, max_height, allow_upscale=False):
h, w = image.shape[:2]
scale = min(max_width / w, max_height / h)
if not allow_upscale:
scale = min(scale, 1.0)
new_w = max(1, round(w * scale))
new_h = max(1, round(h * scale))
if (new_w, new_h) == (w, h):
return image.copy()
interpolation = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_CUBIC
return cv2.resize(image, (new_w, new_h), interpolation=interpolation)
wide = np.zeros((300, 400, 3), dtype=np.uint8)
print(fit_within(wide, 200, 200).shape) # (150, 200, 3)
print(fit_within(wide, 800, 800).shape) # (300, 400, 3)
print(fit_within(wide, 800, 800, allow_upscale=True).shape) # (600, 800, 3)The allow_upscale=False default is deliberate. Enlarging a small image adds no information. It only creates smooth blur, and downstream code that expected "at most this big" gets a surprise if you enlarge silently. Make upscaling an explicit choice.
The helper returns a copy when no resize is needed, so the caller can always treat the result as independent of the input. Returning the same array in one branch and a new array in another is a quiet source of aliasing bugs.
Letterboxing to an exact size
Some consumers, such as neural network inputs, need exactly 640x640. Stretching would distort the picture. Instead, fit the image inside the box and pad the remaining space with a constant color. This is called letterboxing.
import cv2
import numpy as np
def letterbox(image, target_width, target_height, color=(114, 114, 114)):
h, w = image.shape[:2]
scale = min(target_width / w, target_height / h)
new_w = min(target_width, max(1, round(w * scale)))
new_h = min(target_height, max(1, round(h * scale)))
interpolation = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_CUBIC
resized = cv2.resize(image, (new_w, new_h), interpolation=interpolation)
pad_w = target_width - new_w
pad_h = target_height - new_h
left = pad_w // 2
right = pad_w - left
top = pad_h // 2
bottom = pad_h - top
padded = cv2.copyMakeBorder(
resized, top, bottom, left, right,
cv2.BORDER_CONSTANT, value=color,
)
return padded, scale, (left, top)
image = np.full((300, 400, 3), 200, dtype=np.uint8)
out, scale, (left, top) = letterbox(image, 640, 640)
print(out.shape) # (640, 640, 3)
print(scale) # 1.6
print(left, top) # 0 80The min(..., target) clamps matter. Floating-point rounding can make round(w * scale) come out one pixel larger than the target, which would make the padding negative and copyMakeBorder would fail.
The function also returns scale and the offsets (left, top). You need them if you later run a detector on the letterboxed image and want to map its boxes back to the original picture:
x_original = (x_letterboxed - left) / scaley_original = (y_letterboxed - top) / scale
If you throw these values away, you cannot recover the original coordinates reliably.
copyMakeBorder takes the color as a BGR tuple, like the drawing functions. For a grayscale image, pass a single number.
Fill and crop
When every output must be exactly the same size and padding is unwanted, scale so the image covers the box, then cut the overflow from the center.
import cv2
import numpy as np
def fill_and_crop(image, target_width, target_height):
h, w = image.shape[:2]
scale = max(target_width / w, target_height / h)
new_w = max(target_width, round(w * scale))
new_h = max(target_height, round(h * scale))
interpolation = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_CUBIC
resized = cv2.resize(image, (new_w, new_h), interpolation=interpolation)
x0 = (new_w - target_width) // 2
y0 = (new_h - target_height) // 2
return resized[y0:y0 + target_height, x0:x0 + target_width].copy()
image = np.zeros((300, 400, 3), dtype=np.uint8)
print(fill_and_crop(image, 200, 200).shape) # (200, 200, 3)This is the same as the letterbox but with max instead of min. With max, one side matches the target and the other overflows. The slice is indexed [y0:y1, x0:x1], and .copy() releases the larger resized array so the result does not keep it alive as a view.
A center crop can cut off the subject, such as a face near the edge. If you know where the subject is, shift x0 and y0 toward it instead of centering.
Interpolation and quality
The ratio fixes the geometry, but the interpolation method fixes the quality. The helpers above use a simple rule.
| Direction | Method | Reason |
|---|---|---|
| Shrinking | `cv2.INTER_AREA` | Averages the source pixels that map to each output pixel, which avoids aliasing such as jagged edges and moiré patterns |
| Enlarging | `cv2.INTER_CUBIC` | Smoother than `INTER_LINEAR`, but slower and can produce slight ringing near sharp edges |
| Fast enlarging or video | `cv2.INTER_LINEAR` | Cheaper, and the default if you pass nothing |
INTER_NEAREST copies the nearest pixel without blending. It is the right choice for label masks, where each pixel value is a class ID, because blending would invent values that are not valid classes.
For very large reductions, such as 4000 pixels down to 100, INTER_AREA does the work in one step. Chaining many small halvings is not needed.
Common mistakes
- Passing
(h, w)instead of(w, h)tocv2.resize. The image is then rotated in shape and distorted, with no error. - Using integer division on the scale, such as
scale = width // w. In Python 3 the//operator floors the result, so200 // 400is0. Use/. - Computing both new dimensions independently from two different targets, which brings back distortion.
- Forgetting to keep
scaleand padding offsets after a letterbox, so detection results cannot be mapped back. - Calling
cv2.resizeon an image that came from a failedcv2.imread. Check forNonefirst, as you did when loading.
Exercise
A 1920x1080 image (width x height) is letterboxed into a 640x640 box. What are the resized size before padding, the padding at top and bottom, and the formula to map a letterboxed x-coordinate back to the original image?
Show answer
The scale is min(640/1920, 640/1080) = 1/3, so the resized image is 640 wide and 360 high. The vertical padding is 640 - 360 = 280, which is 140 at the top and 140 at the bottom. There is no horizontal padding, so left = 0. A letterboxed x maps back with xoriginal = (xletterboxed - left) / scale = x_letterboxed * 3.
Exercise
Why does fill_and_crop use max for the scale while letterbox uses min, and what does each choice guarantee?
Show answer
With min, the smaller of the two axis scales is used, so both sides of the scaled image are at most the target size and the whole image fits, leaving padding on one axis. With max, the larger scale is used, so both sides are at least the target size and the box is fully covered, leaving overflow on one axis that must be cropped.