python - 绘制形状为 (200, 200) 的 Numpy 数组显示垂直线而不是正方形
问题描述
我刚刚开始学习 Python 3.7.7。
我正在尝试使用 plot 将 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")
我得到这个输出:
为什么我得到的是线条而不是正方形?
也许问题是我添加了一个新轴,然后我将其删除,因为不允许我绘制带有 shape 的图像(200, 200, 1)
。
解决方案
用于numpy.sqeeze()
删除尺寸一维。问题在于将图像作为非二维数组传递。挤压有助于我们降低尺寸axis=2
,使形状从(200, 200, 1)
到 (200, 200)
。
import numpy as np
np.queeze(D[:,0,:][0], axis=2).shape
# (200, 200)
建议改进
# Choose the index i (axis=0)
i = 0 # Values (0, 1, ..., 960)
# Extract mask and output images
img1 = D[i,0,:,:,0] # shape (200, 200) --> mask
img2 = D[i,1,:,:,0] # shape (200, 200) --> output
nifti.plot_grey_images_as_figure(img1, img2, "mask", "output")
参考
推荐阅读
- regex - 从单元格中提取唯一文本字符/表情符号列表
- d3.js - d3.json() 不会执行。不断收到错误:400
- sql - MS Access - 来自同一个表的多个计数
- ios - UIScrollView Subviews being misplaced when scaled down and Subviews not showing up when rounded
- pandas - 将函数内的循环值写入 Pandas 数据帧
- javascript - 我们是否能够为 CSS 语句组合 JavaScript 等效对象?
- c++ - 使用宏反转 4 个字节的字节顺序而不使用 Zeros C++
- javascript - 我该如何解决?找不到包含文件
- java - 如何在 Apache Cloudstack 4.10 版中编辑 css 和 js 文件
- google-chrome-extension - 在尝试上传 Chrome 扩展屏幕截图时总是收到 Invalid size 错误