Sub topic 6
Choosing an interpolation method
This chapter assumes you can load an image with cv2.imread, read its shape, and call cv2.resize with a (width, height) size or with fx and fy scale factors. NumPy indexing and the idea of a pixel grid are also assumed.
What interpolation does
When you resize an image, the output grid has different pixel positions than the input grid. For each output pixel, OpenCV maps its position back into the source image. That position usually falls between source pixels, so OpenCV has to compute a value from the surrounding pixels. The rule it uses is the interpolation method.
You choose the rule with the interpolation argument of cv2.resize. If you leave it out, OpenCV uses cv2.INTER_LINEAR. That default is acceptable for mild changes in size. It is a poor fit for large reductions, and it gives softer results than cubic when you enlarge.
The main methods
| Flag | Neighborhood used | Behavior | Typical use |
|---|---|---|---|
| `cv2.INTER_NEAREST` | 1 pixel | Copies the closest source pixel. Fast, blocky, no new values. | Label maps, masks, pixel-art |
| `cv2.INTER_LINEAR` | 2x2 | Weighted average of 4 pixels. Smooth and fast. | General default, video frames, mild scaling |
| `cv2.INTER_CUBIC` | 4x4 | Bicubic fit over 16 pixels. Sharper than linear and slower. | Enlarging photos |
| `cv2.INTER_AREA` | Whole source area under each output pixel | Averages all covered pixels. | Shrinking |
| `cv2.INTER_LANCZOS4` | 8x8 | Windowed sinc filter. Sharpest and slowest. | High-quality enlargement |
Two details matter in practice.
- Linear and cubic only look at a small fixed neighborhood. If you shrink an image by a factor of 8 with
INTER_LINEAR, each output pixel is computed from only 4 of the 64 source pixels it covers. The other 60 are ignored. Fine detail such as stripes, fabric, or text can then produce false patterns. This effect is called aliasing. It shows up as moiré patterns or jagged lines. INTER_AREAfixes this when shrinking. It averages every source pixel that falls under an output pixel, so no source pixel is skipped. When you enlarge withINTER_AREA, it behaves much likeINTER_NEAREST, so it is the wrong choice for upscaling.
Seeing aliasing directly
The script below needs no image file. It builds a source image of alternating white and black columns, so its mean brightness is 127.5. It then shrinks the image by a factor of 8 with three methods and prints the mean of each result. A resize that preserves the overall brightness should give a value near 127.5.
import cv2
import numpy as np
# 256x256 grayscale image: even columns white (255), odd columns black (0)
src = np.zeros((256, 256), dtype=np.uint8)
src[:, ::2] = 255
print("source mean:", src.mean())
methods = {
"NEAREST": cv2.INTER_NEAREST,
"LINEAR": cv2.INTER_LINEAR,
"AREA": cv2.INTER_AREA,
}
for name, flag in methods.items():
small = cv2.resize(src, (32, 32), interpolation=flag)
print(f"{name:8s} mean={small.mean():7.2f} min={small.min()} max={small.max()}")INTER_NEAREST samples source column 8 * i for output column i. Every sampled column is even, so the result is entirely white and its mean is far from 127.5. INTER_LINEAR samples between a white and a black column, so its mean lands near 127. INTER_AREA averages all 8 columns under each pixel and also lands near 127. The nearest result is the extreme case, because it depends entirely on how the stripe period lines up with the sampling step. Real photographs show the same failure as shimmering or jagged edges that change with the exact output size.
Choosing by direction of resize
Decide on the direction first, and then on the cost you can accept.
Shrinking
Use INTER_AREA as the default. It is the right tool for thumbnails, for reducing images before feeding them to a model, and for downsampling a video frame for display. If you shrink by a very small factor, for example 1000 pixels to 900, the difference between area and linear is small. If speed is the constraint, measure both on your own images.
Enlarging
Use INTER_CUBIC for a good balance, or INTER_LANCZOS4 when you want the sharpest result and can afford the time. Use INTER_LINEAR when you need speed, such as in a real-time loop. Enlarging cannot recover detail that the source did not contain. Better interpolation gives smoother edges, but the image will not become sharper than its source resolution.
Label maps and masks
A segmentation mask often stores class numbers: 0 for background, 1 for road, 2 for car. Averaging 1 and 2 produces 1.5, which rounds to a class that might not mean anything. For this kind of data, always use INTER_NEAREST, because it copies existing values and never creates new ones. This applies equally to an image of object IDs, a depth map with invalid-pixel markers, or any array where values are categories.
Side effects of the sharper methods
INTER_CUBIC and INTER_LANCZOS4 can overshoot. Near a sharp edge, the interpolated value can go slightly above the brighter side or below the darker side. This shows up as a thin halo around high-contrast edges. For uint8 images, OpenCV clips the result to the 0 to 255 range, so you see halos but no wraparound. For float images, the overshoot is kept, and values can leave your expected range, for example 0.0 to 1.0. If a later step assumes that range, clip the result with np.clip after resizing.
A helper that applies the rules
This function chooses a flag from the source and target sizes and from the kind of data. Both sizes are in (width, height) order, matching what cv2.resize expects.
import cv2
import numpy as np
def pick_interpolation(src_wh, dst_wh, label_map=False):
"""Return an interpolation flag for resizing from src_wh to dst_wh."""
if label_map:
return cv2.INTER_NEAREST
sw, sh = src_wh
dw, dh = dst_wh
if dw <= sw and dh <= sh:
return cv2.INTER_AREA
if dw >= sw and dh >= sh:
return cv2.INTER_CUBIC
return cv2.INTER_LINEAR # one axis shrinks while the other grows
def resize_smart(image, dst_wh, label_map=False):
h, w = image.shape[:2]
flag = pick_interpolation((w, h), dst_wh, label_map)
return cv2.resize(image, dst_wh, interpolation=flag)
# Demonstration on synthetic data
photo = np.random.randint(0, 256, (480, 640, 3), dtype=np.uint8)
mask = np.zeros((480, 640), dtype=np.uint8)
mask[100:300, 200:400] = 2
small_photo = resize_smart(photo, (320, 240))
small_mask = resize_smart(mask, (320, 240), label_map=True)
print(small_photo.shape, small_photo.dtype)
print(small_mask.shape, np.unique(small_mask))The printed unique values of the mask are [0 2]. No interpolated value such as 1 appears, because nearest-neighbor copies existing values.
Measuring cost
The methods differ in speed, and the gap grows with image size. Time them on your own hardware with a loop like this.
import time
import cv2
import numpy as np
img = np.random.randint(0, 256, (1080, 1920, 3), dtype=np.uint8)
flags = {
"NEAREST": cv2.INTER_NEAREST,
"LINEAR": cv2.INTER_LINEAR,
"CUBIC": cv2.INTER_CUBIC,
"AREA": cv2.INTER_AREA,
"LANCZOS4": cv2.INTER_LANCZOS4,
}
for name, flag in flags.items():
start = time.perf_counter()
for _ in range(20):
cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=flag)
ms = (time.perf_counter() - start) / 20 * 1000
print(f"{name:9s} {ms:6.2f} ms per resize")Nearest and linear are usually the fastest, and Lanczos is usually the slowest, but exact ratios depend on your CPU, your OpenCV build, and the image size. Do not tune on guesses. For a pipeline that resizes thousands of frames, a few milliseconds per frame is the difference to check.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Shrunken image shimmers or shows moiré patterns | `INTER_LINEAR` or `INTER_NEAREST` used for a large reduction | Use `INTER_AREA` |
| Enlarged image looks blocky | `INTER_NEAREST`, or `INTER_AREA` used for enlarging | Use `INTER_CUBIC` or `INTER_LINEAR` |
| Segmentation mask has unexpected class values after resize | Smooth interpolation averaged neighboring labels | Use `INTER_NEAREST` for masks |
| Bright or dark halos along edges after enlarging | Cubic or Lanczos overshoot | Use `INTER_LINEAR`, or clip float output |
| Float image has values outside the expected range | Overshoot is not clipped for float types | Apply `np.clip` after resizing |
Summary of the decision
- If the array holds categories or mask values, use
INTER_NEAREST. - If the image shrinks, use
INTER_AREA. - If the image grows and quality matters, use
INTER_CUBIC, orINTER_LANCZOS4for the sharpest result. - If the image grows and speed matters, use
INTER_LINEAR. - Resize once, to the final size, and clip float output if later steps need a fixed range.
Exercise
You have a 1200x800 photo and a matching 1200x800 segmentation mask whose pixels hold class IDs 0 to 4. You must produce a 300x200 version of each for a training pipeline. Which interpolation flag do you pass to cv2.resize for the photo, which for the mask, and why? What is the dsize argument you pass?
Show answer
Use cv2.INTER_AREA for the photo, because it is a 4x reduction and area averaging avoids aliasing. Use cv2.INTER_NEAREST for the mask, because it copies existing class IDs and never creates in-between values such as 2.5 or 3. The dsize argument is (300, 200) for both, because cv2.resize takes (width, height).
Exercise
A colleague enlarges a small float32 image with values in 0.0 to 1.0 using cv2.INTER_CUBIC, then passes the result to a function that raises an error for values above 1.0. Why can this happen, and what is the simplest fix?
Show answer
Bicubic interpolation can overshoot near sharp edges, and for float images OpenCV does not clip the result to the original range. Some output values can therefore go slightly below 0.0 or above 1.0. Clip the result with np.clip(result, 0.0, 1.0), or use cv2.INTER_LINEAR, which does not overshoot.