Python生态下的绘图、图形处理库,简直不要太多;从基础的Pillow到专业的OpenCV,再到深度学习(后文简称DL)领域的TensorFlow和PyTorch,形成完整的图像处理和计算机视觉工具链。
| 库名称 | 主要用途 | 特点优势 | 安装命令 | 适用场景 |
|---|---|---|---|---|
| OpenCV | 计算机视觉、图像处理 | 功能全面、性能高、支持实时处理、跨平台 | pip install opencv-python |
实时视频处理、人脸识别、目标检测、图像分析 |
| Pillow(PIL) | 基础图像处理 | 简单易用、支持多种格式、轻量级 | pip install Pillow |
图像格式转换、基本编辑、缩略图生成、简单滤镜 |
scikit-image |
科学图像处理 | 基于NumPy、算法丰富、文档完善 | pip install scikit-image |
医学图像、科研图像、图像分割、特征提取 |
| Mahotas | 高效图像处理 | 多线程支持、速度快、专注形态学操作 | pip install mahotas |
二值图像处理、形态学分析、快速算法实现 |
| imageio | 图像读写 | 简单易用、支持多种格式、轻量级 | pip install imageio |
快速读取/保存图像、视频帧提取 |
| Matplotlib | 图像可视化 | 强大的绘图功能、集成显示 | pip install matplotlib |
图像显示、直方图绘制、结果可视化 |
| TensorFlow Image | DL图像处理 | GPU加速、与TensorFlow生态集成 | pip install tensorflow |
DL训练、图像分类、目标检测 |
| PyTorch Vision | DL图像处理 | 动态计算图、研究友好、GPU加速 | pip install torch torchvision |
DL研究、计算机视觉任务 |
| Kornia | 可微分计算机视觉 | 基于PyTorch、支持自动求导、GPU加速 | pip install kornia |
DL+传统CV结合、可微分图像处理 |
| SimpleITK | 医学图像处理 | 专业医学图像处理、3D图像支持 | pip install SimpleITK |
医学影像分析、3D图像处理 |
| Pydicom | DICOM图像处理 | 专门处理DICOM格式、医学图像标准 | pip install pydicom |
医疗影像处理、DICOM文件读取 |
| scikit-learn | 机器学习图像处理 | 图像特征提取、分类聚类 | pip install scikit-learn |
图像分类、特征工程、ML |
| imgaug | 图像增强 | 专门的数据增强库、支持多种变换 | pip install imgaug |
数据增强、训练集扩充 |
| albumentations | 快速图像增强 | 性能高、支持多种任务、专门优化 | pip install albumentations |
实时数据增强、DL训练 |
| PILlow-SIMD | 高性能图像处理 | Pillow的SIMD加速版本 | pip install pillow-simd |
高性能图像处理、批量处理 |
| rawpy | RAW图像处理 | 专门处理相机RAW格式 | pip install rawpy |
摄影后期、RAW格式处理 |
| PILlow-WebP | WebP格式支持 | 增强的WebP格式支持 | pip install pillow-webp |
WebP格式转换、网页图像优化 |
OpenCV
Open Source Computer Vision Library缩写,官网,开源(GitHub,87.1K Star,56.6K Fork),官方文档。
核心功能:
- 图像处理:滤波、边缘检测、形态学操作、色彩空间转换
- 特征检测:SIFT、SURF、ORB、HOG等
- 目标检测:Haar级联、HOG+SVM、深度学习模型
- 机器学习:SVM、KNN、决策树等算法
- 视频分析:运动检测、光流、背景减除
示例代码:
py
import cv2
import numpy as np
# 读取图像(BGR格式)
img = cv2.imread('image.jpg')
# 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray, 100, 200)
# 人脸检测
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
# 显示图像
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Scikit-Image
核心功能:
- 图像分割算法
- 特征提取
- 几何变换
- 颜色空间操作
- 滤波和恢复
- 形态学操作
示例:
py
from skimage import io, filters, segmentation, color
import matplotlib.pyplot as plt
# 读取图像
image = io.imread('image.jpg')
# 边缘检测
edges = filters.sobel(image)
# 图像分割
segments = segmentation.slic(image, n_segments=100, compactness=10)
# 显示结果
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
axes[0].imshow(image)
axes[1].imshow(edges)
axes[2].imshow(color.label2rgb(segments, image, kind='avg'))
plt.show()
Pillow
Python Imaging Library缩写,官方文档
核心功能:
- 图像打开、保存、格式转换
- 图像裁剪、旋转、缩放、翻转
- 颜色调整、滤镜应用
- 文字和图形绘制
- 图像增强(亮度、对比度、锐度)
py
from PIL import Image, ImageFilter, ImageDraw, ImageFont
# 打开图像
img = Image.open('image.jpg')
# 调整大小
img_resized = img.resize((800, 600))
# 应用滤镜
img_blur = img.filter(ImageFilter.BLUR)
# 添加文字
draw = ImageDraw.Draw(img)
font = ImageFont.truetype('arial.ttf', 36)
draw.text((10, 10), "Hello", fill=(255, 0, 0), font=font)
# 保存
img.save('output.jpg')
Matplotlib
TensorFlow & Keras
简单示例:
py
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# 数据增强
datagen = ImageDataGenerator(
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
)
# 图像分类模型
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(224,224,3)),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
PyTorch & torchvision
简单示例:
py
import torch
import torchvision
import torchvision.transforms as transforms
# 图像变换
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
# 加载数据集
dataset = torchvision.datasets.ImageFolder(root='data/', transform=transform)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True)
Mahotas
基于NumPy,专注于高效算法,提供大量经过优化的图像处理、特征提取和形态学操作函数,常用于生物医学图像分析领域。
核心功能:
- 快速的图像处理操作
- 形态学操作(腐蚀、膨胀、开闭运算)
- 特征提取(纹理、形状)
- 图像分割
- 多线程支持
安装:pip install mahotas
py
import mahotas as mh
import numpy as np
import matplotlib.pyplot as plt
image = mh.imread('sample_cell.jpg')
print(f'图像数组形状: {image.shape}')
print(f'数据类型: {image.dtype}')
print(f'像素值范围: [{image.min()}, {image.max()}]')
image = mh.imread('image.jpg', as_grey=True)
# Otsu阈值分割
thresh = mh.thresholding.otsu(image)
# 二值化
binary = image > thresh
# 距离变换
dist = mh.distance(binary)
# 标记连通区域
labeled, n = mh.label(binary)
mahotas.imread方法读取图片为NumPy数组,可与其他库(如matplotlib)配合显示。
形态学操作是分析细胞、组织等形状的基石。Mahotas提供一套完整的形态学函数,如腐蚀、膨胀、开闭运算等,能有效处理二值图像,分离或连接目标区域。
py
binary_image = mh.imread('cell_binary.png', as_grey=True) > 128
# 执行腐蚀操作,缩小亮区域
eroded = mh.erode(binary_image)
# 执行膨胀操作,扩大亮区域
dilated = mh.dilate(binary_image)
print(f'原图前景像素数: {binary_image.sum()}')
print(f'腐蚀后前景像素数: {eroded.sum()}')
print(f'膨胀后前景像素数: {dilated.sum()}')
从图像中提取有意义的数值特征(如纹理、形状)是分类和识别的关键。
Mahotas的features子模块提供丰富的特征提取器,如Haralick纹理特征,只需一行代码就能计算。
py
from mahotas.features import haralick, lbp
# 计算灰度图像的Haralick纹理特征,假设image_gray是灰度图
texture_features = haralick(image_gray)
# 计算局部二值模式(LBP)特征
lbp_features = lbp(image_gray, radius=3, points=12)
print(f'Haralick特征矩阵形状: {texture_features.shape}')
print(f'LBP特征向量长度: {lbp_features.shape[0]}')
print(f'第一个Haralick特征(能量): {texture_features[0, 0]:.4f}')
包含基础的图像滤波和自动阈值分割算法,gaussian_filter可用于平滑去噪,而otsu方法可自动计算一个最佳阈值将前景与背景分离。
py
from mahotas.colors import rgb2grey
from mahotas import gaussian_filter, otsu
# 将彩色图转为灰度图
gray_image = rgb2grey(image)
# 应用高斯滤波平滑图像
smoothed = gaussian_filter(gray_image, sigma=2.0)
# 使用Otsu方法自动计算最佳阈值
thresh_value = otsu(smoothed)
binary_otsu = smoothed > thresh_value
print(f'Otsu自动计算的阈值: {thresh_value:.2f}')
print(f'分割后前景比例: {binary_otsu.mean():.2%}')
与OpenCV相比,Mahotas更轻量、专注算法实现,尤其在纹理分析和形态学上功能集中。
与scikit-image相比,部分算法(如某些特征提取)执行效率更高。其不足在于社区规模、通用教程和深度学习集成度上不及前两者。
建议:在生物医学图像分析、需要高效传统图像算法(尤其是纹理和形态学)的研究或项目中,Mahotas是极具竞争力的选择。
SimplelTK
Plotnine
官网,官方文档,基于R语言经典的ggplot2理念,为Python带来优雅且直观的图层式绘图系统。
安装:pip install plotnine
Plotnine通过叠加图层构建图表,支持图层灵活组合,可添加趋势线并应用主题;分面功能可创建多子图对比分析。
py
import pandas as pd
from plotnine import *
df = pd.DataFrame({
'category': ['A', 'B', 'C'] * 10,
'value': [5, 8, 3, 7, 2, 6] * 5,
'group': ['X', 'Y'] * 15
})
base_plot = (ggplot(df, aes(x='value', y='category', color='group'))
+ geom_point(size=3)
+ labs(title='基础散点图示例'))
print(base_plot)
enhanced_plot = (ggplot(df, aes(x='value', y='category', color='group'))
+ geom_point(size=3)
+ geom_smooth(method='lm', se=True)
+ theme_minimal()
+ labs(title='带趋势线的散点图'))
print(enhanced_plot)
facet_plot = (ggplot(df, aes(x='category', y='value', fill='group'))
+ geom_bar(stat='identity', position='dodge')
+ facet_wrap('~group')
+ theme_bw()
+ labs(title='分组分面柱状图'))
print(facet_plot)
相比Matplotlib,Plotnine语法直观,图形精美。但学习曲线略陡,动态交互不如Plotly。
Plotly
fastplotlib
基于WGPU、支持GPU极速渲染的交互式科学图形库。GitHub
在pygfx渲染引擎之上抽象而成,Pygf的底层是WGPU,一个跨平台图形API。通过WGPU支持三个OS对应的图像系统库Vulkan(Linux)、Metal(Mac)和DX12(Windows),这些库比OpenGL可更好地支持GPU硬件。
绘制正弦波:
py
import fastplotlib as fpl
import numpy as np
xs = np.linspace(-10, 10, 100)
ys = np.sin(xs)
data = np.dstack([xs, ys])[0]
figure = fpl.Figure()
sine_wave = figure[0, 0].add_line(data=data, thickness=10)
figure.show()
# 对figure的不同特征(颜色图、颜色、数据等)执行各种动态操作
sine_wave.colors[::3] = "red"
事件系统
指定事件非常简单,只需定义想要处理的事件,然后将处理程序添加到事件对应的相应图形或绘图中即可。优点:不需要用户学习新的、复杂的、特定于库的API功能(仅需知道如何定义函数)。
py
import fastplotlib as fpl
import numpy as np
def make_circle(center, radius: float, n_points: int = 75) -> np.ndarray:
theta = np.linspace(0, 2 * np.pi, n_points)
xs = radius * np.sin(theta)
ys = radius * np.cos(theta)
return np.column_stack([xs, ys]) + center
circles = list()
for x in range(0, 50, 10):
circles.append(make_circle(center=(x, 0), radius=4, n_points=100))
fig = fpl.Figure()
circles_graphic = fig[0,0].add_line_collection(data=circles, cmap="tab10", thickness=10)
fig.show()
@fig.renderer.add_event_handler("click")
def click_event(ev):
circles_graphic.cmap = "tab10"
xy = fig[0, 0].map_screen_to_world(ev)[:-1]
nearest = fpl.utils.get_nearest_graphics(xy, circles_graphic)[0]
nearest.colors = "w"
Matplot
Kornia
https://github.com/kornia/kornia
py
import kornia
import torch
# 创建可微分的图像处理操作
image = torch.randn(1, 3, 256, 256) # 批量大小, 通道, 高, 宽
# 可微分的图像变换
transformed = kornia.geometry.transform.rotate(image, angle=45.0)
# 可微分的特征检测
keypoints = kornia.feature.harris_response(image)
最后
上面只是简单罗列汇总介绍十几款库,如何选择呢?
| 需求场景 | 推荐库 | 理由 |
|---|---|---|
| 简单的图像格式转换 | Pillow、imageio | 简单易用,支持格式多 |
| 基础图像处理(裁剪、旋转) | Pillow | API友好,功能全面 |
| 计算机视觉项目 | OpenCV | 算法丰富,性能优秀 |
| 科学研究和分析 | scikit-image | 算法可靠,与SciPy生态集成 |
| 需要快速处理大型图像 | Mahotas | 多线程支持,速度快 |
| 深度学习和神经网络 | TensorFlow/PyTorch | 深度学习框架完整 |
| 图像显示和可视化 | Matplotlib | 绘图功能强大 |
| 可微分图像处理 | Kornia | 与PyTorch无缝集成 |
完整的图像处理流程:
py
# 1. 使用Pillow进行基础处理
from PIL import Image, ImageFilter
img_pil = Image.open('input.jpg')
img_pil = img_pil.resize((800, 600)).rotate(45)
# 2. 使用OpenCV进行计算机视觉处理
import cv2
import numpy as np
img_cv = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR)
gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)
# 3. 使用scikit-image进行特征提取
from skimage import feature
corners = feature.corner_harris(gray)
# 4. 使用Matplotlib进行可视化
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
axes[0,0].imshow(img_pil)
axes[0,1].imshow(gray, cmap='gray')
axes[1,0].imshow(edges, cmap='gray')
axes[1,1].imshow(corners, cmap='hot')
plt.show()
Python图像处理生态系统层次分明、功能互补:
- 基础层:Pillow提供最基础的图像操作能力
- 专业层:OpenCV和scikit-image提供专业的计算机视觉算法
- 性能层:Mahotas等库在特定场景提供极致性能
- 智能层:TensorFlow、PyTorch等提供深度学习能力
可视化层:Matplotlib提供丰富的可视化功能
选择建议:
- 对于大多数日常需求,Pillow+OpenCV组合足够
- 对于科研和数据分析,scikit-image+Matplotlib更合适
- 对于深度学习和AI应用,TensorFlow/PyTorch是必须
- 对于性能敏感场景,可以考虑Mahotas或原生C++扩展
这些库共同构成了Python在图像处理和计算机视觉领域的强大生态,使得从简单的图像处理到复杂的计算机视觉应用都能找到合适的工具。