📌 目录

  1. scipy.ndimage 模块简介
  2. 图像读取与显示
  3. 图像的几何变换
  4. 图像滤波器应用
  5. 图像平滑与去噪
  6. 边缘检测
  7. 二值化与形态学操作
  8. 示例:图像模糊与边缘提取
  9. 出站链接与参考资料

1. scipy.ndimage 模块简介

scipy.ndimage 是 SciPy 中用于多维图像处理的子模块,提供了丰富的函数来处理 N 维数组,尤其适合图像处理任务,如:

  • 卷积
  • 插值
  • 变换(旋转、缩放)
  • 边缘检测
  • 二值形态学操作(膨胀、腐蚀)

2. 图像读取与显示

虽然 scipy.ndimage 不自带读取图像的函数,通常结合 imageioPillow 使用:

import imageio.v2 as imageio
import matplotlib.pyplot as plt

image = imageio.imread('image.jpg', pilmode='L')  # 读入灰度图

plt.imshow(image, cmap='gray')
plt.title("原图像")
plt.axis('off')
plt.show()


3. 图像的几何变换

旋转

from scipy import ndimage

rotated = ndimage.rotate(image, angle=45)
plt.imshow(rotated, cmap='gray')

缩放

zoomed = ndimage.zoom(image, zoom=1.5)


4. 图像滤波器应用

高斯滤波

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

均值滤波(Uniform Filter)

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


5. 图像平滑与去噪

  • 高斯滤波适合去除高斯噪声。
  • 中值滤波适合去除椒盐噪声。
median_filtered = ndimage.median_filter(image, size=3)


6. 边缘检测

Sobel 边缘检测

sobel_x = ndimage.sobel(image, axis=0)
sobel_y = ndimage.sobel(image, axis=1)
edge = np.hypot(sobel_x, sobel_y)

plt.imshow(edge, cmap='gray')

Laplace 滤波器

laplace = ndimage.laplace(image)


7. 二值化与形态学操作

阈值二值化

binary = image > 128

膨胀与腐蚀

dilated = ndimage.binary_dilation(binary)
eroded = ndimage.binary_erosion(binary)


8. 示例:图像模糊与边缘提取

from scipy import ndimage
import matplotlib.pyplot as plt
import imageio.v2 as imageio

img = imageio.imread("image.jpg", pilmode="L")

# 高斯模糊
blur = ndimage.gaussian_filter(img, sigma=3)

# Sobel 边缘
sobel_x = ndimage.sobel(blur, axis=0)
sobel_y = ndimage.sobel(blur, axis=1)
edge = np.hypot(sobel_x, sobel_y)

plt.subplot(1, 3, 1)
plt.title("原图")
plt.imshow(img, cmap='gray')

plt.subplot(1, 3, 2)
plt.title("模糊")
plt.imshow(blur, cmap='gray')

plt.subplot(1, 3, 3)
plt.title("边缘")
plt.imshow(edge, cmap='gray')
plt.show()


🔗 出站链接与参考资料

📘 官方文档

📚 实用资源