And*_*eas 4 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)
Run Code Online (Sandbox Code Playgroud)
目的是将其转换为常见的灰度数组。不幸的是,结果数组output_array不包含正确的像素数据。内容没有错误缩放,它们在空间上受到干扰。问题出在哪里?
获取CT Image的方法是获取CT dicom文件中pixel_array的属性。CT dicom文件中pixel_array的元素类型都是uint16,但是python很多工具,比如OpenCV,一些AI的东西,都不能兼容这个类型。
从CT dicom文件中得到pixel_array(CT Image)后,总是需要将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()
Run Code Online (Sandbox Code Playgroud)
以下是我打印出来的结果。
您现在可能已经解决了这个问题,但我认为 pydicom 无法正确解释平面配置。
您需要首先执行此操作:
img = data_set.pixel_array
img = img.reshape([img.shape[1], img.shape[2], 3])
Run Code Online (Sandbox Code Playgroud)
从这里开始,您的图像将具有形状[rows cols 3],并且通道分开