📌 目录

  1. scipy.ndimage 模块简介
  2. 图像读取与转换
  3. 图像平滑与滤波
  4. 边缘检测与图像梯度
  5. 图像几何变换(旋转、缩放、平移)
  6. 示例:图像处理完整案例
  7. 出站链接与参考资料

1. scipy.ndimage 模块简介

scipy.ndimage 是 SciPy 中用于多维图像处理的模块,广泛应用于医学图像、遥感图像、生物图像分析等领域。它支持滤波器、形态学操作、插值、标签处理、几何变换等多种功能。


2. 图像读取与转换

SciPy 本身不具备图像读取功能,通常借助 imageioPIL 读取图像,再使用 ndimage 进行处理。

from scipy import ndimage
import imageio.v3 as iio
import matplotlib.pyplot as plt

# 读取灰度图像
image = iio.imread("https://upload.wikimedia.org/wikipedia/commons/thumb/2/24/Lenna.png/256px-Lenna.png", mode='L')

# 显示图像
plt.imshow(image, cmap='gray')
plt.title('原始图像')
plt.axis('off')
plt.show()


3. 图像平滑与滤波

高斯滤波(Gaussian Filter)

smoothed = ndimage.gaussian_filter(image, sigma=2)

plt.imshow(smoothed, cmap='gray')
plt.title('高斯平滑')
plt.axis('off')
plt.show()

均值滤波(Uniform Filter)

uniform = ndimage.uniform_filter(image, size=9)

plt.imshow(uniform, cmap='gray')
plt.title('均值滤波')
plt.axis('off')
plt.show()


4. 边缘检测与图像梯度

Sobel 算子(Sobel Filter)

Sobel 滤波器可用于检测图像的水平和垂直边缘。

sobel_x = ndimage.sobel(image, axis=0)
sobel_y = ndimage.sobel(image, axis=1)
sobel = (sobel_x**2 + sobel_y**2)**0.5

plt.imshow(sobel, cmap='gray')
plt.title('Sobel 边缘检测')
plt.axis('off')
plt.show()

Laplace 算子(Laplacian Filter)

laplace = ndimage.laplace(image)

plt.imshow(laplace, cmap='gray')
plt.title('Laplace 边缘检测')
plt.axis('off')
plt.show()


5. 图像几何变换(旋转、缩放、平移)

图像旋转

rotated = ndimage.rotate(image, 45)

plt.imshow(rotated, cmap='gray')
plt.title('旋转45°')
plt.axis('off')
plt.show()

图像缩放(缩小或放大)

zoomed = ndimage.zoom(image, 1.5)

plt.imshow(zoomed, cmap='gray')
plt.title('放大1.5倍')
plt.axis('off')
plt.show()

图像平移

shifted = ndimage.shift(image, shift=(20, 30))

plt.imshow(shifted, cmap='gray')
plt.title('平移图像')
plt.axis('off')
plt.show()


6. 示例:图像处理完整案例

以下是一个综合示例,演示图像读取、平滑、边缘检测和旋转:

from scipy import ndimage
import imageio.v3 as iio
import matplotlib.pyplot as plt

# 读取图像
image = iio.imread("https://upload.wikimedia.org/wikipedia/commons/thumb/2/24/Lenna.png/256px-Lenna.png", mode='L')

# 高斯平滑
smoothed = ndimage.gaussian_filter(image, sigma=2)

# Sobel 边缘检测
sobel_x = ndimage.sobel(smoothed, axis=0)
sobel_y = ndimage.sobel(smoothed, axis=1)
edges = (sobel_x**2 + sobel_y**2)**0.5

# 旋转图像
rotated = ndimage.rotate(edges, 45)

# 显示结果
plt.figure(figsize=(10, 6))
plt.subplot(1, 3, 1)
plt.imshow(image, cmap='gray')
plt.title('原图')

plt.subplot(1, 3, 2)
plt.imshow(edges, cmap='gray')
plt.title('边缘检测')

plt.subplot(1, 3, 3)
plt.imshow(rotated, cmap='gray')
plt.title('旋转图像')

plt.tight_layout()
plt.show()


🔗 出站链接与参考资料

📘 官方文档

🎓 教程与实战