杰瑞科技汇

Python OpenCV resize怎么用?

Of course! Here is a comprehensive guide on how to resize images using Python and OpenCV, covering the basics, different interpolation methods, and practical examples.

Python OpenCV resize怎么用?-图1
(图片来源网络,侵删)

The Core Function: cv2.resize()

The main function you'll use is cv2.resize(). Its syntax is:

import cv2
# dst = cv2.resize(src, dsize, fx, fy, interpolation)

Parameters:

  • src: The source image (the image you want to resize).
  • dsize: The desired size of the output image as a tuple (width, height). This is the most common way to specify the size.
  • fx (optional): The scale factor along the horizontal axis (width). If you use dsize, this is usually set to 0.
  • fy (optional): The scale factor along the vertical axis (height). If you use dsize, this is usually set to 0.
  • interpolation (optional): The interpolation method to use. This is crucial for quality, especially when enlarging or shrinking images.

Interpolation Methods

Choosing the right interpolation method is key to getting a good result. Here are the most common ones:

Method Constant When to Use
cv2.INTER_NEAREST 0 Fastest, but produces blocky, pixelated results. Good for real-time performance or when pixel-perfect accuracy is needed (e.g., in pixel art).
cv2.INTER_LINEAR 1 Default. A good all-around choice. It's a good balance between speed and quality for both enlarging and shrinking.
cv2.INTER_CUBIC 2 Slower than INTER_LINEAR, but produces higher-quality results when enlarging an image. It uses a 4x4 neighborhood of pixels.
cv2.INTER_LANCZOS4 4 The highest quality method. It's the slowest but produces the best results, especially for enlargement. It uses an 8x8 neighborhood.
cv2.INTER_AREA 3 The best method for shrinking (downsampling) an image. It avoids the "aliasing" artifacts that can occur with other methods when reducing size.

Rule of Thumb:

Python OpenCV resize怎么用?-图2
(图片来源网络,侵删)
  • Enlarging an image? Use cv2.INTER_CUBIC or cv2.INTER_LANCZOS4 for better quality.
  • Shrinking an image? Use cv2.INTER_AREA for the best result.
  • Need a good balance? Use the default cv2.INTER_LINEAR.

Practical Examples

Let's start by loading an image. Make sure you have an image file (e.g., input.jpg) in the same directory as your script.

import cv2
import numpy as np
# Load an image
# OpenCV loads images in BGR format by default
image = cv2.imread('input.jpg')
if image is None:
    print("Error: Could not read the image.")
else:
    # Get the original dimensions
    h, w = image.shape[:2]
    print(f"Original image size: Width={w}, Height={h}")

Example 1: Resizing to a Specific Size (Absolute)

This is the most common use case. You want the image to be exactly 300x400 pixels.

# Resize to a specific size (300 pixels wide, 400 pixels high)
# Note: (width, height)
resized_abs = cv2.resize(image, (300, 400), interpolation=cv2.INTER_LINEAR)
# Display the images
cv2.imshow('Original Image', image)
cv2.imshow('Resized to Absolute Size (300x400)', resized_abs)
cv2.waitKey(0)  # Wait for a key press
cv2.destroyAllWindows()

Example 2: Resizing by a Scale Factor (Relative)

Instead of pixels, you can specify how much to scale the image.

