Categories: Python

SimpleITK 使用 MaskImageFilter 與 MaskNegatedImageFilter 套用遮罩影像教學與範例

介紹如何使用 SimpleITK 的 MaskImageFilterMaskNegatedImageFilter 將遮罩套用至影像中,取出原始影像中對應遮罩標示的區域。

MaskImageFilter 套用遮罩

MaskImageFilter 可以將影像套用指定遮罩,將指定遮罩值的區域篩除。

# MaskImageFilter 虛擬碼(pseudocode)
if pixel_from_mask_image != masking_value
  pixel_output_image = pixel_input_image
else
  pixel_output_image = outside_value

以下是 Allen Mouse Brain CCFv3 平均腦與標註影像的範例。

import SimpleITK as sitk
import matplotlib.pyplot as plt

# 讀取平均腦影像檔案
image = sitk.ReadImage("average_template/average_template_25.nrrd")

# 讀取影像分割遮罩檔案
mask = sitk.ReadImage("annotation/ccf_2017/structure_masks/structure_masks_25/structure_477.nrrd")

# 套用遮罩影像
result = sitk.Mask(image, mask, outsideValue=0, maskingValue=0)

# 顯示影像切面
nda = sitk.GetArrayViewFromImage(result)
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
axs[0].imshow(nda[nda.shape[0]//2,:,:], cmap = 'gray')
axs[1].imshow(nda[:,nda.shape[1]//2,:], cmap = 'gray')
axs[2].imshow(nda[:,:,nda.shape[2]//2], cmap = 'gray')
plt.show()
顯示影像切面

使用 itkwidgets 顯示套用遮罩之後的立體影像:

# 顯示立體影像
import itkwidgets
itkwidgets.view(result)
顯示立體影像

MaskNegatedImageFilter 反向套用遮罩

MaskNegatedImageFilter 的作用跟 MaskImageFilter 類似,只不過它是以反向的方式套用遮罩值。

# MaskNegatedImageFilter 虛擬碼(pseudocode)
if pixel_from_mask_image != mask_value
  pixel_output_image = output_value
else
  pixel_output_image = pixel_input_image

以下是 Allen Mouse Brain CCFv3 平均腦與標註影像的範例。

import SimpleITK as sitk
import matplotlib.pyplot as plt

# 讀取平均腦影像檔案
image = sitk.ReadImage("average_template/average_template_25.nrrd")

# 讀取影像分割遮罩檔案
mask = sitk.ReadImage("annotation/ccf_2017/structure_masks/structure_masks_25/structure_477.nrrd")

# 反向套用遮罩影像
result = sitk.MaskNegated(image, sitk.Cast(mask, sitk.sitkUInt16), outsideValue=0, maskingValue=1)

# 顯示影像切面
nda = sitk.GetArrayViewFromImage(result)
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
axs[0].imshow(nda[nda.shape[0]//2,:,:], cmap = 'gray')
axs[1].imshow(nda[:,nda.shape[1]//2,:], cmap = 'gray')
axs[2].imshow(nda[:,:,nda.shape[2]//2], cmap = 'gray')
plt.show()
顯示影像切面
Share
Published by
Office Guide
Tags: ITK

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

10 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

11 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago