Python

Python 使用 ITK ImageFileWriter 串流分批寫入大型檔案教學與範例

介紹如何在 Python 中使用 ITK 的 ImageFileWriter 本身的串流功能,分批處理大型檔案。

在使用 ITK 進行各種處理流程時,除了使用 StreamingImageFilter 分割資料建立串流之外,亦可在使用 ImageFileWriter 寫入檔案的時候,以 SetNumberOfStreamDivisions 設定串流分割參數,讓整條管線都以串流的方式處理,以下是一個轉換影像類型的範例:

import itk

# 設定分割數量
numberOfSplits = 4

# 影像維度
Dimension = 3

# 輸入影像類型
InputPixelType = itk.US
InputImageType = itk.Image[InputPixelType, Dimension]

# 輸出影像類型
OutputPixelType = itk.UC
OutputImageType = itk.Image[OutputPixelType, Dimension]

# 讀取 MHA 影像檔案
inputImageFilename = "input.mha"
outputImageFilename = "output.mha"

# 建立影像 Reader
reader = itk.ImageFileReader[InputImageType].New(FileName=inputImageFilename)

# 建立 PipelineMonitorImageFilter 查看 Streaming 每次處理的範圍
monitorFilter = itk.PipelineMonitorImageFilter[InputImageType].New()
monitorFilter.SetInput(reader.GetOutput())

# 影像資料轉換
rescaler = itk.RescaleIntensityImageFilter[InputImageType, InputImageType].New()
rescaler.SetInput(monitorFilter.GetOutput())
rescaler.SetOutputMinimum(0)
outputPixelTypeMaximum = itk.NumericTraits[OutputPixelType].max()
rescaler.SetOutputMaximum(outputPixelTypeMaximum)

# 影像轉型
castImageFilter = itk.CastImageFilter[InputImageType, OutputImageType].New()
castImageFilter.SetInput(rescaler.GetOutput())

# 寫入影像檔案
writer = itk.ImageFileWriter[OutputImageType].New()
writer.SetFileName(outputImageFilename)
writer.SetInput(castImageFilter.GetOutput())
writer.SetNumberOfStreamDivisions(numberOfSplits)

# 實際執行
writer.Update()

# 輸出 Streaming 的分批 Region 資訊
updatedRequestedRegions = monitorFilter.GetUpdatedRequestedRegions()
print("Updated RequestedRegion's:")
for r in range(len(updatedRequestedRegions)):
    print('  ' + str(updatedRequestedRegions[r]))
Updated RequestedRegion's:
  itkImageRegion3([0, 0, 0], [249, 278, 106])
  itkImageRegion3([0, 0, 106], [249, 278, 106])
  itkImageRegion3([0, 0, 212], [249, 278, 106])
  itkImageRegion3([0, 0, 318], [249, 278, 106])
Share
Published by
Office Guide
Tags: ITK

Recent Posts

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

本篇介紹如何在 Python ...

9 個月 ago

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

本篇介紹如何在 Ubuntu ...

9 個月 ago

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

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

9 個月 ago

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

本篇介紹如何在 Windows...

10 個月 ago

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

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

10 個月 ago

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

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

10 個月 ago