OpenCV Resize Image with Python

To resize an image in Python, set the output dimensions you want. OpenCV’s cv2.resize() changes an image’s pixel dimensions and returns the resized array.

I’ll show how to choose dimensions with cv2.resize(), then how to handle aspect ratios and input errors.

TL;DR

Use cv2.resize(image, (width, height)) for exact output dimensions, or pass None with matching fx and fy values to scale proportionally.

  • NumPy shape is height, width, channels, while resize dsize is width, height.
  • For a proportional fit, calculate both dimensions from one scale factor.
  • INTER_AREA is a sound starting point when shrinking, while INTER_LINEAR or INTER_CUBIC can suit enlargement.

What Is cv2.resize()?

cv2.resize() changes an image’s pixel dimensions and returns the resized array.

A grayscale image often loads as a two-dimensional array, while color data commonly adds a third channel axis. Use image.shape[:2] when code needs only spatial dimensions and should work with either form.

I prefer named width and height variables for dsize because the executed calls returned shape in the opposite order.

ArgumentPurposePython use
srcInput image arrayPass the image returned by cv2.imread() or another array.
dsizeOutput dimensionsUse (width, height), or None when factors determine the size.
fx and fyHorizontal and vertical scale factorsSupply both with None for dsize.
interpolationRule for sampling destination pixelsChoose a cv2 interpolation constant.

An image read as BGR stays BGR after resizing. Convert it separately if a later display function expects RGB.

How to Resize an Image with OpenCV Step by Step

A valid source array is the starting condition for each resize. The steps below check an input, select output dimensions and verify the saved file.

Step 1: Run a complete resize example

I ran .venv/bin/python resize_demo.py to check dimensions, scale routes, interpolation, saving and a missing path using a synthetic source image.

import cv2
import numpy as np

# A small synthetic BGR image makes this demo runnable without an external photo.
image = np.zeros((90, 160, 3), dtype=np.uint8)
image[:, :80] = (40, 120, 220)
image[:, 80:] = (220, 120, 40)

height, width = image.shape[:2]
resized = cv2.resize(image, (80, 45), interpolation=cv2.INTER_AREA)
scaled = cv2.resize(image, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
target_width = 80
target_height = 45
small = cv2.resize(image, (target_width, target_height), interpolation=cv2.INTER_AREA)
print(f"source_shape={image.shape}")
print(f"dsize_output_shape={resized.shape}")
print(f"scale_output_shape={scaled.shape}")
print(f"small_output_shape={small.shape}")
print(f"outputs_equal={np.array_equal(resized, scaled)}")

max_width, max_height = 640, 480
scale = min(max_width / width, max_height / height)
new_width = round(width * scale)
new_height = round(height * scale)
fitted = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_AREA)
saved = cv2.imwrite("resized.jpg", fitted)
print(f"fitted_shape={fitted.shape}")
print(f"saved={saved}")

# Compare interpolation using a one-pixel checkerboard reduced to a single pixel.
checker = np.array([[0, 255], [255, 0]], dtype=np.uint8)
area = cv2.resize(checker, (1, 1), interpolation=cv2.INTER_AREA)
nearest = cv2.resize(checker, (1, 1), interpolation=cv2.INTER_NEAREST)
print(f"checker_area={int(area[0, 0])}")
print(f"checker_nearest={int(nearest[0, 0])}")

missing = cv2.imread("missing-input.png")
print(f"missing_input_is_none={missing is None}")
[ WARN:[email protected]] global loadsave.cpp:278 findDecoder imread_('missing-input.png'): can't open/read file: check file path/integrity
source_shape=(90, 160, 3)
dsize_output_shape=(45, 80, 3)
scale_output_shape=(45, 80, 3)
small_output_shape=(45, 80, 3)
outputs_equal=True
fitted_shape=(360, 640, 3)
saved=True
checker_area=128
checker_nearest=0
missing_input_is_none=True
Terminal output showing OpenCV image resize results and interpolation values
Terminal output shows the resized dimensions, successful file write, checkerboard values and missing-file check.

The final line confirms that the missing path produced no image array. Check that condition before reading shape or resizing.

Step 2: Resize to exact dimensions

Set target_width and target_height to the desired dimensions. The example halves a 160 by 90 source array and uses area resampling for the reduction.

target_width = 80
target_height = 45
small = cv2.resize(image, (target_width, target_height), interpolation=cv2.INTER_AREA)

Check small.shape[:2] before using the array in later processing.

Step 3: Scale by a factor and compare

The full run above compares explicit dimensions with equal scale factors. Both returned matching shapes and pixel arrays.

I chose INTER_AREA for shrinking because the checkerboard probe returned 128, while nearest-neighbor returned 0.

Step 4: Preserve proportions within a bounding box

To fit within maximum dimensions, multiply both source dimensions by the smaller limit-to-source ratio.

max_width, max_height = 640, 480
scale = min(max_width / width, max_height / height)
new_width = round(width * scale)
new_height = round(height * scale)
fitted = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_AREA)

