萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python PIL/Pillow 圖片處理實戰:縮放、旋轉、繪圖、濾鏡與增強

Pillow (PIL 友善分支) 是 Python 影像處理標準庫,支援格式轉換、幾何變換、像素操作、濾鏡、繪圖與色彩增強。本文透過完整類別封裝示範核心功能與實戰技巧。

安裝與匯入


pip install Pillow
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont

核心功能類別封裝


class ImageProcessor:
    def __init__(self, input_path: str, output_path: str):
        self.img = Image.open(input_path)
        self.output_path = output_path
    
    def resize(self, percent: float = 100, width: int = None, height: int = None):
        """縮放:百分比或指定寬高"""
        w, h = self.img.size
        if width and height:
            new_size = (width, height)
        else:
            new_size = (int(w * percent / 100), int(h * percent / 100))
        resized = self.img.resize(new_size, Image.Resampling.LANCZOS)  # 高品質重採樣
        resized.save(self.output_path)
        self.img = resized  # 更新內部狀態
        return self
    
    def rotate(self, angle: float, expand: bool = True):
        """旋轉:expand=True 避免裁切"""
        rotated = self.img.rotate(angle, expand=expand, resample=Image.Resampling.BICUBIC)
        rotated.save(self.output_path)
        self.img = rotated
        return self
    
    def save_as(self, format_path: str):
        """轉換格式 (由副檔名決定)"""
        self.img.save(format_path)
        return self
    
    def draw_shapes(self):
        """繪製幾何圖形"""
        draw = ImageDraw.Draw(self.img)
        w, h = self.img.size
        
        # 對角線
        draw.line([(0, 0), (w-1, h-1)], fill='white', width=2)
        draw.line([(0, h-1), (w-1, 0)], fill='white', width=2)
        
        # 橢圓 (外接矩形)
        draw.ellipse([0, 0, w-1, h-1], outline='white', width=2)
        
        # 矩形
        draw.rectangle([10, 10, w-10, h-10], outline='red', width=3)
        
        # 文字 (需字型檔)
        try:
            font = ImageFont.truetype("arial.ttf", 24)
            draw.text((20, 20), "Pillow Demo", fill='yellow', font=font)
        except OSError:
            draw.text((20, 20), "Pillow Demo", fill='yellow')
        
        self.img.save(self.output_path)
        return self
    
    def enhance(self):
        """色彩/銳度/對比度增強"""
        # 亮度
        enhancer = ImageEnhance.Brightness(self.img)
        self.img = enhancer.enhance(1.2)  # 1.0 原始,>1 變亮
        
        # 銳度
        enhancer = ImageEnhance.Sharpness(self.img)
        self.img = enhancer.enhance(2.0)
        
        # 對比度
        enhancer = ImageEnhance.Contrast(self.img)
        self.img = enhancer.enhance(1.3)
        
        # 色彩飽和度
        enhancer = ImageEnhance.Color(self.img)
        self.img = enhancer.enhance(1.2)
        
        self.img.save(self.output_path)
        return self
    
    def apply_filters(self):
        """內建濾鏡"""
        self.img = self.img.filter(ImageFilter.SHARPEN)      # 銳化
        self.img = self.img.filter(ImageFilter.EDGE_ENHANCE) # 邊緣增強
        self.img = self.img.filter(ImageFilter.BLUR)         # 模糊
        self.img = self.img.filter(ImageFilter.GaussianBlur(radius=2)) # 高斯模糊
        self.img = self.img.filter(ImageFilter.EMBOSS)       # 浮雕
        self.img.save(self.output_path)
        return self
    
    def crop(self, box: tuple):
        """裁切: (left, upper, right, lower)"""
        self.img = self.img.crop(box)
        self.img.save(self.output_path)
        return self
    
    def convert_mode(self, mode: str = 'RGB'):
        """模式轉換: RGB, RGBA, L (灰階), CMYK, 1 (二值)"""
        self.img = self.img.convert(mode)
        self.img.save(self.output_path)
        return self
    
    def get_info(self):
        print(f"Size: {self.img.size}, Mode: {self.img.mode}, Format: {self.img.format}")
        return self

