如何使用pydicom从DICOM文件访问RGB像素阵列?

时间:2017-03-07 13:57:46

标签: python numpy dicom pydicom

我尝试访问具有未知压缩的DICOM文件的 RGB 像素阵列(可能没有)。提取灰度像素阵列完全正常。

然而,使用

import dicom
import numpy as np

data_set = dicom.read_file(path)
pixel_array = data_set.pixel_array
size_of_array = pixel_array.shape

if len(size_of_array ) == 3:     
    chanR = pixel_array[0][0:size_of_array[1], 0:size_of_array[2]]
    chanG = pixel_array[1][0:size_of_array[1], 0:size_of_array[2]]
    chanB = pixel_array[2][0:size_of_array[1], 0:size_of_array[2]]
    output_array = (0.299 ** chanR) + (0.587 ** chanG) + (0.114 ** chanB)

目标是将其转换为通用灰度数组。不幸的是,结果数组output_array不包含正确的像素数据。内容不是虚假缩放,它们在空间上受到干扰。问题在哪里?

3 个答案:

答案 0 :(得分:1)

它不是RGB像素阵列,更好的方法是转换为灰度图像。

获取CT图像的方法是获取CT dicom文件中的pixel_array属性。 CT dicom文件的pixel_array中的元素类型都是uint16。但是python中的许多工具(例如OpenCV,一些AI东西)都不能与该类型兼容。

从CT dicom文件获取pixel_array(CT图像)后,您始终需要将pixel_array转换为灰度图像,以便您可以通过python中的许多图像处理工具来处理该灰度图像

以下代码是将pixel_array转换为灰度图像的有效示例。

import matplotlib.pyplot as plt
import os
import pydicom
import numpy as np 
# Abvoe code is to import dependent libraries of this code

# Read some CT dicom file here by pydicom library
ct_filepath = r"<YOUR_CT_DICOM_FILEPATH>"
ct_dicom = pydicom.read_file(ct_filepath)
img = ct_dicom.pixel_array

# Now, img is pixel_array. it is input of our demo code

# Convert pixel_array (img) to -> gray image (img_2d_scaled)
## Step 1. Convert to float to avoid overflow or underflow losses.
img_2d = img.astype(float)

## Step 2. Rescaling grey scale between 0-255
img_2d_scaled = (np.maximum(img_2d,0) / img_2d.max()) * 255.0

## Step 3. Convert to uint
img_2d_scaled = np.uint8(img_2d_scaled)


# Show information of input and output in above code
## (1) Show information of original CT image 
print(img.dtype)
print(img.shape)
print(img)

## (2) Show information of gray image of it 
print(img_2d_scaled.dtype)
print(img_2d_scaled.shape)
print(img_2d_scaled)

## (3) Show the scaled gray image by matplotlib
plt.imshow(img_2d_scaled, cmap='gray', vmin=0, vmax=255)
plt.show()

以下是我打印出来的结果。

enter image description here

答案 1 :(得分:0)

你现在可能已经解决了这个问题,但我认为pydicom没有正确解释planar configuration

您需要先执行此操作:

img = data_set.pixel_array
img = img.reshape([img.shape[1], img.shape[2], 3])

从此处开始,您的图片将具有[rows cols 3]形状,并且频道已分开

答案 2 :(得分:-1)

正如@Daniel 所说,由于您有 PlanarConfiguration== 1,您必须通过 np.reshape 重新排列列中的颜色,然后转换为灰度,例如使用 OpenCV :

import pydicom as dicom
import numpy as np
import cv2 as cv

data_set = dicom.read_file(path)
pixel_array = data_set.pixel_array
## converting to shape (m,n,3)
pixel_array_rgb = pixel_array.reshape((pixel_array.shape[1], pixel_array.shape[2], 3))
## converting to grayscale
pixel_array_gs = cv.cvtColor(pixel_array_rgb, cv.COLOR_RGB2GRAY)