杰瑞科技汇

python resizeimage

Of course! Here is a comprehensive guide to resizing images in Python, covering the most popular and effective libraries.

python resizeimage-图1
(图片来源网络,侵删)

We'll focus on three primary methods:

  1. Pillow (PIL Fork): The most popular, all-purpose library for image manipulation. It's great for general resizing, cropping, and saving in various formats.
  2. OpenCV: The powerhouse for computer vision tasks. It's extremely fast and the go-to choice for video processing and performance-critical applications.
  3. imageio: A simple, no-frills library that's excellent for reading/writing a wide variety of image formats.

Method 1: Using Pillow (Recommended for most tasks)

Pillow is the modern, maintained fork of the Python Imaging Library (PIL). It's user-friendly and perfect for everyday image processing.

Installation

First, you need to install the library:

pip install Pillow

Basic Resizing Example

This is the simplest way to resize an image. Pillow will maintain the aspect ratio by default, so the image won't look stretched or squished.

python resizeimage-图2
(图片来源网络,侵删)
from PIL import Image
# Open an image file
try:
    with Image.open("input.jpg") as img:
        # Print original size
        print(f"Original size: {img.size}")
        # Resize the image to a specific width and height
        # The 'Image.LANCZOS' filter is a high-quality resampling filter
        resized_img = img.resize((800, 600), Image.LANCZOS)
        # Print new size
        print(f"Resized size: {resized_img.size}")
        # Save the resized image
        resized_img.save("output_pillow.jpg")
        print("Image resized and saved successfully as output_pillow.jpg")
except FileNotFoundError:
    print("Error: The input file was not found.")
except Exception as e:
    print(f"An error occurred: {e}")

Key Points:

  • img.size: Returns a tuple (width, height).
  • img.resize(): The main method for resizing.
  • (800, 600): The target dimensions as a tuple (width, height).
  • Image.LANCZOS: This is a resampling filter. It's important for quality. Other options include:
    • Image.NEAREST: Fastest, but lowest quality. Good for pixel art.
    • Image.BILINEAR: Good for a balance of speed and quality.
    • Image.BICUBIC: Better quality than bilinear, but slower.
    • Image.LANCZOS (or Image.ANTIALIAS in older versions): Highest quality, recommended for photographic images.

Method 2: Using OpenCV

OpenCV (Open Source Computer Vision Library) is designed for speed and is the standard in the computer vision field. It uses NumPy arrays to represent images, which makes it very efficient.

Installation

pip install opencv-python

Basic Resizing Example

OpenCV also maintains the aspect ratio by default when you provide only one dimension.

import cv2
import numpy as np
# Read the image using OpenCV
# Note: OpenCV reads images in BGR format by default
try:
    img = cv2.imread("input.jpg")
    if img is None:
        raise FileNotFoundError("Could not read the image. Check the file path.")
    # Print original size
    print(f"Original size: {img.shape}")
    # Resize to a specific width and height
    # cv2.INTER_AREA is recommended for shrinking
    # cv2.INTER_CUBIC or cv2.INTER_LINEAR are good for enlarging
    resized_img = cv2.resize(img, (800, 600), interpolation=cv2.INTER_AREA)
    # Print new size
    print(f"Resized size: {resized_img.shape}")
    # Save the resized image
    # OpenCV saves images in BGR format, which is standard for it
    cv2.imwrite("output_opencv.jpg", resized_img)
    print("Image resized and saved successfully as output_opencv.jpg")
except FileNotFoundError as e:
    print(f"Error: {e}")
except Exception as e:
    print(f"An error occurred: {e}")

Key Points:

python resizeimage-图3
(图片来源网络,侵删)
  • cv2.imread(): Reads an image. Returns a NumPy array.
  • img.shape: Returns a tuple (height, width, channels). This is a key difference from Pillow.
  • cv2.resize(): The main function for resizing.
  • (800, 600): The target dimensions as a tuple (width, height). This is the opposite of Pillow's (width, height) for the size attribute, but the same as the tuple you pass to resize().
  • interpolation: This is the resampling method. For best results:
    • cv2.INTER_AREA: Best for shrinking an image.
    • cv2.INTER_CUBIC: (Default, slow) Good for enlarging.
    • cv2.INTER_LINEAR: (Fast) Good for enlarging.

Method 3: Using imageio

imageio is a simple library that focuses on reading and writing a vast array of image formats. It's less for manipulation and more for I/O, but resizing is straightforward.

Installation

pip install imageio[PyQt] # Or just pip install imageio

Basic Resizing Example

imageio doesn't have a built-in resizer. You typically use it for reading/writing and pass the image data to another library like NumPy for the resizing operation.

import imageio
import numpy as np
from skimage.transform import resize # A good option for resizing with NumPy
try:
    # Read the image using imageio
    img = imageio.imread("input.jpg")
    # Print original shape
    print(f"Original shape: {img.shape}")
    # Resize the image using scikit-image's resize function
    # It's a common pattern with imageio
    # The order=1 specifies bilinear interpolation
    resized_img = resize(img, (600, 800), anti_aliasing=True)
    # The output of resize is float values between 0 and 1.
    # We need to convert it back to 8-bit integers (0-255) for saving.
    resized_img_8bit = (resized_img * 255).astype(np.uint8)
    # Print new shape
    print(f"Resized shape: {resized_img_8bit.shape}")
    # Save the resized image
    imageio.imwrite("output_imageio.jpg", resized_img_8bit)
    print("Image resized and saved successfully as output_imageio.jpg")
except FileNotFoundError:
    print("Error: The input file was not found.")
except Exception as e:
    print(f"An error occurred: {e}")

Comparison and When to Use Which

Feature Pillow (PIL Fork) OpenCV imageio
Primary Use General image manipulation, web apps, easy scripts. Computer vision, video processing, real-time apps. Simple I/O for many formats, scientific computing.
Ease of Use Very Easy. High-level, intuitive API. Moderate. Requires understanding NumPy arrays (BGR format). Easy for I/O, but often requires another lib for resizing.
Performance Good for most tasks. Slower than OpenCV. Excellent. Highly optimized, especially for video. Good, but not its main focus.
Image Format Standard RGB. BGR by default. Standard RGB.
Key Data Structure Image object. NumPy Array (H, W, C). NumPy Array.
Best For Beginners, web development, batch processing of photos. Video analysis, real-time applications, performance-critical code. Reading/writing uncommon image formats in a scientific context.

Summary

  • For most Python users and general image processing tasks, start with Pillow. It's the most straightforward and "Pythonic" way to handle images.
  • If you are doing any computer vision, video processing, or need the best possible performance, use OpenCV.
  • If you just need to read or save an image in a weird format and want a simple solution, imageio is a great choice. For resizing with it, you'll likely pair it with NumPy/scikit-image.
分享:
扫描分享到社交APP
上一篇
下一篇