Python 图像处理技巧指南
一、基础操作:图像读写与格式处理
1. 图像读取与保存(Pillow):支持主流格式(JPG/PNG/BMP等),读取后返回 Image 对象,保存时自动适配格式。
python
from PIL import Image
# 读取图像
img = Image.open("input.jpg")
# 保存为其他格式
img.save("output.png") # 自动转换格式
2. 图像读取与通道转换(OpenCV):默认读取为 BGR 通道(与Pillow的RGB相反),需手动转换以匹配视觉习惯。
python
import cv2
# 读取图像(BGR格式)
img_bgr = cv2.imread("input.jpg")
# 转换为RGB格式
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
# 保存图像
cv2.imwrite("output.jpg", img_bgr) # 需传入BGR格式
二、核心编辑:尺寸、裁剪与旋转
- 调整尺寸:Pillow用 resize() ,OpenCV用 cv2.resize() ,需指定目标尺寸(宽×高)。
python
# Pillow
img_resized = img.resize((800, 600)) # (width, height)
# OpenCV
img_resized = cv2.resize(img_bgr, (800, 600)) # (width, height)
- 裁剪图像:Pillow通过坐标(左,上,右,下)裁剪,OpenCV用数组切片(行×列,对应高×宽)。
python
# Pillow:裁剪左上角(100,100)到右下角(500,400)的区域
img_cropped = img.crop((100, 100, 500, 400))
# OpenCV:裁剪同区域(行:100-400,列:100-500)
img_cropped = img_bgr[100:400, 100:500]
- 旋转图像:Pillow用 rotate() (角度为正逆时针),OpenCV需通过旋转矩阵实现。
python
# Pillow:逆时针旋转90度
img_rotated = img.rotate(90)
# OpenCV:逆时针旋转90度(更高效)
img_rotated = cv2.rotate(img_bgr, cv2.ROTATE_90_COUNTERCLOCKWISE)
三、像素级处理:色彩与对比度
1. 转为灰度图:移除色彩信息,仅保留亮度通道,是后续分析的基础。
python
# Pillow
img_gray = img.convert("L") # "L"代表灰度模式
# OpenCV
img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
2. 调整亮度与对比度:Pillow用 ImageEnhance ,OpenCV通过像素线性变换( alpha×像素 + beta ,alpha控制对比度,beta控制亮度)。
python
# Pillow
from PIL import ImageEnhance
enhancer = ImageEnhance.Brightness(img)
img_bright = enhancer.enhance(1.5) # 1.5倍亮度(<1变暗,>1变亮)
# OpenCV:对比度1.2,亮度+30
img_adjusted = cv2.convertScaleAbs(img_bgr, alpha=1.2, beta=30)
四、高级技巧:滤镜与边缘检测
- 添加滤镜(Pillow):内置模糊、锐化等滤镜,通过 ImageFilter 调用。
python
from PIL import ImageFilter
# 高斯模糊(半径越大越模糊)
img_blur = img.filter(ImageFilter.GaussianBlur(radius=5))
# 锐化
img_sharp = img.filter(ImageFilter.SHARPEN)
- 边缘检测(OpenCV):用 Canny() 函数,需指定高低阈值(阈值越低检测边缘越细)。
python
# 灰度图是边缘检测的前提
img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
# Canny边缘检测
edges = cv2.Canny(img_gray, threshold1=50, threshold2=150)
五、批量处理图像
借助 os 库遍历文件夹,批量执行上述操作(以“批量调整尺寸”为例):
python
import os
from PIL import Image
input_dir = "images/" # 输入文件夹
output_dir = "resized_images/" # 输出文件夹
os.makedirs(output_dir, exist_ok=True) # 确保输出文件夹存在
# 遍历所有图像文件
for filename in os.listdir(input_dir):
if filename.endswith((".jpg", ".png", ".jpeg")):
img_path = os.path.join(input_dir, filename)
img = Image.open(img_path)
# 批量调整为600×400
img_resized = img.resize((600, 400))
# 保存到输出文件夹
img_resized.save(os.path.join(output_dir, filename))