skimage库 图像中值滤波;均值滤波;极大值滤波

使用 view_as_blocks (来源于skimage.util)函数。当我们想要对非重叠图像块执行局部操作时,块视图(view_as_blocks的返回值)非常有用。
我们将 图像 astronaut (来源于skimage.data)切成小方块(4*4)。在每个方块内部,我们计算均值、最大值和中位值,然后用这些值表示这个方块的值。处理后结果被放在一起展示,结果中第一张图像为使用三次样条插值后形成的图像。

import numpy as np
from scipy import ndimage as ndi
from matplotlib import pyplot as plt
import matplotlib.cm as cm

from skimage import data
from skimage import color
from skimage.util import view_as_blocks


# 彩色图像 to 灰度图像
l = color.rgb2gray(data.astronaut())

# 采样块大小
block_shape = (4, 4)

# 将宇航员这张图像转换为矩阵块
view = view_as_blocks(l, block_shape)
# print(l.shape)  # output:(512,512)
# print(view.shape) # output:(128,128,4,4)

# 将view最后两个维度压缩成一个
flatten_view = view.reshape(view.shape[0], view.shape[1], -1)
# print(flatten_view.shape) # output:(128,128,16)

# 使用均值、最大值、中位值采样后形成的图像
mean_view = np.mean(flatten_view, axis=2)
# print(mean_view.shape) # output:(128,128)
max_view = np.max(flatten_view, axis=2)
median_view = np.median(flatten_view, axis=2)

# 展示重新采样后图像
fig, axes = plt.subplots(2, 2, figsize=(8, 8), sharex=True, sharey=True)
# print(axes.shape) # output:(2,2)
# 将数据压缩至一维
ax = axes.ravel()
# print(ax.shape) # output:(4,)

# 三次样条插值放大图像
l_resized = ndi.zoom(l, 2, order=3)
# print(l_resized.shape) # output:(1024,1024)
ax[0].set_title("Original rescaled with\n spline interpolation (order=3)")
ax[0].imshow(l_resized, extent=(0, 128, 128, 0),
             cmap=cm.Greys_r)

ax[1].set_title("Block view with\n local mean pooling")
ax[1].imshow(mean_view, cmap=cm.Greys_r)

ax[2].set_title("Block view with\n local max pooling")
ax[2].imshow(max_view, cmap=cm.Greys_r)

ax[3].set_title("Block view with\n local median pooling")
ax[3].imshow(median_view, cmap=cm.Greys_r)

for a in ax:
    a.set_axis_off()

fig.tight_layout()
plt.show()
程序输出结果

你可能感兴趣的:(skimage库 图像中值滤波;均值滤波;极大值滤波)