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

程序輸出結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM