首页 > 解决方案 > 绘制形状为 (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)

标签: pythonnumpymatplotlibplotitk

解决方案


用于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")

参考

  1. numpy.squeeze()文件

推荐阅读