0
0
Computer-visionHow-ToBeginner ยท 3 min read

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:

  • src is the input image.
  • dsize is the desired size as (width, height). If set to (0, 0), size is calculated from fx and fy.
  • fx and fy are scale factors along the x and y axes.
  • interpolation defines the method to resize (e.g., cv2.INTER_LINEAR for 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 dsize to (0, 0) without specifying fx and fy, 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

ParameterDescriptionExample
srcInput image to resizeimage = cv2.imread('img.jpg')
dsizeNew size as (width, height); use (0,0) to scale by fx, fy(300, 200) or (0, 0)
fxScale factor along width if dsize=(0,0)0.5
fyScale factor along height if dsize=(0,0)0.5
interpolationMethod to resize; e.g. INTER_LINEAR for smoothcv2.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.