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

Office 指南

辦公室工作實用教學

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

DICOM 影像中文標籤與 UTF-8 編碼儲存問題教學與範例

介紹如何在 Python 中使用 pydicom 模組設定 Specific Character Set,讓 DICOM 標籤以 UTF-8 編碼儲存中文字。

載入 DICOM 檔案

這裏我們載入 pydicom 內建的 DICOM 測試檔案作為示範,關於 pydicom 的基本操作說明,可以參考 Python 使用 Pydicom 讀取、編輯 DICOM 影像檔案教學與範例。

from pydicom import dcmread
from pydicom.data import get_testdata_files

# 取得 Pydicom 附帶的 DICOM 測試影像路徑
filename = get_testdata_files('MR_small.dcm')[0]

# 讀取 DICOM 檔案
ds = dcmread(filename)

# 列出所有後設資料(metadata)
print(ds)
[略]
(0010, 0010) Patient's Name                      PN: 'CompressedSamples^MR1'
(0010, 0020) Patient ID                          LO: '4MR1'
(0010, 0030) Patient's Birth Date                DA: ''
(0010, 0040) Patient's Sex                       CS: 'F'
(0010, 1020) Patient's Size                      DS: None
(0010, 1030) Patient's Weight                    DS: "80.0"
[略]

加入中文內容

假設我們想要更改 DICOM 中的 (0010,0010) Patient Name 標籤,寫入病人的中文姓名:

# 更改 (0010,0010) Patient Name 資料,寫入中文字
ds.PatientName = "王曉明"
print(ds.PatientName)
王曉明

由於 DICOM 預設的 ISO 8859 編碼不支援中文字,當 DICOM 檔案中包含中文字時,若以預設的方式儲存,就會出現問題:

# 另存 DICOM 檔案
ds.save_as("chinese.dcm")
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pydicom/charset.py:534: UserWarning: Failed to encode value with encodings: iso8859 - using replacement characters in encoded string
  .format(', '.join(encodings)))

這段警告訊息是說 ISO 8859 編碼不支援中文字,會將不支援的中文字以其他字元替代,等於實際的中文資料無法儲存至 DICOM 檔案中。

設定 Specific Character Set

遇到這個問題,可以將 (0008,0005) Specific Character Set 指定為 ISO_IR 192,採用 UTF-8 編碼:

# 修改 (0008,0005) Specific Character Set,採用 ISO_IR 192(UTF-8)編碼
ds.SpecificCharacterSet = 'ISO_IR 192'

這樣就可以在 DICOM 檔案中正常儲存中文字了:

# 另存 DICOM 檔案
ds.save_as("utf8.dcm")

參考資料

  • Ray’s Blog:DICOM Tag中文编码问题
  • pydicom:Character Encoding and Decoding
  • Source code for pydicom.charset

分類:Python 標籤:DICOM

主要資訊欄

搜尋

近期文章

  • 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