How to Resize Image Using OpenCV in Computer Vision
To resize an image in OpenCV, use the
cv2.resize() function by passing the image and the desired size as a tuple. You can specify the new width and height directly or use scaling factors to resize proportionally.Syntax
The basic syntax of the cv2.resize() function is:
cv2.resize(src, dsize, fx=0, fy=0, interpolation=cv2.INTER_LINEAR)
Where:
srcis the input image.dsizeis the desired size as (width, height). If set to (0, 0), size is calculated fromfxandfy.fxandfyare scale factors along the x and y axes.interpolationdefines the method to resize (e.g.,cv2.INTER_LINEARfor smooth resizing).
python
resized_image = cv2.resize(src, dsize, fx=0, fy=0, interpolation=cv2.INTER_LINEAR)
Example
This example loads an image, resizes it to 300x200 pixels, and shows both original and resized images.
python
import cv2 # Load image from file image = cv2.imread('input.jpg') # Resize image to width=300, height=200 resized = cv2.resize(image, (300, 200), interpolation=cv2.INTER_LINEAR) # Show original and resized images cv2.imshow('Original Image', image) cv2.imshow('Resized Image', resized) cv2.waitKey(0) cv2.destroyAllWindows()
Output
Two windows open: one showing the original image, the other showing the resized image at 300x200 pixels.
Common Pitfalls
Common mistakes when resizing images with OpenCV include:
- Setting
dsizeto(0, 0)without specifyingfxandfy, which results in no resizing. - Confusing width and height order in
dsize(it must be(width, height)). - Using nearest neighbor interpolation (
cv2.INTER_NEAREST) for photos, which can cause pixelated results. - Not handling aspect ratio, which can distort the image if width and height are changed independently.
Correct way to resize proportionally:
python
# Resize image proportionally by scale factor 0.5 resized_proportional = cv2.resize(image, (0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_LINEAR)
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| src | Input image to resize | image = cv2.imread('img.jpg') |
| dsize | New size as (width, height); use (0,0) to scale by fx, fy | (300, 200) or (0, 0) |
| fx | Scale factor along width if dsize=(0,0) | 0.5 |
| fy | Scale factor along height if dsize=(0,0) | 0.5 |
| interpolation | Method to resize; e.g. INTER_LINEAR for smooth | cv2.INTER_LINEAR |
Key Takeaways
Use cv2.resize() with dsize=(width, height) to set exact new size.
Set dsize=(0,0) and use fx, fy to scale proportionally.
Choose interpolation method wisely for quality (INTER_LINEAR is good default).
Remember dsize order is (width, height), not (height, width).
Maintain aspect ratio to avoid image distortion.