• 跳至主要導覽
  • 跳至主要內容
  • 跳至主要資訊欄
Office 指南

Office 指南

辦公室工作實用教學

  • Excel
  • Word
  • PowerPoint
  • Windows
  • PowerShell
  • R

Python NumPy 陣列與 VTK 影像轉換教學與範例

介紹如何在 Python 中處理 NumPy 與 VTK 兩種影像格式的互相轉換。

相關文章:
Python 處理 NumPy、SimpleITK 與 ITK 影像互相轉換教學與範例

NumPy 陣列轉為 VTK 影像

以下是在 Python 中將普通的 NumPy 陣列轉為 VTK 影像的範例。

import vtk
import numpy as np

# 建立三維 NumPy 陣列
npArr = np.zeros([75, 75, 75], dtype=np.uint8)
npArr[0:35, 0:35, 0:35] = 50
npArr[25:55, 25:55, 25:55] = 100
npArr[45:74, 45:74, 45:74] = 150

# 建立 vtkImageImport
dataImporter = vtk.vtkImageImport()

# 將 NumPy 陣列轉為 Bytes
arrBytes = npArr.tobytes()

# 透過 vtkImageImport 將 Bytes 轉為 VTK 影像
dataImporter.CopyImportVoidPointer(arrBytes, len(arrBytes))

# 直接使用資料,不複製
#dataImporter.SetImportVoidPointer(arrBytes)

# 設定影像類型為 unsigned char(uint8)
dataImporter.SetDataScalarTypeToUnsignedChar()

# 設定 Scalar Components 個數
dataImporter.SetNumberOfScalarComponents(1)

# 設定影像大小
dataImporter.SetWholeExtent(0, 74, 0, 74, 0, 74)
dataImporter.SetDataExtentToWholeExtent()

# 設定 Voxel Size
dataImporter.SetDataSpacing(1.0, 1.0, 2.0)

# 設定 Origin
dataImporter.SetDataOrigin(0, 350, 0)

# 匯入影像
dataImporter.Update()

# 取得 VTK 影像
vtkImage = dataImporter.GetOutput()

使用 itkwidgets 查看 VTK 影像:

# 使用 itkwidgets 查看 VTK 影像
import itkwidgets
itkwidgets.view(vtkImage)

在 vtk.util.numpy_support 中的 numpy_to_vtk 函數可以很方便的將 NumPy 陣列轉為 VTK 影像,但是只能用於 2D 影像:

from vtk.util.numpy_support import numpy_to_vtk

# 建立 2D 的 NumPy 陣列
npArr2D = np.zeros([75, 75], dtype=np.uint8)

# 轉為 2D 的 VTK 影像
vtkImage2D = numpy_to_vtk(npArr)

VTK 影像轉為 NumPy 陣列

若要將 VTK 影像轉為 NumPy 陣列,可以使用 vtk.util.numpy_support 中的 vtk_to_numpy 函數:

from vtk.util.numpy_support import vtk_to_numpy

# 從 VTK 影像中取出 NumPy 資料
npArr2 = vtk_to_numpy(vtkImage.GetPointData().GetScalars())

# 設定陣列維度
npArr2 = npArr2.reshape(vtkImage.GetDimensions())

參考資料:VTKWithNumpy、ImageImport、vtkplotlib、Kitware

分類:Python 標籤:VTK

主要資訊欄

搜尋

近期文章

  • Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤
  • Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例
  • Linux 網路設定 ip 指令用法教學與範例
  • Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例
  • Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例
  • Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例
  • Linux 以 Cryptsetup 與 LUKS 加密磁碟教學與範例
  • Linux 使用 age 簡潔的加密、解密工具使用教學與範例

推薦網站

  • Udemy 線上教學課程
  • Coursera 線上教學課程

關注本站

  • 電子郵件
  • Facebook

公益

  • 家扶基金會
  • 台灣世界展望會
  • Yahoo 奇摩公益
  • igiving 公益網
  • 兒福聯盟

Copyright © 2021 · Office Guide