OpenCV derives scale-based dimensions from the source and rounds the results. Inspect the returned shape when a downstream model needs exact counts, and clamp a zero-sized side to one pixel before resizing.

Step 5: Save the resized result

Pass the destination filename and resized array to cv2.imwrite().

saved = cv2.imwrite("resized.jpg", fitted)
if not saved:
    raise OSError("Could not write resized.jpg")

Keep the destination directory available and choose an extension for a format supported by the OpenCV build.

cv2.resize() does not show a window. In a server script, inspect fitted.shape to verify the destination dimensions. A desktop display call is separate.

For transparency, load a mode that retains the alpha channel and check that the output array still has it. The selected file format and viewer also affect how transparency appears.

Image pixel dimensions do not determine compressed file size, so inspect the saved file and adjust encoder settings separately when the goal is a smaller download.

Generate alternate target sizes from the original array when you need several outputs. Resizing an already-resized result compounds resampling and can discard detail before the final dimensions are reached.

The source and destination arrays can occupy memory at the same time. For large images or batches, process one input at a time and release arrays that are no longer needed.

Handle Aspect Ratios, Interpolation and Input Errors

I fit the 160 by 90 source within a 640 by 480 box because the executed result kept its proportions at 640 by 360.

Fit, stretch, crop or pad?

Each row pairs a framing goal with a transformation and its trade-off.

GoalChoiceTrade-off
Keep the whole image proportionalFit within boundsOne side may be shorter than the target.
Fill every target pixelStretchShapes can distort.
Fill while keeping proportionsScale then center cropEdges are discarded.
Keep all content on a fixed canvasScale then letterboxPadding remains around the image.

For model inputs, labels and detected coordinates must use the same crop and padding offsets as the transformed image.

Record scale and offset when another step must map a processed-image point back to source coordinates.

Select interpolation for the image type

OpenCV interpolation calculates destination values from nearby source samples, so the selected method affects detail and runtime. The table gives starting choices.

SituationStarting choiceReason
Shrinking a photocv2.INTER_AREAUses pixel-area relationships during reduction.
General resize or quick enlargementcv2.INTER_LINEARDefault bilinear interpolation is a practical baseline.
Smoother enlargementcv2.INTER_CUBICUses a wider neighborhood and can cost more time.
Segmentation masks or pixel artcv2.INTER_NEARESTAvoids blending neighboring label values.

Upscaling creates samples between existing pixels, which may smooth an edge but cannot restore missing source texture.

For segmentation masks, class IDs represent categories rather than colors to blend. Nearest-neighbor resizing keeps destination values from being averaged between adjacent labels, while a photographic interpolation can create values that were never valid classes.

Catch missing files and process batches safely

The table lists four file-processing failures and a response for each one.

CaseSymptomFix
Unreadable pathcv2.imread() returns None.Check for None before reading shape or resizing.
Unexpected working directoryA relative path does not point to the intended file.Use a path based on the script or provide a known full path.
Batch output collisionDifferent inputs write to the same filename.Build a unique destination name for each input.
Incomplete scale argumentsThe output grid is not fully specified.Pass dsize or provide both fx and fy.

For separate files, resize each valid array in a loop. Measure decoding, resizing and writing together when runtime is important.

Sort input paths when a stable processing order matters. Derive each output name from its source path to prevent collisions between folders.

For image loading and saving details, see Reading, Writing and Displaying Images Using OpenCV in Python and the CodeForGeek guide to reading an image with OpenCV.

Conclusion

A resize call is predictable when its output dimensions, proportion policy and interpolation are chosen before processing. Check the returned array and saved file rather than assuming a successful-looking call preserved every detail.

OpenCV’s geometric image transformation documentation lists the resize parameters and interpolation methods. The CodeForGeek guides above cover image input and output before you connect resizing to a larger image workflow.

FAQ

These answers cover common choices that follow from the resize call.

How do I resize an image without changing its aspect ratio?

Calculate one scale factor and apply it to both width and height. Pass the resulting (width, height) tuple to cv2.resize(), or pass the same factor as fx and fy with dsize=None.

What is the correct order for cv2.resize dimensions?

The dsize tuple is (width, height). NumPy image.shape reports (height, width) for a grayscale image and usually (height, width, channels) for a color image.

Which interpolation should I use when shrinking an image?

cv2.INTER_AREA is a common starting choice for shrinking. Inspect the result for your image and task because interpolation affects pixel values and visual detail.

Can cv2.resize process a batch of images at once?

For separate image files, loop over the inputs, check each cv2.imread() result, resize each valid image and check each cv2.imwrite() result. The ordinary call resizes one image array at a time.

Snigdha Keshariya
Snigdha Keshariya

Snigdha Keshariya covers AI concepts and tools, from AI agents, RLHF, prompting, and model architectures to coding assistants and AI productivity tools.

Articles: 111