我刚刚开始学习Python 3.7.7。
我正在尝试使用图将NIFTI图像显示为带有float32元素的numpy数组。
这是显示图像的代码:
import os
import SimpleITK as sitk
import numpy as np
import matplotlib.pyplot as plt
import cv2
def plot_grey_images_as_figure(img1, img2, title1, title2):
"""
Show img1 and img2 as a single figure using matplotlib.pylot.
Show img1 and img2 as a single figure using matplotlib.pylot with the titles
title1 for img1 and title2 for img2.
Parameters:
img1 (array-like or PIL image): Image to show first.
img2 (array-like or PIL image): Image to show second.
title1 (string) : Title for image 1.
title2 (string) : Title for image 2.
Returns:
Nothing.
"""
plt.subplot(121), plt.imshow(img1, cmap = 'gray')
plt.title(title1), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(img2, cmap = 'gray')
plt.title(title2), plt.xticks([]), plt.yticks([])
plt.show()
return
这是我在显示图像之前对其进行预处理的方式:
def preprocessing_array(array, rows_standard, cols_standard, debug): # array shape is (48, 240, 240)
image_rows_Dataset = np.shape(array)[1]
image_cols_Dataset = np.shape(array)[2]
num_rows_1 = ((image_rows_Dataset // 2) - (rows_standard // 2)) # 20
num_rows_2 = ((image_rows_Dataset // 2) + (rows_standard // 2)) # 220
num_cols_1 = ((image_cols_Dataset // 2) - (cols_standard // 2)) # 20
num_cols_2 = ((image_cols_Dataset // 2) + (cols_standard // 2)) # 220
array = array[:, num_rows_1:num_rows_2, num_cols_1:num_cols_2]
### ------ New Axis --------------------------------------------------------
# Add a new axis to denote that this is a one channel image.
array = array[..., np.newaxis]
return array # array shape is (48, 200, 200, 1)
要显示图像,我这样做:
# D is a dataset with shape (960, 2, 200, 200, 1) with float32 elements.
print("Shape: ", D[:,0,:][0].shape)
nifti.plot_grey_images_as_figure(D[:,0,:][0][:,-1], D[:,1,:][0][:,-1], "mask", "output")
我得到此输出:
为什么我得到线条而不是正方形?
也许问题是我添加了一个新轴,然后将其删除,因为不允许我绘制形状为(200, 200, 1)
的图像。
图像切片不正确。您的绘图功能应为
base = D[:,0,:]
img1 = base[0][:, :, 0] # Shape of (200, 200)
img2 = base[1][:, :, 0]
nifti.plot_grey_images_as_figure(img1, img2, "mask", "output")
使用numpy.sqeeze()
删除尺寸一的尺寸。问题在于将图像作为非2D数组传递。 Squeezing帮助我们沿axis=2
放置尺寸,使形状从(200, 200, 1)
to (200, 200)
。
import numpy as np
np.queeze(D[:,0,:][0], axis=2).shape
# (200, 200)