How to display a tensor image in google colab??请在我的代码中查找错误

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

我无法显示保存在驱动器上的图像。请帮助更正代码。

代码如下:

`import cv2
 import torch
 import matplotlib.pyplot as plt

 img = cv2.imread('/content/drive/MyDrive/GANcoursera/0148.png')
 print("Ori image shape", img.shape)
 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # Convert BGR to RGB
 img_tensor = torch.FloatTensor(img.transpose((2, 0, 1)))  # Transpose dimensions
 print("Original image shape:", img_tensor.shape)
 def show_tensor_images(image_tensor):
 image_tensor = (image_tensor + 1) / 2
 image_tensor = torch.clamp(image_tensor, 0, 1)
 plt.axis('on')
 plt.imshow(image_tensor.permute(1, 2, 0))
 print("final image shape:", image_tensor.permute(1, 2, 0).shape)
 plt.pause(0.001)
 plt.show()
show_tensor_images(img_tensor)

`

This is the original image kept on drive which is to be displayed

这是**输出**:

Ori图像形状(339、510、3) 原图形状:torch.Size([3, 339, 510]) 最终图像形状:torch.Size([339, 510, 3])

This in the output image

我不明白问题出在哪里。

image pytorch google-colaboratory display tensor
1个回答
0
投票

问题似乎是您实际上并没有在输出中显示图像,而是显示了张量形状。要显示图像,可以在使用 .numpy() 方法将张量转换回 numpy 数组后使用 plt.imshow() 函数。

import cv2
import torch
import matplotlib.pyplot as plt

img = cv2.imread('/content/drive/MyDrive/GANcoursera/0148.png')
print("Ori image shape", img.shape)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # Convert BGR to RGB
img_tensor = torch.FloatTensor(img.transpose((2, 0, 1)))  # Transpose dimensions
print("Original image shape:", img_tensor.shape)

def show_tensor_images(image_tensor):
image_tensor = (image_tensor + 1) / 2
image_tensor = torch.clamp(image_tensor, 0, 1)
npimg = image_tensor.permute(1, 2, 0).numpy()  # Convert tensor to numpy array
plt.axis('off')
plt.imshow(npimg)
plt.pause(0.001)
plt.show()

show_tensor_images(img_tensor)
© www.soinside.com 2019 - 2024. All rights reserved.