Python Pillow 庫詳解文檔(最新推薦)
Python Pillow 庫詳解文檔
簡介
Pillow (PIL Fork) 是 Python 中最流行的圖像處理庫,它是 Python Imaging Library (PIL) 的現代分支和繼承者。Pillow 提供了廣泛的圖像處理功能,支持多種圖像格式的讀取、處理、保存和顯示。
安裝
pip install Pillow
核心模塊架構
Pillow 庫的核心圍繞 Image 類構建,同時提供了多個專門的子模塊來處理不同的圖像處理任務。主要的模塊包括圖像基礎操作、濾鏡處理、顏色管理、字體渲染、圖像增強等功能模塊。
Image 模塊 - 核心圖像處理
基本導入和使用
from PIL import Image, ImageDraw, ImageFont import os
圖像創(chuàng)建與打開
創(chuàng)建新圖像
# 創(chuàng)建空白圖像
img = Image.new('RGB', (800, 600), color='white')
img = Image.new('RGBA', (400, 300), color=(255, 0, 0, 128))
# 創(chuàng)建漸變圖像
img = Image.new('L', (256, 256))
for x in range(256):
for y in range(256):
img.putpixel((x, y), x)打開現有圖像
# 打開圖像文件
img = Image.open('example.jpg')
img = Image.open('path/to/image.png')
# 驗證圖像
try:
img.verify()
print("圖像文件有效")
except:
print("圖像文件損壞")圖像基本屬性和信息
# 獲取圖像基本信息
print(f"尺寸: {img.size}") # (width, height)
print(f"模式: {img.mode}") # RGB, RGBA, L, P 等
print(f"格式: {img.format}") # JPEG, PNG, GIF 等
print(f"調色板: {img.palette}")
# 獲取圖像統(tǒng)計信息
extrema = img.getextrema() # 最小值和最大值
histogram = img.histogram() # 直方圖數據圖像變換操作
尺寸調整
# 調整圖像大小 resized = img.resize((400, 300)) # 指定尺寸 resized = img.resize((400, 300), Image.LANCZOS) # 指定重采樣算法 # 按比例縮放 width, height = img.size new_img = img.resize((width//2, height//2)) # 創(chuàng)建縮略圖 img.thumbnail((128, 128)) # 保持寬高比
旋轉和翻轉
# 旋轉圖像 rotated = img.rotate(45) # 順時針旋轉45度 rotated = img.rotate(90, expand=True) # 擴展畫布適應旋轉 # 翻轉圖像 flipped_h = img.transpose(Image.FLIP_LEFT_RIGHT) # 水平翻轉 flipped_v = img.transpose(Image.FLIP_TOP_BOTTOM) # 垂直翻轉 rotated_90 = img.transpose(Image.ROTATE_90) # 90度旋轉
裁剪操作
# 矩形裁剪
box = (100, 100, 400, 300) # (left, top, right, bottom)
cropped = img.crop(box)
# 智能裁剪到內容邊界
bbox = img.getbbox()
if bbox:
trimmed = img.crop(bbox)圖像模式轉換
# 模式轉換
gray_img = img.convert('L') # 轉為灰度
rgba_img = img.convert('RGBA') # 添加透明通道
rgb_img = img.convert('RGB') # 移除透明通道
# 帶抖動的轉換
palette_img = img.convert('P', dither=Image.FLOYDSTEINBERG)ImageDraw 模塊 - 圖形繪制
ImageDraw 模塊提供了在圖像上繪制各種圖形和文本的功能。
基礎繪制操作
from PIL import Image, ImageDraw
# 創(chuàng)建繪制對象
img = Image.new('RGB', (400, 300), 'white')
draw = ImageDraw.Draw(img)
# 繪制基本形狀
draw.rectangle([50, 50, 150, 100], fill='red', outline='black', width=2)
draw.ellipse([200, 50, 350, 150], fill='blue', outline='navy')
draw.line([0, 0, 400, 300], fill='green', width=3)
# 繪制多邊形
points = [(100, 200), (150, 250), (200, 200), (175, 150), (125, 150)]
draw.polygon(points, fill='yellow', outline='orange')文本繪制
# 基礎文本繪制
draw.text((50, 200), "Hello World", fill='black')
# 使用自定義字體
try:
font = ImageFont.truetype("arial.ttf", 24)
draw.text((50, 250), "Custom Font", font=font, fill='blue')
except:
# 使用默認字體
font = ImageFont.load_default()
draw.text((50, 250), "Default Font", font=font, fill='blue')
# 獲取文本尺寸
text = "Measure me"
bbox = draw.textbbox((0, 0), text, font=font)
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]高級繪制功能
# 繪制圓弧 draw.arc([100, 100, 200, 200], start=0, end=180, fill='red', width=3) # 繪制扇形 draw.pieslice([250, 100, 350, 200], start=0, end=90, fill='green') # 繪制多條線段 points = [(0, 150), (100, 100), (200, 150), (300, 100), (400, 150)] draw.line(points, fill='purple', width=2)
ImageFilter 模塊 - 圖像濾鏡
ImageFilter 模塊提供了各種圖像濾鏡效果。
內置濾鏡
from PIL import Image, ImageFilter
img = Image.open('example.jpg')
# 模糊濾鏡
blurred = img.filter(ImageFilter.BLUR)
gaussian_blur = img.filter(ImageFilter.GaussianBlur(radius=2))
# 銳化濾鏡
sharpened = img.filter(ImageFilter.SHARPEN)
unsharp_mask = img.filter(ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3))
# 邊緣檢測
edges = img.filter(ImageFilter.FIND_EDGES)
edge_enhance = img.filter(ImageFilter.EDGE_ENHANCE)
# 浮雕效果
embossed = img.filter(ImageFilter.EMBOSS)
# 輪廓檢測
contour = img.filter(ImageFilter.CONTOUR)自定義卷積濾鏡
# 創(chuàng)建自定義濾鏡內核
from PIL.ImageFilter import Kernel
# 3x3 拉普拉斯算子
laplacian_kernel = Kernel((3, 3), [
-1, -1, -1,
-1, 8, -1,
-1, -1, -1
])
# 應用自定義濾鏡
filtered_img = img.filter(laplacian_kernel)
# 5x5 高斯模糊核
gaussian_5x5 = Kernel((5, 5), [
1, 4, 6, 4, 1,
4, 16, 24, 16, 4,
6, 24, 36, 24, 6,
4, 16, 24, 16, 4,
1, 4, 6, 4, 1
], scale=256)ImageEnhance 模塊 - 圖像增強
ImageEnhance 模塊提供了調整圖像亮度、對比度、飽和度和銳度的功能。
from PIL import Image, ImageEnhance
img = Image.open('example.jpg')
# 亮度調整
brightness = ImageEnhance.Brightness(img)
bright_img = brightness.enhance(1.5) # 增加50%亮度
dark_img = brightness.enhance(0.5) # 減少50%亮度
# 對比度調整
contrast = ImageEnhance.Contrast(img)
high_contrast = contrast.enhance(2.0) # 增強對比度
low_contrast = contrast.enhance(0.5) # 降低對比度
# 顏色飽和度調整
color = ImageEnhance.Color(img)
saturated = color.enhance(1.8) # 增強飽和度
desaturated = color.enhance(0.2) # 降低飽和度(接近灰度)
# 銳度調整
sharpness = ImageEnhance.Sharpness(img)
sharp_img = sharpness.enhance(2.0) # 增強銳度
soft_img = sharpness.enhance(0.5) # 降低銳度ImageOps 模塊 - 圖像操作
ImageOps 模塊提供了許多實用的圖像操作函數。
from PIL import Image, ImageOps
img = Image.open('example.jpg')
# 自動對比度
autocontrast_img = ImageOps.autocontrast(img)
# 顏色均衡
equalized_img = ImageOps.equalize(img)
# 反轉顏色
inverted_img = ImageOps.invert(img)
# 灰度化
grayscale_img = ImageOps.grayscale(img)
# 鏡像翻轉
mirrored_img = ImageOps.mirror(img)
# 適應尺寸(保持寬高比)
fitted_img = ImageOps.fit(img, (300, 300), method=Image.LANCZOS)
# 添加邊框
bordered_img = ImageOps.expand(img, border=20, fill='black')
# 色調分離
posterized_img = ImageOps.posterize(img, bits=4)
# 曝光度調整
solarized_img = ImageOps.solarize(img, threshold=128)ImageColor 模塊 - 顏色處理
ImageColor 模塊提供了顏色格式轉換和顏色名稱解析功能。
from PIL import ImageColor
# 顏色名稱轉RGB
red_rgb = ImageColor.getrgb('red') # (255, 0, 0)
blue_rgb = ImageColor.getrgb('#0000FF') # (0, 0, 255)
# 轉換為RGBA
red_rgba = ImageColor.getcolor('red', 'RGBA') # (255, 0, 0, 255)
# HSL轉RGB
hsl_color = ImageColor.getcolor('hsl(120, 100%, 50%)', 'RGB') # (0, 255, 0)
# 支持的顏色格式
formats = [
'red', # 顏色名稱
'#FF0000', # 十六進制
'rgb(255, 0, 0)', # RGB函數
'rgba(255, 0, 0, 1.0)', # RGBA函數
'hsl(0, 100%, 50%)', # HSL函數
]ImageFont 模塊 - 字體處理
ImageFont 模塊用于加載和使用字體文件。
from PIL import Image, ImageDraw, ImageFont
# 加載TrueType字體
try:
font_large = ImageFont.truetype("arial.ttf", 36)
font_small = ImageFont.truetype("arial.ttf", 16)
except:
# 使用默認字體
font_large = ImageFont.load_default()
font_small = ImageFont.load_default()
# 使用字體繪制文本
img = Image.new('RGB', (400, 200), 'white')
draw = ImageDraw.Draw(img)
draw.text((10, 10), "Large Text", font=font_large, fill='black')
draw.text((10, 60), "Small Text", font=font_small, fill='gray')
# 獲取字體指標
ascent, descent = font_large.getmetrics()
text_size = font_large.getsize("Sample Text")實際應用示例
圖像批處理
import os
from PIL import Image
def batch_resize(input_dir, output_dir, size=(800, 600)):
"""批量調整圖像尺寸"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp')):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
try:
with Image.open(input_path) as img:
img.thumbnail(size, Image.LANCZOS)
img.save(output_path, optimize=True, quality=85)
print(f"處理完成: {filename}")
except Exception as e:
print(f"處理失敗 {filename}: {e}")水印添加
def add_watermark(image_path, watermark_text, output_path):
"""為圖像添加文字水印"""
with Image.open(image_path) as img:
# 創(chuàng)建透明層
overlay = Image.new('RGBA', img.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(overlay)
# 設置字體和位置
try:
font = ImageFont.truetype("arial.ttf", 36)
except:
font = ImageFont.load_default()
# 計算文本位置(右下角)
text_bbox = draw.textbbox((0, 0), watermark_text, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
x = img.width - text_width - 20
y = img.height - text_height - 20
# 繪制半透明文字
draw.text((x, y), watermark_text, font=font, fill=(255, 255, 255, 128))
# 合并圖層
watermarked = Image.alpha_composite(img.convert('RGBA'), overlay)
watermarked.convert('RGB').save(output_path, quality=95)圖像格式轉換
def convert_format(input_path, output_path, output_format='JPEG'):
"""轉換圖像格式"""
with Image.open(input_path) as img:
# 如果目標格式不支持透明度,轉換為RGB
if output_format in ['JPEG', 'BMP'] and img.mode in ['RGBA', 'LA']:
background = Image.new('RGB', img.size, (255, 255, 255))
background.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else None)
img = background
img.save(output_path, format=output_format, quality=95)創(chuàng)建圖像拼貼
def create_collage(image_paths, output_path, cols=3, spacing=10):
"""創(chuàng)建圖像拼貼"""
images = []
for path in image_paths:
img = Image.open(path)
img.thumbnail((200, 200), Image.LANCZOS)
images.append(img)
# 計算拼貼尺寸
rows = (len(images) + cols - 1) // cols
max_width = max(img.width for img in images)
max_height = max(img.height for img in images)
total_width = cols * max_width + (cols - 1) * spacing
total_height = rows * max_height + (rows - 1) * spacing
# 創(chuàng)建拼貼畫布
collage = Image.new('RGB', (total_width, total_height), 'white')
# 粘貼圖像
for i, img in enumerate(images):
row = i // cols
col = i % cols
x = col * (max_width + spacing)
y = row * (max_height + spacing)
collage.paste(img, (x, y))
collage.save(output_path, quality=95)性能優(yōu)化建議
使用 Pillow 進行圖像處理時,應該注意內存管理和性能優(yōu)化。對于大圖像處理,建議使用 with 語句確保及時釋放資源,選擇合適的重采樣算法以平衡質量和速度。批處理時可以考慮多線程處理以提高效率,同時注意設置合適的圖像質量參數以控制輸出文件大小。
對于需要處理大量圖像的應用,可以考慮結合 NumPy 進行數值計算,或使用 Pillow-SIMD 等優(yōu)化版本來獲得更好的性能表現。在 Web 應用中使用時,應該注意設置合理的圖像尺寸限制和格式檢查,以防止惡意文件攻擊。
錯誤處理和調試
在實際應用中,應該對圖像操作進行適當的錯誤處理,檢查文件存在性、格式支持性和內存限制等問題。Pillow 提供了詳細的異常信息,可以幫助快速定位和解決問題。建議在生產環(huán)境中添加日志記錄,以便追蹤圖像處理的執(zhí)行情況和性能指標。
到此這篇關于Python Pillow 庫詳解文檔的文章就介紹到這了,更多相關Python Pillow 庫內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
基于Python實現一個多分類的Logistic回歸模型的代碼示例
在機器學習中,Logistic回歸是一種基本但非常有效的分類算法,它不僅可以用于二分類問題,還可以擴展應用于多分類問題,本文將詳細介紹如何使用Python實現一個多分類的Logistic回歸模型,并給出詳細的代碼示例,需要的朋友可以參考下2025-01-01
使用python+Flask實現日志在web網頁實時更新顯示
日志是一種可以追蹤某些軟件運行時所發(fā)生事件的方法,下面這篇文章主要給大家介紹了關于使用python+Flask實現日志在web網頁實時更新顯示的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2022-08-08
Python import用法以及與from...import的區(qū)別
這篇文章主要介紹了Python import用法以及與from...import的區(qū)別,本文簡潔明了,很容易看懂,需要的朋友可以參考下2015-05-05

