python的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()

程序輸出結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章