pytorch 如何在google colab中显示Tensor图像??请查找我的代码中的错误

46scxncf  于 2023-05-17  发布在  Go
关注(0)|答案(1)|浏览(117)

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

`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
这是OUTPUT
Ori图像形状(339,510,3)原始图像形状: Torch 。大小([3,339,510])最终图像形状: Torch .尺寸([339,510,3])
This in the output image
我不明白问题出在哪里。

ffdz8vbo

ffdz8vbo1#

问题似乎是你实际上没有在输出中显示图像,而是显示Tensor形状。要显示图像,可以在使用.numpy()方法将Tensor转换回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)

相关问题