# 使用範例
if __name__ == '__main__':
    processor = ImageProcessor('input.jpg', 'output.jpg')
    (processor
     .get_info()
     .resize(percent=50)
     .rotate(45)
     .draw_shapes()
     .enhance()
     .apply_filters()
     .save_as('output.png'))

關鍵技術細節

重採樣濾波器 (Resampling Filters)

濾波器品質速度適用場景
NEAREST低最快像素藝術、索引色
BOX中快縮小
BILINEAR中中一般用途
HAMMING中高中縮小
BICUBIC高較慢放大、高品質
LANCZOS最高最慢專業級縮放 (推薦)

圖片模式 (Mode)

  • `1` - 1-bit 二值圖 (黑白)
  • `L` - 8-bit 灰階
  • `P` - 8-bit 調色盤模式
  • `RGB` - 24-bit 真彩色
  • `RGBA` - 32-bit 真彩色 + Alpha 通道
  • `CMYK` - 印刷四色
  • `YCbCr` - 視訊編碼常用

像素級操作 (高效能)


# 像素存取物件 (C 級速度)
px = img.load()
px[10, 20] = (255, 0, 0)  # 設定單點

# 批量像素操作 (NumPy 互操作)
import numpy as np
arr = np.array(img)        # Image -> ndarray (H, W, C)
arr[:, :, 0] = 255 - arr[:, :, 0]  # 反轉紅通道
img = Image.fromarray(arr) # ndarray -> Image

常見任務範例

批次處理目錄圖片


from pathlib import Path

input_dir = Path('photos')
output_dir = Path('thumbnails')
output_dir.mkdir(exist_ok=True)

for img_path in input_dir.glob('*.jpg'):
    with Image.open(img_path) as img:
        img.thumbnail((300, 300), Image.Resampling.LANCZOS)
        img.save(output_dir / f'{img_path.stem}_thumb.jpg', quality=85, optimize=True)

圖片拼接 (網格)


def grid_montage(images: list, cols: int, gap: int = 5):
    rows = (len(images) + cols - 1) // cols
    max_w = max(img.width for img in images)
    max_h = max(img.height for img in images)
    canvas_w = cols * max_w + (cols - 1) * gap
    canvas_h = rows * max_h + (rows - 1) * gap
    canvas = Image.new('RGB', (canvas_w, canvas_h), 'white')
    
    for idx, img in enumerate(images):
        r, c = divmod(idx, cols)
        x = c * (max_w + gap)
        y = r * (max_h + gap)
        canvas.paste(img, (x, y))
    return canvas

水印添加


def add_watermark(base_img: Image.Image, watermark: Image.Image, 
                  position: str = 'bottom-right', opacity: float = 0.5):
    # 調整水印透明度
    if watermark.mode != 'RGBA':
        watermark = watermark.convert('RGBA')
    alpha = watermark.split()[3]
    alpha = alpha.point(lambda x: int(x * opacity))
    watermark.putalpha(alpha)
    
    # 計算位置
    bw, bh = base_img.size
    ww, wh = watermark.size
    positions = {
        'top-left': (0, 0),
        'top-right': (bw - ww, 0),
        'bottom-left': (0, bh - wh),
        'bottom-right': (bw - ww, bh - wh),
        'center': ((bw - ww)//2, (bh - wh)//2),
    }
    base_img.paste(watermark, positions[position], watermark)
    return base_img

效能優化建議

  • 大量處理時**重用 `Image` 物件**,避免重複 `open`/`save` 磁碟 I/O。
  • 使用 `Image.thumbnail` 就地縮略圖生成 (修改原物件),比 `resize` 省記憶體。
  • 儲存 JPEG 設定 `quality=85, optimize=True` 平衡品質與大小。
  • 像素運算**務必用 NumPy 向量化**,避免 Python 迴圈逐像素處理。
  • 多核心並行處理用 `multiprocessing.Pool` 或 `concurrent.futures`。
copyright © 萬盛學電腦網 all rights reserved