scipy.ndimage
是 SciPy 库中的一个模块,专注于多维图像处理和分析。它提供了许多功能,包括图像滤波、变换、标签、测量和插值。ndimage
可以处理任意维度的数组(不仅仅是图像),并提供了高效的操作。
主要功能和函数
以下是 scipy.ndimage
中一些常用功能的介绍:
- 滤波:
-
scipy.ndimage.gaussian_filter
:对图像应用高斯滤波。 -
scipy.ndimage.median_filter
:对图像应用中值滤波。 -
scipy.ndimage.uniform_filter
:对图像应用均值滤波。
示例:
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt
# 创建一个示例图像
image = np.random.rand(100, 100)
# 应用高斯滤波
blurred_image = ndimage.gaussian_filter(image, sigma=2)
# 显示图像
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(blurred_image, cmap='gray')
plt.title('Blurred Image')
plt.axis('off')
plt.show()
- 变换:
-
scipy.ndimage.zoom
:对数组进行缩放。 -
scipy.ndimage.rotate
:对数组进行旋转。 -
scipy.ndimage.shift
:对数组进行平移。
示例:
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
# 创建一个示例图像
image = np.random.rand(100, 100)
# 旋转图像
rotated_image = ndimage.rotate(image, angle=45)
# 显示图像
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(rotated_image, cmap='gray')
plt.title('Rotated Image')
plt.axis('off')
plt.show()
- 标签和测量:
-
scipy.ndimage.label
:为图像中的连通区域分配标签。 -
scipy.ndimage.find_objects
:找到连通区域的切片。 -
scipy.ndimage.measurements
:计算区域的度量,如质心、区域面积等。
示例:
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
# 创建一个二值图像
image = np.random.rand(100, 100) > 0.8
# 标签连通区域
labeled_array, num_features = ndimage.label(image)
# 显示图像
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Binary Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(labeled_array, cmap='nipy_spectral')
plt.title('Labeled Image')
plt.axis('off')
plt.show()
- 插值:
-
scipy.ndimage.map_coordinates
:从数组中进行坐标映射。 -
scipy.ndimage.interpolation
:执行插值操作,例如对多维数据进行插值。
示例:
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
# 创建一个示例图像
image = np.random.rand(100, 100)
# 定义新坐标
coords = np.array([[50, 50], [60, 60]])
# 使用 map_coordinates 进行插值
interpolated_values = ndimage.map_coordinates(image, coords.T)
print('Interpolated Values:', interpolated_values)
主要函数
- 滤波函数:
gaussian_filter(input, sigma, mode='reflect')
median_filter(input, size, mode='reflect')
uniform_filter(input, size, mode='reflect')
- 变换函数:
zoom(input, zoom, order=3, mode='reflect')
rotate(input, angle, axes=(0, 1), reshape=True, order=3, mode='reflect')
shift(input, shift, order=3, mode='reflect')
- 标签和测量函数:
label(input, structure=None, output=None)
find_objects(input)
center_of_mass(input, labels=None, index=None)
- 插值函数:
map_coordinates(input, coordinates, order=3, mode='reflect')
总结
scipy.ndimage
是一个功能强大的模块,适用于各种多维数组的处理任务。它提供了广泛的工具,用于图像和信号处理,包括滤波、变换、标签和测量等操作,使得处理和分析多维数据变得更加方便和高效。