Şiy*_*dır 5 python arrays rgb numpy dicom
所以我预处理了一些 dicom 图像来输入神经网络,在图像增强步骤中,图像数据生成器需要 4d 输入,而我的数据是 3d (200, 420, 420)
我尝试重塑数组并扩展尺寸,但在这两种情况下,我都无法绘制数组中的各个图像(期望形状为 420, 420 的图像,而我的新图像的形状为 420, 420, 1)
这是我的代码;
我有三个函数可以将 DICOM 图像转换为对比度良好的图像;
这个需要 housefield 单位
def transform_to_hu(medical_image, image):
intercept = medical_image.RescaleIntercept
slope = medical_image.RescaleSlope
hu_image = image * slope + intercept
return hu_image
Run Code Online (Sandbox Code Playgroud)
这设置了窗口图像值;
def window_image(image, window_center, window_width):
img_min = window_center - window_width // 2
img_max = window_center + window_width // 2
window_image = image.copy()
window_image[window_image < img_min] = img_min
window_image[window_image > img_max] = img_max
return window_image
Run Code Online (Sandbox Code Playgroud)
这个函数加载图像:
def load_image(file_path):
medical_image = dicom.read_file(file_path)
image = medical_image.pixel_array
hu_image = transform_to_hu(medical_image, image)
brain_image = window_image(hu_image, 40, 80)
return brain_image
Run Code Online (Sandbox Code Playgroud)
然后我加载我的图像:
files = sorted(glob.glob('F:\CT_Data_Classifier\*.dcm'))
images = np.array([load_image(path) for path in files])
Run Code Online (Sandbox Code Playgroud)
images.shape返回 (200, 512, 512) 并且数据一切都很好,例如我可以绘制第 100 个图像
plt.imshow(images[100])并绘制图像
然后我将数据输入图像数据生成器
train_image_data = ImageDataGenerator(
rescale=1./255,
shear_range=0.,
zoom_range=0.05,
rotation_range=180,
width_shift_range=0.05,
height_shift_range=0.05,
horizontal_flip=True,
vertical_flip=True,
fill_mode='constant',
cval=0
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用以下代码进行绘图时:
plt.figure(figsize=(12, 12))
for X_batch, y_batch in train_image_data.flow(trainX, trainY, batch_size=9):
for i in range(0, 9):
plt.subplot(330 + 1 + i)
plt.imshow(X_batch[i])
plt.show()
break
Run Code Online (Sandbox Code Playgroud)
它返回
(ValueError: ('Input data in "NumpyArrayIterator" should have rank 4. You passed an array with shape', (162, 420, 420)))
我尝试 Expand_dims 和 reshape 在数组末尾添加一个额外的维度来表示通道,但随后它返回
TypeError: Invalid shape (420, 420, 1) for image data
Run Code Online (Sandbox Code Playgroud)
在plt.imshow舞台上
我是一名医生,而不是经验丰富的程序员,所以我非常感谢您的帮助。干杯。
您添加额外的维度来表示通道是正确的。那部分看起来不错。问题出在绘图上。为此,您可以使用:
plt.matshow(x[..., 0]).
Run Code Online (Sandbox Code Playgroud)
其中x是 3D 数组。该语法x[..., 0]意味着取 array 最后一个维度的索引 0 x。省略号 ( ...) 是填写尺寸的简写。对于 3D 数组,等效的调用是x[:, :, 0].