In the field of computer vision, image resizing and cropping are the most fundamental and commonly used operations. Whether you’re adjusting the image size to fit a model’s input or cropping out irrelevant regions to highlight the subject, these techniques can help you solve practical problems. This article will guide you through these two core operations in Python OpenCV in the simplest way possible, making it easy to follow even for beginners.

1. Image Resizing: Techniques to Adjust Image Dimensions

Image resizing is like “stretching” or “compressing” a photo, which can be done by scaling proportionally or directly specifying the target size. In OpenCV, the cv2.resize() function is used for this, and it’s the first tool you must master.

1.1 Detailed Explanation of cv2.resize() Parameters

The key parameters of this function include:
- Input Image: The image to be processed (e.g., img).
- Target Size: Can be specified in two ways:
- Method 1: (width, height) – directly set the target dimensions (e.g., (200, 300)).
- Method 2: (0, 0) + fx/fyfx is the horizontal scaling factor, fy is the vertical scaling factor (e.g., fx=0.5 means reducing the width to half the original).
- Interpolation Method: Controls “how new pixel values are calculated”. Common options:
- cv2.INTER_AREA: Suitable for reducing image size (produces clearer results).
- cv2.INTER_LINEAR: Suitable for enlarging images (default option, good for smoothness).

1.2 Example 1: Proportional Resizing (Most Common)

Suppose you have a 1000×600 image and need to resize it to half its original size or 1.5 times larger. The code is as follows:

import cv2

# 1. Read the image (replace "test.jpg" with your image path)
img = cv2.imread("test.jpg")  # Color image
if img is None:  # Check if the image was read successfully
    print("Invalid image path! Please ensure the file exists.")
else:
    # 2. Resize proportionally: fx=0.5 (width halved), fy=0.5 (height halved)
    scaled_img = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)

    # 3. Display original and resized images
    cv2.imshow("Original", img)   # Show original image
    cv2.imshow("Scaled", scaled_img)  # Show scaled image
    cv2.waitKey(0)  # Wait for any key press to close windows
    cv2.destroyAllWindows()  # Destroy all windows

Key Point: None means the size is not directly specified; it is automatically calculated using fx and fy.

1.3 Example 2: Specifying Target Size (Fixed Width and Height)

If you need precise control over the output size (e.g., resize the image to 200×200 pixels), directly pass the target width and height:

# Target size: width 200, height 200
target_size = (200, 200)
resized_img = cv2.resize(img, target_size, interpolation=cv2.INTER_LINEAR)

# Display the result
cv2.imshow("Target Size", resized_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Note: If the target size does not match the original aspect ratio, the image will be stretched. To maintain the aspect ratio, it is recommended to use proportional resizing.

1.4 Common Resizing Issues

  • Incorrect Image Path: Use an absolute path (e.g., "C:/Users/xxx/Desktop/test.jpg") for safety.
  • Wrong Interpolation Method: Use INTER_AREA for downscaling and INTER_LINEAR for upscaling to avoid distortion.
  • Window Flickering: Always include cv2.waitKey(0) to pause the display and cv2.destroyAllWindows() to close windows.

2. Image Cropping: Precisely Extracting Regions of Interest

Cropping is like using scissors to “cut out” a part of the image, retaining only the region of interest. In OpenCV, images are stored as NumPy arrays, so cropping is essentially an array slicing operation.

2.1 Cropping Principle: Array Slicing

An image in OpenCV is stored as a NumPy array with the format (height, width, number_of_channels) (e.g., (600, 1000, 3)). To crop a region, specify the top-left and bottom-right coordinates using the slicing format:
img[y_start:y_end, x_start:x_end]

  • y_start: Starting row of the cropping region (vertical direction).
  • y_end: Ending row of the cropping region (vertical direction).
  • x_start: Starting column of the cropping region (horizontal direction).
  • x_end: Ending column of the cropping region (horizontal direction).

2.2 Example 1: Cropping a Fixed Region

Suppose you need to crop a specific area (e.g., from the top-left corner (100, 50) to the bottom-right corner (400, 300)):

# Read the image
img = cv2.imread("test.jpg")

# Define the cropping region: y from 100 to 500, x from 50 to 400 (order: y first, then x)
cropped_img = img[100:500, 50:400]  # Slicing format: [y_start:y_end, x_start:x_end]

# Display the result
cv2.imshow("Cropped", cropped_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Key Point: Coordinate out-of-bounds will cause errors! Ensure y_end < height and x_end < width (where height = img.shape[0] and width = img.shape[1]).

2.3 Example 2: Cropping the Center Region (Centered Cropping)

To crop the center part of an image (e.g., to a fixed size of 200×200), first calculate the center coordinates:

# Read the image
img = cv2.imread("test.jpg")
h, w = img.shape[:2]  # Get original height h and width w

# Target cropping size: 200×200
target_h, target_w = 200, 200

# Calculate center offsets
x_start = (w - target_w) // 2  # Horizontal centering
y_start = (h - target_h) // 2  # Vertical centering
x_end = x_start + target_w
y_end = y_start + target_h

# Crop the center region
cropped_center = img[y_start:y_end, x_start:x_end]

# Display the result
cv2.imshow("Center Cropped", cropped_center)
cv2.waitKey(0)
cv2.destroyAllWindows()

Key Point: Use // (integer division) to avoid non-integer coordinates and ensure the cropping region is complete.

3. Summary: Core Techniques for Beginners

3.1 Image Resizing

  • Use cv2.resize(): Proportional resizing with fx/fy, fixed size with (width, height).
  • Choose INTER_AREA for downscaling and INTER_LINEAR for upscaling to avoid distortion.
  • Ensure correct image paths and window cleanup with destroyAllWindows().

3.2 Image Cropping

  • Essentially array slicing: img[y_start:y_end, x_start:x_end].
  • Coordinates start from the top-left corner; out-of-bounds coordinates will cause errors.
  • Centered cropping requires calculating center offsets to ensure the region is complete.

With these two core operations, you can handle most simple image preprocessing tasks. In practice, these techniques are often used together (e.g., crop first, then resize). Try them out! When encountering issues, check the image path, coordinate ranges, and window operations—these are common pitfalls for beginners.

Xiaoye