Python案例如何调整图片尺寸?

wen python案例 48

本文目录导读:

Python案例如何调整图片尺寸?

  1. 方法一:使用PIL/Pillow库(最常用)
  2. 方法二:使用OpenCV
  3. 方法三:批量处理多张图片
  4. 方法四:使用scikit-image
  5. 完整的实用示例
  6. 注意事项

我来介绍几种在Python中调整图片尺寸的常用方法:

使用PIL/Pillow库(最常用)

from PIL import Image
# 打开图片
img = Image.open('input.jpg')
# 方法1:指定宽高
resized_img = img.resize((800, 600))  # (宽度, 高度)
resized_img.save('output1.jpg')
# 方法2:按比例缩放
width, height = img.size
new_width = 400
new_height = int(height * new_width / width)  # 保持宽高比
resized_img = img.resize((new_width, new_height))
resized_img.save('output2.jpg')
# 方法3:使用thumbnail(保持比例,不会放大)
img.thumbnail((400, 400))  # 限制最大尺寸
img.save('output3.jpg')

使用OpenCV

import cv2
# 读取图片
img = cv2.imread('input.jpg')
# 方法1:指定尺寸
resized = cv2.resize(img, (800, 600))
cv2.imwrite('output1.jpg', resized)
# 方法2:按比例缩放
scale_percent = 50  # 缩放50%
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
resized = cv2.resize(img, (width, height))
cv2.imwrite('output2.jpg', resized)
# 方法3:使用不同插值方法
resized = cv2.resize(img, (800, 600), interpolation=cv2.INTER_LANCZOS4)
cv2.imwrite('output3.jpg', resized)

批量处理多张图片

from PIL import Image
import os
from pathlib import Path
def batch_resize(input_folder, output_folder, target_size=(800, 600)):
    """
    批量调整图片尺寸
    """
    # 创建输出文件夹
    Path(output_folder).mkdir(parents=True, exist_ok=True)
    # 遍历输入文件夹中的所有图片
    for filename in os.listdir(input_folder):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
            # 打开图片
            img_path = os.path.join(input_folder, filename)
            img = Image.open(img_path)
            # 调整尺寸
            resized_img = img.resize(target_size, Image.Resampling.LANCZOS)
            # 保存图片
            output_path = os.path.join(output_folder, filename)
            resized_img.save(output_path)
            print(f"已处理: {filename}")
# 使用示例
batch_resize('原始图片文件夹', '调整后的图片文件夹', (800, 600))

使用scikit-image

from skimage import io, transform
import matplotlib.pyplot as plt
# 读取图片
img = io.imread('input.jpg')
# 调整尺寸
resized = transform.resize(img, (600, 800))  # (高, 宽)
# 保存图片
io.imsave('output.jpg', resized)

完整的实用示例

from PIL import Image
import os
def resize_image_with_options(
    input_path, 
    output_path, 
    target_width=None, 
    target_height=None, 
    maintain_aspect_ratio=True,
    quality=95
):
    """
    智能调整图片尺寸
    参数:
    - input_path: 输入图片路径
    - output_path: 输出图片路径
    - target_width: 目标宽度 (像素)
    - target_height: 目标高度 (像素)
    - maintain_aspect_ratio: 是否保持宽高比
    - quality: JPEG保存质量 (1-100)
    """
    # 打开图片
    img = Image.open(input_path)
    original_width, original_height = img.size
    # 计算新尺寸
    if maintain_aspect_ratio:
        if target_width and target_height:
            # 如果同时指定了宽高,取最小的缩放比例
            width_ratio = target_width / original_width
            height_ratio = target_height / original_height
            ratio = min(width_ratio, height_ratio)
            new_width = int(original_width * ratio)
            new_height = int(original_height * ratio)
        elif target_width:
            # 只指定宽度,按比例计算高度
            ratio = target_width / original_width
            new_width = target_width
            new_height = int(original_height * ratio)
        elif target_height:
            # 只指定高度,按比例计算宽度
            ratio = target_height / original_height
            new_height = target_height
            new_width = int(original_width * ratio)
        else:
            # 没有指定尺寸,返回原图
            img.save(output_path, quality=quality)
            return
    else:
        # 不保持宽高比
        new_width = target_width or original_width
        new_height = target_height or original_height
    # 调整尺寸
    resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
    # 保存图片
    resized_img.save(output_path, quality=quality)
    print(f"原始尺寸: {original_width}x{original_height}")
    print(f"调整后尺寸: {new_width}x{new_height}")
# 使用示例
resize_image_with_options(
    'input.jpg',
    'output.jpg',
    target_width=800,  # 宽度设为800像素
    maintain_aspect_ratio=True,
    quality=95
)
# 或只指定高度
resize_image_with_options(
    'input.jpg',
    'output.jpg',
    target_height=600,  # 高度设为600像素
    maintain_aspect_ratio=True
)

注意事项

  1. 安装依赖

    pip install Pillow opencv-python scikit-image
  2. 保持图片质量

    • 使用 Image.Resampling.LANCZOScv2.INTER_LANCZOS4 获得最佳质量
    • JPEG保存时设置 quality=95 以上
  3. 内存考虑

    • 处理大图片时注意内存使用
    • 可以考虑分块处理或使用内存映射
  4. 文件格式

    • 保存为JPEG时注意质量参数
    • PNG支持透明度,JPEG不支持

这些方法可以根据具体需求选择使用,Pillow是最简单和常用的选择。

抱歉,评论功能暂时关闭!