为什么PIL和plt.imshow在Python中使用相同的张量时显示不同的图像?

问题描述 投票:0回答:1

我正在尝试将 PyTorch 张量转换为 PIL 图像并使用 matplotlib.pyplot 和 PIL 显示它。但是,我注意到 plt.imshow 和 PIL 的 display() 函数显示的图像看起来彼此不同。

即时显示

PIL

下面是我用来执行转换和显示图像的函数:

import matplotlib.pyplot as plt
from PIL import Image

def tensor_to_pil(image_tensor):
    print(image_tensor[0].shape)
    plt.figure()
    plt.imshow(image_tensor[0].cpu().squeeze().numpy(), cmap='gray')

    if image_tensor.shape[1] == 1:
        pil_image = Image.fromarray(image_tensor[0].cpu().squeeze().numpy(), "L")
    else:
        # This seems to be an error in the code where 'error' is not defined
        # error
        pil_image = Image.fromarray(image_tensor[0].permute(1, 2, 0).cpu().numpy())
    print("yes")
    display(pil_image)
    print("yes")


张量尺寸:我使用的张量是灰度图像(1个颜色通道),image_tensor变量的尺寸为torch.Size([1,1,640,640])

什么可能导致 plt.imshow 和 PIL 显示相同图像张量的差异?我需要做任何额外的处理来调整它们的输出吗?

python pytorch python-imaging-library
1个回答
0
投票

PIL.Image.fromarray 函数似乎只接受一组数据类型进行转换(如 https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image 所示。来自数组)。

对于您的情况,我尝试将火炬阵列转换为

np.uint32
并且成功了。

您可以通过以下方式执行此操作:

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from IPython.display import display
def tensor_to_pil(image_tensor):
    print(image_tensor[0].shape)
    plt.figure()
    plt.imshow(image_tensor[0].cpu().squeeze().numpy(), cmap='gray')
    plt.show()
    # print((image_tensor[0].cpu().squeeze().numpy()))
    if image_tensor.shape[1] == 1:
        pil_image = Image.fromarray(image_tensor[0].cpu().squeeze().numpy().astype(np.uint32))
    else:
        # This seems to be an error in the code where 'error' is not defined
        # error
        pil_image = Image.fromarray(image_tensor[0].permute(1, 2, 0).cpu().numpy())
    print("yes")
    display(pil_image)
    print("yes")
© www.soinside.com 2019 - 2024. All rights reserved.