Sub topic 5
Resizing to a Size or by a Scale Factor
This chapter covers cv2.resize: the two ways to call it, the argument-order trap, rounding behavior, and the errors that come up most often. It assumes you can write basic Python functions, have installed opencv-python and numpy with pip, and know that an OpenCV image is a NumPy array with shape (height, width, channels) in BGR order. Interpolation methods and aspect-ratio-preserving helpers get their own chapters, so they appear here only where needed to make the examples run sensibly.
What resizing does
Resizing produces a new image with a different number of pixels. OpenCV maps each pixel position in the output back to a position in the source image. It then computes a value from the nearby source pixels. How it combines those neighbors is the interpolation method. The function never modifies the input array. It returns a new array.
The signature, simplified, is:
dst = cv2.resize(src, dsize, fx=0, fy=0, interpolation=cv2.INTER_LINEAR)You describe the output size in one of two ways:
- Give
dsizeas an explicit(width, height)tuple. - Pass
dsize=Noneand give the scale factorsfxandfy.
If you give both a non-zero dsize and scale factors, dsize wins and the factors are ignored. That can hide mistakes, so pick one style per call.
Resizing to an exact size
Pass dsize as (width, height). This is the reverse of the order in img.shape, which is (height, width, channels). Mixing them up is the most common resize bug.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
h, w = img.shape[:2]
print("source:", w, "x", h)
# dsize is (width, height), the reverse of img.shape order
small = cv2.resize(img, (w // 2, h // 2), interpolation=cv2.INTER_AREA)
print("small shape:", small.shape) # (h // 2, w // 2, 3)Note that w // 2 uses integer division. dsize must contain integers. Passing a float such as w / 2 raises an error in current OpenCV versions, because the tuple cannot be converted to integer sizes.
The argument-order trap
Suppose a 600-pixel-wide, 400-pixel-tall image. You want a 300 by 200 result.
import cv2
img = cv2.imread("photo.jpg") # assume 600 wide, 400 tall: shape (400, 600, 3)
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
right = cv2.resize(img, (300, 200)) # (width, height) -> shape (200, 300, 3)
wrong = cv2.resize(img, (200, 300)) # (width, height) -> shape (300, 200, 3)
print(right.shape)
print(wrong.shape)The second call runs without any error. It returns a tall, squeezed image. No exception warns you, so check the output shape when something looks stretched.
Resizing by a scale factor
When you want "half the size" or "twice the size", scale factors are shorter. Pass None for dsize.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
# Scale by factors instead of giving an explicit size
big = cv2.resize(img, None, fx=2.0, fy=2.0, interpolation=cv2.INTER_CUBIC)
half = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
print(img.shape, big.shape, half.shape)OpenCV computes the output size as round(width * fx) by round(height * fy). Use the same value for fx and fy to keep proportions. Different values stretch the image along one axis.
If you pass dsize=None and leave fx and fy at 0, OpenCV raises an assertion error, since it has no way to determine the output size.
Rounding and exact sizes
Because the output size is rounded, a scale factor does not always give the size you expect. A 101-pixel-wide image scaled by 0.5 becomes 50 or 51 pixels wide, depending on the rounding rule. If an exact size matters, for example when a neural network needs 224 by 224 input, use dsize. Use scale factors when the exact size matters less than the ratio.
| Situation | Preferred style |
|---|---|
| Model input needs a fixed size | `dsize=(width, height)` |
| Thumbnail with a target width | `dsize` computed from the width (see the aspect-ratio chapter) |
| "Make it half the size" | `fx=0.5, fy=0.5` |
| Same scale on both axes, size not critical | `fx` and `fy` |
| Match the size of another image | `dsize=(other.shape[1], other.shape[0])` |
Matching another image's size
To resize one image to match another, pull the width and height out of the other image's shape. Index 1 is the width and index 0 is the height, so the tuple order has to be swapped.
import cv2
a = cv2.imread("photo.jpg")
b = cv2.imread("other.jpg")
if a is None or b is None:
raise FileNotFoundError("Could not read one of the input images")
b_resized = cv2.resize(b, (a.shape[1], a.shape[0]))
assert b_resized.shape[:2] == a.shape[:2]The assert compares shape[:2] directly, where both sides use (height, width). This is a useful check after any resize.
What stays the same and what changes
- dtype. The output keeps the input dtype. A
uint8image staysuint8. - Channels. The channel count and order are unchanged. A BGR image stays BGR, and a grayscale image with shape
(h, w)stays two-dimensional. - Values. Interpolation can produce values that were not in the original. Resizing a mask with a smooth method creates in-between values at the edges. For label masks, where each value is a class id, use
cv2.INTER_NEARESTso no new values appear. - Memory. The result is a separate array. Resizing a large image to a small one frees you to discard the large one, but both exist until you delete the reference.
import cv2
import numpy as np
mask = np.zeros((100, 100), dtype=np.uint8)
mask[20:60, 20:60] = 255
smooth = cv2.resize(mask, (37, 37), interpolation=cv2.INTER_LINEAR)
exact = cv2.resize(mask, (37, 37), interpolation=cv2.INTER_NEAREST)
print(np.unique(smooth)) # likely includes values between 0 and 255
print(np.unique(exact)) # only [0 255]The nearest-neighbor result contains only the original values, which matters when the values are labels instead of brightness.
Common errors
| Symptom | Likely cause | Fix | Column | Column |
|---|---|---|---|---|
| Image looks stretched or squeezed, no error | `dsize` given as `(height, width)` | Use `(width, height)` | ||
| `error: (-215:Assertion failed) !ssize.empty()` | `src` is empty, usually because `imread` returned `None` or a crop was empty | Check for `None` and check slice bounds before resizing | ||
| `error: (-215:Assertion failed) !dsize.empty() | (inv_scale_x > 0 && inv_scale_y > 0)` | `dsize=None` with `fx` and `fy` left at 0 | Provide a size or both factors | |
| `TypeError` about `dsize` | Float values in the tuple | Use `int(...)`, `round(...)`, or `//` | ||
| Output size differs by one pixel from your estimate | Rounding of `width * fx` | Use `dsize` for exact sizes | ||
| Colors look wrong after resize | The colors were wrong before, from BGR vs RGB confusion elsewhere | Resizing does not change channel order. Check the conversion step | ||
| Edges look jagged or blurry | Interpolation does not fit the direction of the resize | See the interpolation chapter |
Resizing in a loop
A common task is resizing every image in a folder. Handle failed loads explicitly, since imread returns None for unreadable files and a later resize on None fails with a confusing message.
import cv2
from pathlib import Path
src_dir = Path("images")
dst_dir = Path("resized")
dst_dir.mkdir(exist_ok=True)
for path in sorted(src_dir.glob("*.jpg")):
img = cv2.imread(str(path))
if img is None:
print(f"skipping unreadable file: {path}")
continue
out = cv2.resize(img, (256, 256), interpolation=cv2.INTER_AREA)
cv2.imwrite(str(dst_dir / path.name), out)This forces every image to 256 by 256, which distorts images that are not square. Whether that is acceptable depends on the task. The next chapters cover choosing an interpolation method and keeping the aspect ratio.
Edge cases
- Zero or negative sizes. A
dsizewith a zero or negative entry fails with an assertion error. A tiny scale factor such asfx=0.001on a small image rounds to zero pixels and fails the same way. - Identical size. Resizing to the current size works and returns a copy of the data, which is a quick way to get an independent array.
- Very large outputs. Memory use grows with width times height times channels. A 20,000 by 20,000 BGR
uint8image needs about 1.2 GB. - Grayscale and alpha images. A two-dimensional array or a four-channel BGRA array both resize without special handling. Interpolation is applied to each channel independently, so color bleeding at transparent edges is possible with alpha.
- Other dtypes. Float32 images resize fine. Float images are not clipped to the 0 to 255 range, so cubic interpolation can overshoot slightly beyond the original range.
Exercise
An image has shape (480, 640, 3). You call cv2.resize(img, (240, 320)). What shape does the result have, and does OpenCV raise an error? What call would produce a result with half the height and half the width?
Show answer
The result has shape (320, 240, 3), because dsize is (width, height) so the new width is 240 and the new height is 320. OpenCV raises no error, and the image is distorted. To halve both dimensions, use cv2.resize(img, (320, 240)) for shape (240, 320, 3), or cv2.resize(img, None, fx=0.5, fy=0.5), which gives the same shape.
Exercise
You resize a segmentation mask whose pixel values are class ids 0, 1, and 2. After resizing with the default interpolation, you find pixels with value 1 along the border between class 0 and class 2. What went wrong, and how do you fix it?
Show answer
The default interpolation is INTERLINEAR, which averages neighboring pixels and creates in-between values such as 1 at the boundary between 0 and 2. Pass interpolation=cv2.INTERNEAREST so each output pixel copies one existing input value.