Python實(shí)現(xiàn)批量自動(dòng)化處理圖像的完整指南
在日常辦公中,我們經(jīng)常需要處理大量圖像,如產(chǎn)品照片、營銷素材、文檔掃描件等。手動(dòng)處理這些圖像不僅耗時(shí),還容易出錯(cuò)。通過Python自動(dòng)化圖像處理,我們可以高效地完成批量縮放、裁剪、加水印、格式轉(zhuǎn)換等任務(wù),大大提高工作效率。
本文將介紹兩個(gè)強(qiáng)大的Python圖像處理庫:Pillow(PIL的fork版本)和OpenCV,并通過實(shí)例展示如何使用它們實(shí)現(xiàn)各種圖像處理自動(dòng)化任務(wù)。
使用Pillow操作圖像
Pillow是Python中最流行的圖像處理庫之一,它簡單易用,功能強(qiáng)大,適合大多數(shù)日常圖像處理任務(wù)。
安裝Pillow
pip install Pillow
打開和保存圖像
from PIL import Image
# 打開圖像
img = Image.open('example.jpg')
# 顯示圖像信息
print(f"圖像格式: {img.format}")
print(f"圖像大小: {img.size}")
print(f"圖像模式: {img.mode}")
# 保存圖像(可以指定不同格式)
img.save('example_copy.jpg') # 保存為JPG
img.save('example.png') # 保存為PNG
img.save('example.webp', quality=80) # 保存為WebP,指定質(zhì)量
圖像縮放
PIL.Image.Image 類包含重新調(diào)整圖像大小的 resize() 方法,參數(shù)為指定新尺寸的元組。
from PIL import Image
def resize_image(input_path, output_path, new_size):
"""調(diào)整圖像大小
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
new_size: 新尺寸,格式為(寬, 高)
"""
try:
# 打開原始圖像
img = Image.open(input_path)
# 調(diào)整大小
resized_img = img.resize(new_size)
# 保存調(diào)整后的圖像
resized_img.save(output_path)
print(f"已將圖像從 {img.size} 調(diào)整為 {new_size}")
return True
except Exception as e:
print(f"調(diào)整圖像大小時(shí)出錯(cuò): {e}")
return False
# 使用示例
resize_image('example.jpg', 'example_resized.jpg', (800, 600))
等比例縮放
from PIL import Image
def resize_image_proportionally(input_path, output_path, max_size):
"""等比例調(diào)整圖像大小,保持寬高比
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
max_size: 最大尺寸,格式為(最大寬度, 最大高度)
"""
try:
# 打開原始圖像
img = Image.open(input_path)
# 獲取原始尺寸
width, height = img.size
# 計(jì)算縮放比例
max_width, max_height = max_size
scale = min(max_width / width, max_height / height)
# 計(jì)算新尺寸
new_width = int(width * scale)
new_height = int(height * scale)
# 調(diào)整大小
resized_img = img.resize((new_width, new_height))
# 保存調(diào)整后的圖像
resized_img.save(output_path)
print(f"已將圖像從 {img.size} 等比例調(diào)整為 {resized_img.size}")
return True
except Exception as e:
print(f"調(diào)整圖像大小時(shí)出錯(cuò): {e}")
return False
# 使用示例
resize_image_proportionally('example.jpg', 'example_resized_prop.jpg', (800, 600))
圖像裁剪
from PIL import Image
def crop_image(input_path, output_path, crop_box):
"""裁剪圖像
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
crop_box: 裁剪區(qū)域,格式為(左, 上, 右, 下)
"""
try:
# 打開原始圖像
img = Image.open(input_path)
# 裁剪圖像
cropped_img = img.crop(crop_box)
# 保存裁剪后的圖像
cropped_img.save(output_path)
print(f"已裁剪圖像,裁剪區(qū)域: {crop_box}")
return True
except Exception as e:
print(f"裁剪圖像時(shí)出錯(cuò): {e}")
return False
# 使用示例
crop_image('example.jpg', 'example_cropped.jpg', (100, 100, 500, 400))
圖像旋轉(zhuǎn)
PIL.Image.Image 類包含旋轉(zhuǎn)圖像的 rotate() 方法,參數(shù)為逆時(shí)針旋轉(zhuǎn)的角度。
from PIL import Image
def rotate_image(input_path, output_path, angle, expand=True):
"""旋轉(zhuǎn)圖像
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
angle: 旋轉(zhuǎn)角度(逆時(shí)針)
expand: 是否擴(kuò)展畫布以適應(yīng)旋轉(zhuǎn)后的圖像
"""
try:
# 打開原始圖像
img = Image.open(input_path)
# 旋轉(zhuǎn)圖像
rotated_img = img.rotate(angle, expand=expand)
# 保存旋轉(zhuǎn)后的圖像
rotated_img.save(output_path)
print(f"已將圖像旋轉(zhuǎn) {angle} 度")
return True
except Exception as e:
print(f"旋轉(zhuǎn)圖像時(shí)出錯(cuò): {e}")
return False
# 使用示例
rotate_image('example.jpg', 'example_rotated.jpg', 90) # 旋轉(zhuǎn)90度
圖像格式轉(zhuǎn)換
Python Imaging Library允許你使用 convert() 方法在不同像素表示之間轉(zhuǎn)換圖像,同時(shí)可以通過保存時(shí)指定不同的擴(kuò)展名來轉(zhuǎn)換格式。
from PIL import Image
import os
def convert_image_format(input_path, output_format):
"""轉(zhuǎn)換圖像格式
Args:
input_path: 輸入圖像路徑
output_format: 輸出格式(如'png', 'jpg', 'webp'等)
"""
try:
# 打開原始圖像
img = Image.open(input_path)
# 獲取文件名(不含擴(kuò)展名)
filename = os.path.splitext(os.path.basename(input_path))[0]
# 構(gòu)建輸出路徑
output_path = f"{filename}.{output_format.lower()}"
# 保存為新格式
img.save(output_path)
print(f"已將圖像從 {os.path.splitext(input_path)[1]} 轉(zhuǎn)換為 {output_format}")
return output_path
except Exception as e:
print(f"轉(zhuǎn)換圖像格式時(shí)出錯(cuò): {e}")
return None
# 使用示例
convert_image_format('example.jpg', 'png') # 將JPG轉(zhuǎn)換為PNG
convert_image_format('example.jpg', 'webp') # 將JPG轉(zhuǎn)換為WebP
添加水印
from PIL import Image, ImageDraw, ImageFont
def add_text_watermark(input_path, output_path, text, position=None, color=(255, 255, 255, 128), font_size=40):
"""添加文字水印
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
text: 水印文字
position: 水印位置,格式為(x, y),默認(rèn)為None(居中)
color: 水印顏色,格式為(R, G, B, A),默認(rèn)為半透明白色
font_size: 字體大小
"""
try:
# 打開原始圖像
img = Image.open(input_path).convert("RGBA")
# 創(chuàng)建透明圖層
txt = Image.new('RGBA', img.size, (255, 255, 255, 0))
# 獲取繪圖對象
draw = ImageDraw.Draw(txt)
# 加載字體
try:
font = ImageFont.truetype("Arial.ttf", font_size)
except IOError:
font = ImageFont.load_default()
# 計(jì)算文本大小
text_width, text_height = draw.textsize(text, font)
# 如果未指定位置,則居中放置
if position is None:
position = ((img.width - text_width) // 2, (img.height - text_height) // 2)
# 繪制水印文字
draw.text(position, text, font=font, fill=color)
# 合并圖層
watermarked = Image.alpha_composite(img, txt)
# 保存結(jié)果
watermarked.convert('RGB').save(output_path)
print(f"已添加文字水印: '{text}'")
return True
except Exception as e:
print(f"添加水印時(shí)出錯(cuò): {e}")
return False
def add_image_watermark(input_path, output_path, watermark_path, position=None, opacity=0.3):
"""添加圖像水印
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
watermark_path: 水印圖像路徑
position: 水印位置,格式為(x, y),默認(rèn)為None(右下角)
opacity: 水印透明度,0-1之間
"""
try:
# 打開原始圖像和水印
base_image = Image.open(input_path).convert("RGBA")
watermark = Image.open(watermark_path).convert("RGBA")
# 調(diào)整水印大?。蛇x,這里設(shè)為原圖的1/4寬度)
watermark_width = base_image.width // 4
watermark_height = int(watermark.height * watermark_width / watermark.width)
watermark = watermark.resize((watermark_width, watermark_height))
# 調(diào)整水印透明度
watermark_with_opacity = Image.new('RGBA', watermark.size, (0, 0, 0, 0))
for x in range(watermark.width):
for y in range(watermark.height):
r, g, b, a = watermark.getpixel((x, y))
watermark_with_opacity.putpixel((x, y), (r, g, b, int(a * opacity)))
# 如果未指定位置,則放在右下角
if position is None:
position = (base_image.width - watermark_width - 10, base_image.height - watermark_height - 10)
# 創(chuàng)建透明圖層
transparent = Image.new('RGBA', base_image.size, (0, 0, 0, 0))
transparent.paste(watermark_with_opacity, position)
# 合并圖層
watermarked = Image.alpha_composite(base_image, transparent)
# 保存結(jié)果
watermarked.convert('RGB').save(output_path)
print(f"已添加圖像水印")
return True
except Exception as e:
print(f"添加水印時(shí)出錯(cuò): {e}")
return False
# 使用示例
add_text_watermark('example.jpg', 'example_text_watermark.jpg', '? 2023 公司名稱')
add_image_watermark('example.jpg', 'example_image_watermark.jpg', 'logo.png')
圖像增強(qiáng)
Python Imaging Library提供了許多可用于增強(qiáng)圖像的方法和模塊。比如 ImageFilter 模塊包含許多可以與 filter() 方法一起使用的預(yù)定義增強(qiáng)濾波器。
from PIL import Image, ImageEnhance, ImageFilter
def enhance_image(input_path, output_path, brightness=1.0, contrast=1.0, sharpness=1.0, color=1.0):
"""增強(qiáng)圖像
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
brightness: 亮度因子,1.0為原始亮度
contrast: 對比度因子,1.0為原始對比度
sharpness: 銳度因子,1.0為原始銳度
color: 色彩因子,1.0為原始色彩
"""
try:
# 打開原始圖像
img = Image.open(input_path)
# 調(diào)整亮度
if brightness != 1.0:
enhancer = ImageEnhance.Brightness(img)
img = enhancer.enhance(brightness)
# 調(diào)整對比度
if contrast != 1.0:
enhancer = ImageEnhance.Contrast(img)
img = enhancer.enhance(contrast)
# 調(diào)整銳度
if sharpness != 1.0:
enhancer = ImageEnhance.Sharpness(img)
img = enhancer.enhance(sharpness)
# 調(diào)整色彩
if color != 1.0:
enhancer = ImageEnhance.Color(img)
img = enhancer.enhance(color)
# 保存增強(qiáng)后的圖像
img.save(output_path)
print(f"已增強(qiáng)圖像")
return True
except Exception as e:
print(f"增強(qiáng)圖像時(shí)出錯(cuò): {e}")
return False
def apply_filter(input_path, output_path, filter_type):
"""應(yīng)用濾鏡
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
filter_type: 濾鏡類型,如'BLUR', 'CONTOUR', 'SHARPEN'等
"""
try:
# 打開原始圖像
img = Image.open(input_path)
# 應(yīng)用濾鏡
if filter_type == 'BLUR':
filtered_img = img.filter(ImageFilter.BLUR)
elif filter_type == 'CONTOUR':
filtered_img = img.filter(ImageFilter.CONTOUR)
elif filter_type == 'SHARPEN':
filtered_img = img.filter(ImageFilter.SHARPEN)
elif filter_type == 'EMBOSS':
filtered_img = img.filter(ImageFilter.EMBOSS)
elif filter_type == 'EDGE_ENHANCE':
filtered_img = img.filter(ImageFilter.EDGE_ENHANCE)
elif filter_type == 'SMOOTH':
filtered_img = img.filter(ImageFilter.SMOOTH)
else:
print(f"未知濾鏡類型: {filter_type}")
return False
# 保存處理后的圖像
filtered_img.save(output_path)
print(f"已應(yīng)用 {filter_type} 濾鏡")
return True
except Exception as e:
print(f"應(yīng)用濾鏡時(shí)出錯(cuò): {e}")
return False
# 使用示例
enhance_image('example.jpg', 'example_enhanced.jpg', brightness=1.2, contrast=1.1, sharpness=1.3)
apply_filter('example.jpg', 'example_blur.jpg', 'BLUR')
apply_filter('example.jpg', 'example_sharpen.jpg', 'SHARPEN')
批量處理圖像
import os
from PIL import Image
def batch_process_images(input_folder, output_folder, process_func, **kwargs):
"""批量處理圖像
Args:
input_folder: 輸入文件夾路徑
output_folder: 輸出文件夾路徑
process_func: 處理函數(shù)
**kwargs: 傳遞給處理函數(shù)的參數(shù)
"""
# 確保輸出文件夾存在
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 獲取所有圖像文件
image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp')
image_files = [f for f in os.listdir(input_folder)
if os.path.isfile(os.path.join(input_folder, f))
and f.lower().endswith(image_extensions)]
# 處理每個(gè)圖像
success_count = 0
for image_file in image_files:
input_path = os.path.join(input_folder, image_file)
output_path = os.path.join(output_folder, image_file)
try:
# 調(diào)用處理函數(shù)
result = process_func(input_path, output_path, **kwargs)
if result:
success_count += 1
except Exception as e:
print(f"處理 {image_file} 時(shí)出錯(cuò): {e}")
print(f"批量處理完成,成功處理 {success_count}/{len(image_files)} 個(gè)文件")
return success_count
# 定義一個(gè)簡單的處理函數(shù)(調(diào)整大?。?
def resize_for_batch(input_path, output_path, width, height):
try:
img = Image.open(input_path)
img = img.resize((width, height))
img.save(output_path)
return True
except Exception as e:
print(f"處理 {input_path} 時(shí)出錯(cuò): {e}")
return False
# 使用示例
batch_process_images('input_images', 'output_images', resize_for_batch, width=800, height=600)
使用OpenCV處理圖像
OpenCV是一個(gè)功能更強(qiáng)大的計(jì)算機(jī)視覺庫,適合更復(fù)雜的圖像處理任務(wù),如圖像識(shí)別、特征提取、目標(biāo)檢測等。
安裝OpenCV
pip install opencv-python
基本操作
import cv2
import numpy as np
# 讀取圖像
img = cv2.imread('example.jpg')
# 顯示圖像信息
print(f"圖像形狀: {img.shape}") # 返回(高度, 寬度, 通道數(shù))
print(f"圖像大小: {img.size}") # 返回像素總數(shù)
print(f"圖像類型: {img.dtype}") # 返回?cái)?shù)據(jù)類型
# 顯示圖像(僅在有GUI環(huán)境時(shí)有效)
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 保存圖像
cv2.imwrite('example_copy.jpg', img)
圖像縮放
import cv2
def resize_image_cv2(input_path, output_path, new_size):
"""調(diào)整圖像大小
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
new_size: 新尺寸,格式為(寬, 高)
"""
try:
# 讀取圖像
img = cv2.imread(input_path)
# 調(diào)整大小
resized_img = cv2.resize(img, new_size)
# 保存調(diào)整后的圖像
cv2.imwrite(output_path, resized_img)
print(f"已將圖像從 {img.shape[1]}x{img.shape[0]} 調(diào)整為 {new_size[0]}x{new_size[1]}")
return True
except Exception as e:
print(f"調(diào)整圖像大小時(shí)出錯(cuò): {e}")
return False
# 使用示例
resize_image_cv2('example.jpg', 'example_resized_cv2.jpg', (800, 600))
圖像裁剪
import cv2
def crop_image_cv2(input_path, output_path, crop_box):
"""裁剪圖像
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
crop_box: 裁剪區(qū)域,格式為(y_start, y_end, x_start, x_end)
"""
try:
# 讀取圖像
img = cv2.imread(input_path)
# 裁剪圖像
y_start, y_end, x_start, x_end = crop_box
cropped_img = img[y_start:y_end, x_start:x_end]
# 保存裁剪后的圖像
cv2.imwrite(output_path, cropped_img)
print(f"已裁剪圖像,裁剪區(qū)域: {crop_box}")
return True
except Exception as e:
print(f"裁剪圖像時(shí)出錯(cuò): {e}")
return False
# 使用示例
crop_image_cv2('example.jpg', 'example_cropped_cv2.jpg', (100, 400, 100, 500))
圖像旋轉(zhuǎn)
import cv2
import numpy as np
def rotate_image_cv2(input_path, output_path, angle):
"""旋轉(zhuǎn)圖像
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
angle: 旋轉(zhuǎn)角度(逆時(shí)針)
"""
try:
# 讀取圖像
img = cv2.imread(input_path)
# 獲取圖像中心點(diǎn)
height, width = img.shape[:2]
center = (width // 2, height // 2)
# 創(chuàng)建旋轉(zhuǎn)矩陣
rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
# 計(jì)算新圖像的邊界
abs_cos = abs(rotation_matrix[0, 0])
abs_sin = abs(rotation_matrix[0, 1])
new_width = int(height * abs_sin + width * abs_cos)
new_height = int(height * abs_cos + width * abs_sin)
# 調(diào)整旋轉(zhuǎn)矩陣
rotation_matrix[0, 2] += new_width / 2 - center[0]
rotation_matrix[1, 2] += new_height / 2 - center[1]
# 執(zhí)行旋轉(zhuǎn)
rotated_img = cv2.warpAffine(img, rotation_matrix, (new_width, new_height))
# 保存旋轉(zhuǎn)后的圖像
cv2.imwrite(output_path, rotated_img)
print(f"已將圖像旋轉(zhuǎn) {angle} 度")
return True
except Exception as e:
print(f"旋轉(zhuǎn)圖像時(shí)出錯(cuò): {e}")
return False
# 使用示例
rotate_image_cv2('example.jpg', 'example_rotated_cv2.jpg', 45) # 旋轉(zhuǎn)45度
添加水印
import cv2
import numpy as np
def add_text_watermark_cv2(input_path, output_path, text, position=None, color=(255, 255, 255), thickness=2, font_scale=1.0):
"""添加文字水印
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
text: 水印文字
position: 水印位置,格式為(x, y),默認(rèn)為None(居中)
color: 水印顏色,格式為(B, G, R),默認(rèn)為白色
thickness: 文字粗細(xì)
font_scale: 字體大小縮放因子
"""
try:
# 讀取圖像
img = cv2.imread(input_path)
# 獲取文本大小
font = cv2.FONT_HERSHEY_SIMPLEX
text_size = cv2.getTextSize(text, font, font_scale, thickness)[0]
# 如果未指定位置,則居中放置
if position is None:
position = ((img.shape[1] - text_size[0]) // 2, (img.shape[0] + text_size[1]) // 2)
# 添加文字水印
cv2.putText(img, text, position, font, font_scale, color, thickness)
# 保存結(jié)果
cv2.imwrite(output_path, img)
print(f"已添加文字水印: '{text}'")
return True
except Exception as e:
print(f"添加水印時(shí)出錯(cuò): {e}")
return False
def add_image_watermark_cv2(input_path, output_path, watermark_path, position=None, alpha=0.3):
"""添加圖像水印
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
watermark_path: 水印圖像路徑
position: 水印位置,格式為(x, y),默認(rèn)為None(右下角)
alpha: 水印透明度,0-1之間
"""
try:
# 讀取圖像和水印
img = cv2.imread(input_path)
watermark = cv2.imread(watermark_path, cv2.IMREAD_UNCHANGED)
# 如果水印有Alpha通道,則分離
if watermark.shape[2] == 4:
# 分離BGR和Alpha通道
bgr = watermark[:, :, 0:3]
alpha_channel = watermark[:, :, 3] / 255.0
alpha_channel = cv2.merge([alpha_channel, alpha_channel, alpha_channel])
else:
bgr = watermark
alpha_channel = np.ones(bgr.shape, dtype=bgr.dtype)
# 調(diào)整水印大?。蛇x,這里設(shè)為原圖的1/4寬度)
watermark_width = img.shape[1] // 4
watermark_height = int(watermark.shape[0] * watermark_width / watermark.shape[1])
bgr = cv2.resize(bgr, (watermark_width, watermark_height))
alpha_channel = cv2.resize(alpha_channel, (watermark_width, watermark_height))
# 如果未指定位置,則放在右下角
if position is None:
position = (img.shape[1] - watermark_width - 10, img.shape[0] - watermark_height - 10)
# 計(jì)算ROI
x, y = position
h, w = bgr.shape[0], bgr.shape[1]
roi = img[y:y+h, x:x+w]
# 應(yīng)用水印
result = (1 - alpha * alpha_channel) * roi + alpha * alpha_channel * bgr
# 將結(jié)果放回原圖
img[y:y+h, x:x+w] = result
# 保存結(jié)果
cv2.imwrite(output_path, img)
print(f"已添加圖像水印")
return True
except Exception as e:
print(f"添加水印時(shí)出錯(cuò): {e}")
return False
# 使用示例
add_text_watermark_cv2('example.jpg', 'example_text_watermark_cv2.jpg', '? 2023 公司名稱')
add_image_watermark_cv2('example.jpg', 'example_image_watermark_cv2.jpg', 'logo.png')
圖像增強(qiáng)和濾鏡
import cv2
import numpy as np
def adjust_brightness_contrast(input_path, output_path, brightness=0, contrast=1.0):
"""調(diào)整亮度和對比度
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
brightness: 亮度調(diào)整值,正值增加亮度,負(fù)值降低亮度
contrast: 對比度調(diào)整因子,大于1增加對比度,小于1降低對比度
"""
try:
# 讀取圖像
img = cv2.imread(input_path)
# 應(yīng)用公式:新像素 = 對比度 * 原像素 + 亮度
adjusted = cv2.convertScaleAbs(img, alpha=contrast, beta=brightness)
# 保存結(jié)果
cv2.imwrite(output_path, adjusted)
print(f"已調(diào)整亮度和對比度")
return True
except Exception as e:
print(f"調(diào)整亮度和對比度時(shí)出錯(cuò): {e}")
return False
def apply_filter_cv2(input_path, output_path, filter_type, kernel_size=5):
"""應(yīng)用濾鏡
Args:
input_path: 輸入圖像路徑
output_path: 輸出圖像路徑
filter_type: 濾鏡類型,如'blur', 'gaussian', 'median', 'bilateral'
kernel_size: 核大小
"""
try:
# 讀取圖像
img = cv2.imread(input_path)
# 應(yīng)用濾鏡
if filter_type == 'blur':
filtered_img = cv2.blur(img, (kernel_size, kernel_size))
elif filter_type == 'gaussian':
filtered_img = cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
elif filter_type == 'median':
filtered_img = cv2.medianBlur(img, kernel_size)
elif filter_type == 'bilateral':
filtered_img = cv2.bilateralFilter(img, kernel_size, 75, 75)
else:
print(f"未知濾鏡類型: {filter_type}")
return False
# 保存結(jié)果
cv2.imwrite(output_path, filtered_img)
print(f"已應(yīng)用 {filter_type} 濾鏡")
return True
except Exception as e:
print(f"應(yīng)用濾鏡時(shí)出錯(cuò): {e}")
return False
# 使用示例
adjust_brightness_contrast('example.jpg', 'example_adjusted_cv2.jpg', brightness=30, contrast=1.2)
apply_filter_cv2('example.jpg', 'example_gaussian_cv2.jpg', 'gaussian')
apply_filter_cv2('example.jpg', 'example_bilateral_cv2.jpg', 'bilateral')
實(shí)際應(yīng)用場景
場景一:產(chǎn)品圖片批量處理
import os
from PIL import Image, ImageEnhance
def process_product_images(input_folder, output_folder, target_size=(800, 800), enhance=True):
"""批量處理產(chǎn)品圖片
Args:
input_folder: 輸入文件夾路徑
output_folder: 輸出文件夾路徑
target_size: 目標(biāo)尺寸
enhance: 是否增強(qiáng)圖像
"""
# 確保輸出文件夾存在
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 獲取所有圖像文件
image_extensions = ('.jpg', '.jpeg', '.png')
image_files = [f for f in os.listdir(input_folder)
if os.path.isfile(os.path.join(input_folder, f))
and f.lower().endswith(image_extensions)]
print(f"找到 {len(image_files)} 個(gè)產(chǎn)品圖片")
# 處理每個(gè)圖像
for image_file in image_files:
input_path = os.path.join(input_folder, image_file)
output_path = os.path.join(output_folder, image_file)
try:
# 打開圖像
img = Image.open(input_path)
# 創(chuàng)建白色背景
background = Image.new('RGB', target_size, (255, 255, 255))
# 調(diào)整圖像大小,保持寬高比
img_ratio = min(target_size[0] / img.width, target_size[1] / img.height)
new_size = (int(img.width * img_ratio), int(img.height * img_ratio))
img = img.resize(new_size, Image.LANCZOS)
# 將圖像居中放置在白色背景上
offset = ((target_size[0] - new_size[0]) // 2, (target_size[1] - new_size[1]) // 2)
background.paste(img, offset)
# 增強(qiáng)圖像
if enhance:
# 增加亮度
enhancer = ImageEnhance.Brightness(background)
background = enhancer.enhance(1.1)
# 增加對比度
enhancer = ImageEnhance.Contrast(background)
background = enhancer.enhance(1.1)
# 增加銳度
enhancer = ImageEnhance.Sharpness(background)
background = enhancer.enhance(1.2)
# 保存處理后的圖像
background.save(output_path, quality=95)
print(f"已處理: {image_file}")
except Exception as e:
print(f"處理 {image_file} 時(shí)出錯(cuò): {e}")
print("產(chǎn)品圖片批量處理完成")
# 使用示例
# process_product_images('product_images', 'processed_products')
場景二:批量添加水印
import os
from PIL import Image, ImageDraw, ImageFont
def batch_add_watermark(input_folder, output_folder, watermark_text, position=None, font_size=30, opacity=0.5):
"""批量添加水印
Args:
input_folder: 輸入文件夾路徑
output_folder: 輸出文件夾路徑
watermark_text: 水印文字
position: 水印位置,格式為(x, y),默認(rèn)為None(右下角)
font_size: 字體大小
opacity: 水印透明度,0-1之間
"""
# 確保輸出文件夾存在
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 獲取所有圖像文件
image_extensions = ('.jpg', '.jpeg', '.png')
image_files = [f for f in os.listdir(input_folder)
if os.path.isfile(os.path.join(input_folder, f))
and f.lower().endswith(image_extensions)]
print(f"找到 {len(image_files)} 個(gè)圖像文件")
# 加載字體
try:
font = ImageFont.truetype("Arial.ttf", font_size)
except IOError:
font = ImageFont.load_default()
# 處理每個(gè)圖像
for image_file in image_files:
input_path = os.path.join(input_folder, image_file)
output_path = os.path.join(output_folder, image_file)
try:
# 打開圖像
img = Image.open(input_path).convert("RGBA")
# 創(chuàng)建透明圖層
txt = Image.new('RGBA', img.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(txt)
# 計(jì)算文本大小
text_width, text_height = draw.textsize(watermark_text, font)
# 如果未指定位置,則放在右下角
if position is None:
position = (img.width - text_width - 20, img.height - text_height - 20)
# 繪制水印文字
draw.text(position, watermark_text, font=font, fill=(255, 255, 255, int(255 * opacity)))
# 合并圖層
watermarked = Image.alpha_composite(img, txt)
# 保存結(jié)果
watermarked.convert('RGB').save(output_path)
print(f"已處理: {image_file}")
except Exception as e:
print(f"處理 {image_file} 時(shí)出錯(cuò): {e}")
print("批量添加水印完成")
# 使用示例
# batch_add_watermark('photos', 'watermarked_photos', '? 2023 公司名稱')
場景三:圖像格式批量轉(zhuǎn)換
import os
from PIL import Image
def batch_convert_format(input_folder, output_folder, target_format='webp', quality=85):
"""批量轉(zhuǎn)換圖像格式
Args:
input_folder: 輸入文件夾路徑
output_folder: 輸出文件夾路徑
target_format: 目標(biāo)格式,如'jpg', 'png', 'webp'等
quality: 圖像質(zhì)量,1-100之間(僅對jpg和webp有效)
"""
# 確保輸出文件夾存在
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 獲取所有圖像文件
image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp')
image_files = [f for f in os.listdir(input_folder)
if os.path.isfile(os.path.join(input_folder, f))
and f.lower().endswith(image_extensions)]
print(f"找到 {len(image_files)} 個(gè)圖像文件")
# 處理每個(gè)圖像
for image_file in image_files:
input_path = os.path.join(input_folder, image_file)
# 獲取文件名(不含擴(kuò)展名)
filename = os.path.splitext(image_file)[0]
output_path = os.path.join(output_folder, f"{filename}.{target_format.lower()}")
try:
# 打開圖像
img = Image.open(input_path)
# 如果圖像有透明通道且目標(biāo)格式是JPG,則添加白色背景
if img.mode == 'RGBA' and target_format.lower() == 'jpg':
background = Image.new('RGB', img.size, (255, 255, 255))
background.paste(img, mask=img.split()[3]) # 使用alpha通道作為mask
img = background
# 保存為目標(biāo)格式
if target_format.lower() in ('jpg', 'jpeg'):
img.convert('RGB').save(output_path, 'JPEG', quality=quality)
elif target_format.lower() == 'webp':
img.save(output_path, 'WEBP', quality=quality)
else:
img.save(output_path, target_format.upper())
print(f"已轉(zhuǎn)換: {image_file} -> {os.path.basename(output_path)}")
except Exception as e:
print(f"轉(zhuǎn)換 {image_file} 時(shí)出錯(cuò): {e}")
print("批量格式轉(zhuǎn)換完成")
# 使用示例
# batch_convert_format('original_images', 'webp_images', 'webp', 85)
通過以上代碼示例和應(yīng)用場景,你可以輕松實(shí)現(xiàn)各種圖像處理自動(dòng)化任務(wù),大大提高工作效率。無論是批量處理產(chǎn)品圖片、添加水印,還是轉(zhuǎn)換圖像格式,Python都能幫你輕松應(yīng)對。
到此這篇關(guān)于Python實(shí)現(xiàn)批量自動(dòng)化處理圖像的完整指南的文章就介紹到這了,更多相關(guān)Python圖像處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python調(diào)用REST API接口的幾種方式匯總
這篇文章主要介紹了Python調(diào)用REST API接口的幾種方式匯總,幫助大家更好的利用python進(jìn)行自動(dòng)化運(yùn)維,感興趣的朋友可以了解下2020-10-10
Python 多線程共享變量的實(shí)現(xiàn)示例
這篇文章主要介紹了Python 多線程共享變量的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
Python+matplotlib實(shí)現(xiàn)堆疊圖的繪制
Matplotlib作為Python的2D繪圖庫,它以各種硬拷貝格式和跨平臺(tái)的交互式環(huán)境生成出版質(zhì)量級別的圖形。本文將利用Matplotlib庫繪制堆疊圖,感興趣的可以了解一下2022-03-03
python 實(shí)現(xiàn)一個(gè)圖形界面的匯率計(jì)算器
這篇文章主要介紹了python 實(shí)現(xiàn)一個(gè)圖形界面的匯率計(jì)算器,幫助大家更好的理解和學(xué)習(xí)如何制作gui程序,感興趣的朋友可以了解下2020-11-11
django 外鍵創(chuàng)建注意事項(xiàng)說明
這篇文章主要介紹了django 外鍵創(chuàng)建注意事項(xiàng)說明,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Python PyCryptodome庫介紹與實(shí)例教程
PyCryptodome提供了豐富的加密功能,可以滿足多種安全需求,本文介紹了幾個(gè)常見的使用場景,包括對稱加密、非對稱加密、哈希函數(shù)和消息認(rèn)證碼,感興趣的朋友跟隨小編一起看看吧2024-07-07
用Python進(jìn)行簡單圖像識(shí)別(驗(yàn)證碼)
這篇文章主要為大家詳細(xì)介紹了用Python進(jìn)行簡單圖像識(shí)別驗(yàn)證碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01

