首页 > 解决方案 > 如何修复“AttributeError:'JpegImageFile'对象没有属性'read'?

问题描述

我是初学者,我正在学习编写图像分类器。我的目标是创建一个预测函数。

有什么建议可以解决吗?

在这个项目中,我想使用预测功能来识别不同的花种。所以我可以稍后检查他们的标签。

尝试修复:不幸的是,错误仍然存​​在。我已经尝试过这些代码:

img = process_image(Image.open(image))
img = torch.from_numpy(img).type(torch.FloatTensor) 

这是我现在需要修复的错误。

AttributeError:“JpegImageFile”对象没有“读取”属性

代码:

# Imports here
import pandas as pd
import numpy as np

import torch
from torch import nn
from torchvision import datasets, transforms, models
import torchvision.models as models
import torch.nn.functional as F
import torchvision.transforms.functional as F
from torch import optim
import json

from collections import OrderedDict
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
from PIL import Image

def predict(image, model, topk=5):

#Predict the class (or classes) of an image using a trained deep #learning model.
#Here, image is the path to an image file, but input to process_image #should be Image.open(image).                                                         

    img = process_image(Image.open(image))
    img = torch.from_numpy(img).type(torch.FloatTensor) 

    output = model.forward(img)
    probs, labels = torch.topk(output, topk)        
    probs = probs.exp()

    # Reverse the dict
    idx_to_class = {val: key for key, val in
model.class_to_idx.items()}
    # Get the correct indices
    top_classes = [idx_to_class[each] for each in classes]

    return labels, probs
predict(image,model)
print(probs)
print(classes)

错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-32-b49fdcab5791> in <module>()
----> 1 probs, classes = predict(image, model)
      2 print(probs)
      3 print(classes)

<ipython-input-31-6f996290ea63> in predict(image, model, topk)
      5       Image.open(image)
      6     '''
----> 7     img = process_image(Image.open(image))
      8     img = torch.from_numpy(img).type(torch.FloatTensor)
      9 

/opt/conda/lib/python3.6/site-packages/PIL/Image.py in open(fp, mode)
   2587         exclusive_fp = True
   2588 
-> 2589     prefix = fp.read(16)
   2590 
   2591     preinit()

AttributeError: 'JpegImageFile' object has no attribute 'read'

我想要的只是得到这些类似的结果。谢谢!

tensor([[ 0.5607,  0.3446,  0.0552,  0.0227,  0.0054]], device='cuda:0')   
tensor([[  8,   1,  31,  24,   7]], device='cuda:0')

标签: pythonimagepython-imaging-library

解决方案


打开后将图像转换为 RGB 为我解决了这个问题

   PIL.Image.open(image_path).convert('RGB')

推荐阅读