如何使用pydicom从DICOM文件访问RGB像素数组?

2024-10-04 03:23:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用未知压缩(可能没有)访问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没有包含正确的像素数据。内容不是假标度,而是受到空间干扰。问题在哪里?在


Tags: ofimportoutputdatasize像素数组array
2条回答

您现在可能已经解决了这个问题,但我认为pydicom不能正确地解释planar configuration。在

您需要先执行以下操作:

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

从这里开始,您的图像将具有[rows cols 3]的形状,通道分开

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

获取CT图像的方法是在CT-dicom文件中获取像素阵列的属性。 CT-dicom文件像素数组中的元素类型都是uint16,但是python中的很多工具,比如OpenCV,一些人工智能的东西,都不能与之兼容。在

从CT-dicom文件中获取pixel_array(CT Image)后,需要将pixel_数组转换成灰度图像,这样您就可以通过python中的大量图像处理工具对该灰度图像进行处理。在

下面的代码是一个将pixel_数组转换为灰色图像的工作示例。

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

相关问题 更多 >