# Scale the image to 50% of its original size
# fx = 0.5 (scale factor for width)
# fy = 0.5 (scale factor for height)
# dsize is (0,0) because we are using fx and fy
resized_half = cv2.resize(image, (0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
# Scale the image to 150% of its original size
resized_150 = cv2.resize(image, (0, 0), fx=1.5, fy=1.5, interpolation=cv2.INTER_CUBIC)
cv2.imshow('Original Image', image)
cv2.imshow('Resized to 50% (Scale Factor)', resized_half)
cv2.imshow('Resized to 150% (Scale Factor)', resized_150)
cv2.waitKey(0)
cv2.destroyAllWindows()

Example 3: Resizing While Maintaining Aspect Ratio

This is a very common task, for example, when creating thumbnails. You want to set a maximum width or height and scale the other dimension proportionally.

Python OpenCV resize怎么用?-图3
(图片来源网络,侵删)

Logic:

  1. Decide on the target dimension (e.g., max width of 300).
  2. Calculate the scaling factor: scale = target_width / original_width.
  3. Calculate the new height: new_height = int(original_height * scale).
  4. Use cv2.resize() with the new dimensions.
def resize_with_aspect_ratio(image, width=None, height=None, inter=cv2.INTER_AREA):
    # Grab the image size and initialize dimensions
    dim = None
    (h, w) = image.shape[:2]
    # If both the width and height are None, return the original image
    if width is None and height is None:
        return image
    # Check if the width is None
    if width is None:
        # Calculate the ratio of the height and construct the
        # dimensions
        r = height / float(h)
        dim = (int(w * r), height)
    # Otherwise, the height is None
    else:
        # Calculate the ratio of the width and construct the
        # dimensions
        r = width / float(w)
        dim = (width, int(h * r))
    # Resize the image
    resized = cv2.resize(image, dim, interpolation=inter)
    # Return the resized image
    return resized
# --- Usage ---
# Let's say we want a max width of 300 pixels
max_width = 300
resized_ar = resize_with_aspect_ratio(image, width=max_width, inter=cv2.INTER_AREA)
# Let's say we want a max height of 300 pixels
max_height = 300
resized_ar_h = resize_with_aspect_ratio(image, height=max_height, inter=cv2.INTER_AREA)
cv2.imshow('Original Image', image)
cv2.imshow(f'Resized (Max Width {max_width})', resized_ar)
cv2.imshow(f'Resized (Max Height {max_height})', resized_ar_h)
cv2.waitKey(0)
cv2.destroyAllWindows()

Complete, Runnable Script

Here is a full script you can save as resize_script.py and run. It includes all the examples above.

import cv2
import numpy as np
def resize_with_aspect_ratio(image, width=None, height=None, inter=cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]
    if width is None and height is None:
        return image
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    else:
        r = width / float(w)
        dim = (width, int(h * r))
    resized = cv2.resize(image, dim, interpolation=inter)
    return resized
# --- Main Execution ---
if __name__ == "__main__":
    # Load an image
    image_path = 'input.jpg' # <-- CHANGE THIS TO YOUR IMAGE PATH
    image = cv2.imread(image_path)
    if image is None:
        print(f"Error: Could not read the image at '{image_path}'.")
        print("Please make sure the image file exists in the same directory.")
    else:
        # Get the original dimensions
        h, w = image.shape[:2]
        print(f"Original image size: Width={w}, Height={h}\n")
        # 1. Resizing to a specific size
        print("Resizing to a specific size (300x400)...")
        resized_abs = cv2.resize(image, (300, 400), interpolation=cv2.INTER_LINEAR)
        cv2.imshow('Resized to Absolute Size (300x400)', resized_abs)
        # 2. Resizing by a scale factor
        print("Resizing to 50% using scale factor...")
        resized_half = cv2.resize(image, (0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
        cv2.imshow('Resized to 50% (Scale Factor)', resized_half)
        # 3. Resizing while maintaining aspect ratio
        print("Resizing while maintaining aspect ratio (max width=300)...")
        resized_ar = resize_with_aspect_ratio(image, width=300, inter=cv2.INTER_AREA)
        cv2.imshow('Resized with Aspect Ratio (Max Width 300)', resized_ar)
        # 4. Show the original for comparison
        cv2.imshow('Original Image', image)
        # Wait for a key press and close all windows
        print("\nDisplaying images. Press any key to exit.")
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        print("Done.")

Saving the Resized Image

After resizing, you can easily save the result using cv2.imwrite().

# ... after resizing an image, for example:
resized_image = cv2.resize(image, (800, 600))
# Save the resized image
output_path = 'resized_output.jpg'
success = cv2.imwrite(output_path, resized_image)
if success:
    print(f"Image successfully saved to {output_path}")
else:
    print("Error: Failed to save the image.")

This covers all the essential aspects of resizing images with Python and OpenCV. Happy coding

分享:
扫描分享到社交APP
上一篇
下一篇