尝试输入 RGB fMRI DICOM 图像,修改它,并使用 pydicom 将其保存为 Python 中的灰度 dicom 图像

Trying to input a RGB fMRI DICOM image, modify it, and save it as a grayscale dicom image in Python using pydicom

我正在尝试将 RGB fMRI 扫描作为输入并输出相同的扫描,但在灰度中,颜色部分基本上“燃烧”成白色。

每当我尝试修改任何数据元素,例如光度解释和每像素样本,并使用 save_as 编写新的 dicom 文件时,我无法使用 dicom 打开该 dicom 扫描查看器给我的错误是它不是 dicom 图像。

我的代码如下。

感谢您的帮助。提前致谢。

import pydicom
from pydicom import dcmread
import numpy as np

#function to turn RGB array to grayscale array
#uses dot product of matrices
def rgb2gray(rgb):
   fil = [0.299, 0.587, 0.144]
   return np.dot(rgb, fil)

ds = pydicom.dcmread("dicom file")

arr = ds.pixel_array
gray_arr = rgb2gray(arr)
#gray_arr = ds.pixel_array[:,:,0]

#Have to change meta tag information when working with dicom images
ds.PhotometricInterpretation = "MONOCRHOME2"
ds.SamplesPerPixel = 1
ds.BitsAllocated = 16
ds.BitsStored = 16
ds.HighBit = 15
del ds.PlanarConfiguration
ds.is_little_endian = True
ds.fix_meta_info()


ds.PixelData = gray_arr.tobytes()
ds.save_as('fMRI.dcm', write_like_original=False)

主要问题是您的数组类型错误 - 它是浮点而不是字节,因此保存到像素数据的是浮点值的字节表示形式(每个 4 个字节)。此外,您将 BitsAllocated 设置为 16,这意味着您期望每个像素 2 个字节,但在您的计算中您只有一个字节范围,例如每个像素只需要 8 位。

最后,您在 PhotometricInterpretation 中有错字(“MONOCRHOME2”而不是“MONOCHROME2”)。 这是一个可能的解决方案,将浮点数组转换为字节数组:

from pydicom import dcmread
from pydicom.uid import generate_uid
import numpy as np

def rgb2gray(rgb):
   fil = [0.299, 0.587, 0.144]
   return np.dot(rgb, fil)

ds = pydicom.dcmread("dicom file")

arr = ds.pixel_array
gray_arr = rgb2gray(arr).round().astype(np.uint8)

ds.PhotometricInterpretation = "MONOCHROME2"
ds.SamplesPerPixel = 1
ds.BitsAllocated = 8
ds.BitsStored = 8
ds.HighBit = 7
ds.PixelRepresenation = 0
ds.SOPInstanceUID = uid.generate_uid()
del ds.PlanarConfiguration
ds.is_little_endian = True
ds.fix_meta_info()


ds.PixelData = gray_arr.tobytes()
ds.save_as('fMRI.dcm', write_like_original=False)

一些注意事项:

  • 这仅在您具有未压缩的传输语法时有效,否则您还必须调整传输语法
  • 我添加了 PixelRepresentation 以表明这些是无符号值
  • 我还添加了一个新的 SOPInstanceUID,否则原始图像将被 PACS 查看器中的派生图像覆盖
  • 为了与 DICOM 保持一致(例如,如果您想将数据发送到 PACS),您可能需要适应更多标签,例如 ImageType