Python Pillow 庫詳解文檔(最新推薦)
Python Pillow 庫詳解文檔
簡介
Pillow (PIL Fork) 是 Python 中最流行的圖像處理庫,它是 Python Imaging Library (PIL) 的現(xiàn)代分支和繼承者。Pillow 提供了廣泛的圖像處理功能,支持多種圖像格式的讀取、處理、保存和顯示。
安裝
pip install Pillow
核心模塊架構(gòu)
Pillow 庫的核心圍繞 Image 類構(gòu)建,同時(shí)提供了多個(gè)專門的子模塊來處理不同的圖像處理任務(wù)。主要的模塊包括圖像基礎(chǔ)操作、濾鏡處理、顏色管理、字體渲染、圖像增強(qiáng)等功能模塊。
Image 模塊 - 核心圖像處理
基本導(dǎo)入和使用
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)打開現(xiàn)有圖像
# 打開圖像文件
img = Image.open('example.jpg')
img = Image.open('path/to/image.png')
# 驗(yàn)證圖像
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"調(diào)色板: {img.palette}")
# 獲取圖像統(tǒng)計(jì)信息
extrema = img.getextrema() # 最小值和最大值
histogram = img.histogram() # 直方圖數(shù)據(jù)圖像變換操作
尺寸調(diào)整
# 調(diào)整圖像大小 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)) # 保持寬高比
旋轉(zhuǎn)和翻轉(zhuǎn)
# 旋轉(zhuǎn)圖像 rotated = img.rotate(45) # 順時(shí)針旋轉(zhuǎn)45度 rotated = img.rotate(90, expand=True) # 擴(kuò)展畫布適應(yīng)旋轉(zhuǎn) # 翻轉(zhuǎn)圖像 flipped_h = img.transpose(Image.FLIP_LEFT_RIGHT) # 水平翻轉(zhuǎn) flipped_v = img.transpose(Image.FLIP_TOP_BOTTOM) # 垂直翻轉(zhuǎn) rotated_90 = img.transpose(Image.ROTATE_90) # 90度旋轉(zhuǎn)
裁剪操作
# 矩形裁剪
box = (100, 100, 400, 300) # (left, top, right, bottom)
cropped = img.crop(box)
# 智能裁剪到內(nèi)容邊界
bbox = img.getbbox()
if bbox:
trimmed = img.crop(bbox)圖像模式轉(zhuǎn)換
# 模式轉(zhuǎn)換
gray_img = img.convert('L') # 轉(zhuǎn)為灰度
rgba_img = img.convert('RGBA') # 添加透明通道
rgb_img = img.convert('RGB') # 移除透明通道
# 帶抖動(dòng)的轉(zhuǎn)換
palette_img = img.convert('P', dither=Image.FLOYDSTEINBERG)ImageDraw 模塊 - 圖形繪制
ImageDraw 模塊提供了在圖像上繪制各種圖形和文本的功能。
基礎(chǔ)繪制操作
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')文本繪制
# 基礎(chǔ)文本繪制
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:
# 使用默認(rèn)字體
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 模塊提供了各種圖像濾鏡效果。
內(nèi)置濾鏡
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)建自定義濾鏡內(nèi)核
from PIL.ImageFilter import Kernel
# 3x3 拉普拉斯算子
laplacian_kernel = Kernel((3, 3), [
-1, -1, -1,
-1, 8, -1,
-1, -1, -1
])
# 應(yīng)用自定義濾鏡
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 模塊 - 圖像增強(qiáng)
ImageEnhance 模塊提供了調(diào)整圖像亮度、對比度、飽和度和銳度的功能。
from PIL import Image, ImageEnhance
img = Image.open('example.jpg')
# 亮度調(diào)整
brightness = ImageEnhance.Brightness(img)
bright_img = brightness.enhance(1.5) # 增加50%亮度
dark_img = brightness.enhance(0.5) # 減少50%亮度
# 對比度調(diào)整
contrast = ImageEnhance.Contrast(img)
high_contrast = contrast.enhance(2.0) # 增強(qiáng)對比度
low_contrast = contrast.enhance(0.5) # 降低對比度
# 顏色飽和度調(diào)整
color = ImageEnhance.Color(img)
saturated = color.enhance(1.8) # 增強(qiáng)飽和度
desaturated = color.enhance(0.2) # 降低飽和度(接近灰度)
# 銳度調(diào)整
sharpness = ImageEnhance.Sharpness(img)
sharp_img = sharpness.enhance(2.0) # 增強(qiáng)銳度
soft_img = sharpness.enhance(0.5) # 降低銳度ImageOps 模塊 - 圖像操作
ImageOps 模塊提供了許多實(shí)用的圖像操作函數(shù)。
from PIL import Image, ImageOps
img = Image.open('example.jpg')
# 自動(dòng)對比度
autocontrast_img = ImageOps.autocontrast(img)
# 顏色均衡
equalized_img = ImageOps.equalize(img)
# 反轉(zhuǎn)顏色
inverted_img = ImageOps.invert(img)
# 灰度化
grayscale_img = ImageOps.grayscale(img)
# 鏡像翻轉(zhuǎn)
mirrored_img = ImageOps.mirror(img)
# 適應(yīng)尺寸(保持寬高比)
fitted_img = ImageOps.fit(img, (300, 300), method=Image.LANCZOS)
# 添加邊框
bordered_img = ImageOps.expand(img, border=20, fill='black')
# 色調(diào)分離
posterized_img = ImageOps.posterize(img, bits=4)
# 曝光度調(diào)整
solarized_img = ImageOps.solarize(img, threshold=128)ImageColor 模塊 - 顏色處理
ImageColor 模塊提供了顏色格式轉(zhuǎn)換和顏色名稱解析功能。
from PIL import ImageColor
# 顏色名稱轉(zhuǎn)RGB
red_rgb = ImageColor.getrgb('red') # (255, 0, 0)
blue_rgb = ImageColor.getrgb('#0000FF') # (0, 0, 255)
# 轉(zhuǎn)換為RGBA
red_rgba = ImageColor.getcolor('red', 'RGBA') # (255, 0, 0, 255)
# HSL轉(zhuǎn)RGB
hsl_color = ImageColor.getcolor('hsl(120, 100%, 50%)', 'RGB') # (0, 255, 0)
# 支持的顏色格式
formats = [
'red', # 顏色名稱
'#FF0000', # 十六進(jìn)制
'rgb(255, 0, 0)', # RGB函數(shù)
'rgba(255, 0, 0, 1.0)', # RGBA函數(shù)
'hsl(0, 100%, 50%)', # HSL函數(shù)
]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:
# 使用默認(rèn)字體
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')
# 獲取字體指標(biāo)
ascent, descent = font_large.getmetrics()
text_size = font_large.getsize("Sample Text")實(shí)際應(yīng)用示例
圖像批處理
import os
from PIL import Image
def batch_resize(input_dir, output_dir, size=(800, 600)):
"""批量調(diào)整圖像尺寸"""
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)
# 設(shè)置字體和位置
try:
font = ImageFont.truetype("arial.ttf", 36)
except:
font = ImageFont.load_default()
# 計(jì)算文本位置(右下角)
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)圖像格式轉(zhuǎn)換
def convert_format(input_path, output_path, output_format='JPEG'):
"""轉(zhuǎn)換圖像格式"""
with Image.open(input_path) as img:
# 如果目標(biāo)格式不支持透明度,轉(zhuǎn)換為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)
# 計(jì)算拼貼尺寸
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 進(jìn)行圖像處理時(shí),應(yīng)該注意內(nèi)存管理和性能優(yōu)化。對于大圖像處理,建議使用 with 語句確保及時(shí)釋放資源,選擇合適的重采樣算法以平衡質(zhì)量和速度。批處理時(shí)可以考慮多線程處理以提高效率,同時(shí)注意設(shè)置合適的圖像質(zhì)量參數(shù)以控制輸出文件大小。
對于需要處理大量圖像的應(yīng)用,可以考慮結(jié)合 NumPy 進(jìn)行數(shù)值計(jì)算,或使用 Pillow-SIMD 等優(yōu)化版本來獲得更好的性能表現(xiàn)。在 Web 應(yīng)用中使用時(shí),應(yīng)該注意設(shè)置合理的圖像尺寸限制和格式檢查,以防止惡意文件攻擊。
錯(cuò)誤處理和調(diào)試
在實(shí)際應(yīng)用中,應(yīng)該對圖像操作進(jìn)行適當(dāng)?shù)腻e(cuò)誤處理,檢查文件存在性、格式支持性和內(nèi)存限制等問題。Pillow 提供了詳細(xì)的異常信息,可以幫助快速定位和解決問題。建議在生產(chǎn)環(huán)境中添加日志記錄,以便追蹤圖像處理的執(zhí)行情況和性能指標(biāo)。
到此這篇關(guān)于Python Pillow 庫詳解文檔的文章就介紹到這了,更多相關(guān)Python Pillow 庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中執(zhí)行調(diào)用JS的多種實(shí)現(xiàn)方法總結(jié)
這篇文章主要給大家介紹了關(guān)于Python中執(zhí)行調(diào)用JS的多種實(shí)現(xiàn)方法,在一些特殊的python應(yīng)用場景下需要逆向執(zhí)行javascript代碼塊或者.js文件,需要的朋友可以參考下2023-08-08
利用插件和python實(shí)現(xiàn)Excel轉(zhuǎn)json的兩種辦法
轉(zhuǎn)換Excel表格到JSON格式有很多方法,下面這篇文章主要給大家介紹了關(guān)于利用插件和python實(shí)現(xiàn)Excel轉(zhuǎn)json的兩種辦法,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-11-11
Python封裝Netcat打造跨平臺(tái)文件傳輸利器
作為網(wǎng)絡(luò)安全工程師,我發(fā)現(xiàn)將命令行工具圖形化能極大提升滲透測試效率,本文我們就來看看Python如何封裝Netcat打造跨平臺(tái)文件傳輸利器,感興趣的可以了解下2025-07-07
基于Python實(shí)現(xiàn)一個(gè)多分類的Logistic回歸模型的代碼示例
在機(jī)器學(xué)習(xí)中,Logistic回歸是一種基本但非常有效的分類算法,它不僅可以用于二分類問題,還可以擴(kuò)展應(yīng)用于多分類問題,本文將詳細(xì)介紹如何使用Python實(shí)現(xiàn)一個(gè)多分類的Logistic回歸模型,并給出詳細(xì)的代碼示例,需要的朋友可以參考下2025-01-01
Python實(shí)現(xiàn)將列表高效導(dǎo)出為 Excel 文件
在當(dāng)今數(shù)據(jù)驅(qū)動(dòng)的世界中,Python 已成為數(shù)據(jù)處理和分析的強(qiáng)大工具,本文將深入探討如何利用 Spire.XLS for Python 庫將列表導(dǎo)出為 Excel 文件,感興趣的小伙伴可以了解下2025-12-12
使用python+Flask實(shí)現(xiàn)日志在web網(wǎng)頁實(shí)時(shí)更新顯示
日志是一種可以追蹤某些軟件運(yùn)行時(shí)所發(fā)生事件的方法,下面這篇文章主要給大家介紹了關(guān)于使用python+Flask實(shí)現(xiàn)日志在web網(wǎng)頁實(shí)時(shí)更新顯示的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
Python import用法以及與from...import的區(qū)別
這篇文章主要介紹了Python import用法以及與from...import的區(qū)別,本文簡潔明了,很容易看懂,需要的朋友可以參考下2015-05-05

