Skip to main content
 首页 » 编程设计

python之在 matplotlib 中显示张量图像

2024年11月24日11cloudgamer

我正在使用 Python nanodegree 为 Udacity 的 AI 做一个项目。

我正在尝试显示从图像文件路径获得的 torch.cuda.FloatTensor。该图像下方将是一个条形图,显示前 5 个最有可能的花名及其相关概率。

plt.figure(figsize=(3,3)) 
path = 'flowers/test/1/image_06743.jpg'  
 
top5_probs, top5_class_names = predict(path, model,5) 
 
print(top5_probs) 
print(top5_class_names) 
 
flower_np_image = process_image(Image.open(path)) 
flower_tensor_image = torch.from_numpy(flower_np_image).type(torch.cuda.FloatTensor) 
flower_tensor_image = flower_tensor_image.unsqueeze_(0) 
 
axs = imshow(flower_tensor_image, ax = plt) 
axs.axis('off') 
axs.title(top5_class_names[0]) 
axs.show() 
fig, ax = plt.subplots() 
y_pos = np.arange(len(top5_class_names)) 
plt.barh(y_pos, list(reversed(top5_probs))) 
plt.yticks(y_pos, list(reversed(top5_class_names))) 
plt.ylabel('Flower Type') 
plt.xlabel('Class Probability') 

imshow 函数是给我的

def imshow(image, ax=None, title=None): 
    if ax is None: 
        fig, ax = plt.subplots() 
 
    # PyTorch tensors assume the color channel is the first dimension 
    # but matplotlib assumes is the third dimension 
    image = image.transpose((1, 2, 0)) 
 
    # Undo preprocessing 
    mean = np.array([0.485, 0.456, 0.406]) 
    std = np.array([0.229, 0.224, 0.225]) 
    image = std * image + mean 
 
    # Image needs to be clipped between 0 and 1 or it looks like noise when displayed 
    image = np.clip(image, 0, 1) 
 
    ax.imshow(image) 
 
    return ax 

但是我得到了这个输出

[0.8310797810554504, 0.14590543508529663, 0.013837042264640331, 0.005048676859587431, 0.0027143193874508142] 
['petunia', 'pink primrose', 'balloon flower', 'hibiscus', 'tree mallow'] 
 
--------------------------------------------------------------------------- 
TypeError                                 Traceback (most recent call last) 
<ipython-input-17-f54be68feb7a> in <module>() 
     12 flower_tensor_image = flower_tensor_image.unsqueeze_(0) 
     13  
---> 14 axs = imshow(flower_tensor_image, ax = plt) 
     15 axs.axis('off') 
     16 axs.title(top5_class_names[0]) 
 
<ipython-input-15-9c543acc89cc> in imshow(image, ax, title) 
      5     # PyTorch tensors assume the color channel is the first dimension 
      6     # but matplotlib assumes is the third dimension 
----> 7     image = image.transpose((1, 2, 0)) 
      8  
      9     # Undo preprocessing 
 
TypeError: transpose(): argument 'dim0' (position 1) must be int, not tuple 
 
<matplotlib.figure.Figure at 0x7f5855792160> 

我的预测功能有效,但 imshow 只是因调用转置而窒息。有想法该怎么解决这个吗?我认为它隐约与转换回 numpy 数组有关。

我正在处理的笔记本可以在 https://github.com/BozSteinkalt/ImageClassificationProject 上找到

谢谢!

请您参考如下方法:

您正在尝试申请 numpy.transpose到 torch.Tensor 对象,从而调用 tensor.transpose相反。

您应该先将 flower_tensor_image 转换为 numpy,使用 .numpy()

axs = imshow(flower_tensor_image.detach().cpu().numpy(), ax = plt)