過濾區域最大值#

在這裡,我們使用形態學重建來建立背景影像,我們可以從原始影像中減去該背景影像以隔離明亮特徵(區域最大值)。

首先,我們嘗試從影像邊緣開始進行膨脹重建。我們將種子影像初始化為影像的最小強度,並將其邊界設定為原始影像中的像素值。這些最大像素將被膨脹以重建背景影像。

import numpy as np
import matplotlib.pyplot as plt

from scipy.ndimage import gaussian_filter
from skimage import data
from skimage import img_as_float
from skimage.morphology import reconstruction

# Convert to float: Important for subtraction later which won't work with uint8
image = img_as_float(data.coins())
image = gaussian_filter(image, 1)

seed = np.copy(image)
seed[1:-1, 1:-1] = image.min()
mask = image

dilated = reconstruction(seed, mask, method='dilation')

減去膨脹影像會留下一張只有硬幣和平坦黑色背景的影像,如下所示。

fig, (ax0, ax1, ax2) = plt.subplots(
    nrows=1, ncols=3, figsize=(8, 2.5), sharex=True, sharey=True
)

ax0.imshow(image, cmap='gray')
ax0.set_title('original image')
ax0.axis('off')

ax1.imshow(dilated, vmin=image.min(), vmax=image.max(), cmap='gray')
ax1.set_title('dilated')
ax1.axis('off')

ax2.imshow(image - dilated, cmap='gray')
ax2.set_title('image - dilated')
ax2.axis('off')

fig.tight_layout()
original image, dilated, image - dilated

儘管特徵(即硬幣)已被明確隔離,但在原始影像中被明亮背景包圍的硬幣在減去的影像中會較暗。我們可以嘗試使用不同的種子影像來更正此問題。

我們可以使用影像本身的特徵來為重建過程提供種子,而不是建立一個邊緣具有最大值的種子影像。在這裡,種子影像為原始影像減去固定值 h

h = 0.4
seed = image - h
dilated = reconstruction(seed, mask, method='dilation')
hdome = image - dilated

為了了解重建過程,我們繪製影像切片(以紅色線條表示)上的遮罩、種子和膨脹影像的強度。

fig, (ax0, ax1, ax2) = plt.subplots(nrows=1, ncols=3, figsize=(8, 2.5))
yslice = 197

ax0.plot(mask[yslice], '0.5', label='mask')
ax0.plot(seed[yslice], 'k', label='seed')
ax0.plot(dilated[yslice], 'r', label='dilated')
ax0.set_ylim(-0.2, 2)
ax0.set_title('image slice')
ax0.set_xticks([])
ax0.legend()

ax1.imshow(dilated, vmin=image.min(), vmax=image.max(), cmap='gray')
ax1.axhline(yslice, color='r', alpha=0.4)
ax1.set_title('dilated')
ax1.axis('off')

ax2.imshow(hdome, cmap='gray')
ax2.axhline(yslice, color='r', alpha=0.4)
ax2.set_title('image - dilated')
ax2.axis('off')

fig.tight_layout()
plt.show()
image slice, dilated, image - dilated

如您在影像切片中所見,每個硬幣在重建影像中都具有不同的基準強度;這是因為我們使用局部強度(偏移 h)作為種子值。因此,減去的影像中的硬幣具有相似的像素強度。最終結果稱為影像的 h-dome,因為這往往會隔離高度為 h 的區域最大值。當您的影像照明不均勻時,此操作特別有用。

腳本的總執行時間: (0 分鐘 0.872 秒)

由 Sphinx-Gallery 產生的圖庫