【问题标题】:How to fix "AttributeError: 'JpegImageFile' object has no attribute 'read'?如何修复“AttributeError:'JpegImageFile'对象没有属性'read'?
【发布时间】:2021-03-01 23:07:15
【问题描述】:

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

有什么解决办法吗?

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

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

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

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

AttributeError: 'JpegImageFile' 对象没有属性 'read'

代码:

# 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')

【问题讨论】:

  • 嗨@Paula,你能告诉我process_image()function 定义在哪里吗?

标签: python image python-imaging-library


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    image 是什么?它来自哪里?

    它看起来像是已经被Image.open()ed 的东西,而您正试图重新读取它,就好像它是一个文件或路径一样。

    【讨论】:

    • 你问了一个有趣的问题。 image 是一个 image_path。
    • 根据你得到的异常,它肯定不像它。
    • 也许,我应该更改路径的名称吗?
    • 这个答案帮助我意识到我坚持使用已经打开的图像。谢谢。
    【解决方案3】:

    尝试使用函数numpy.asarray(image) 将JpegImageFile 转换为numpy 数组,然后您就可以使用图像了。

    【讨论】:

    • 这似乎没有帮助
    【解决方案4】:

    我在尝试打开已经调用 Image.open() 的图像时遇到了同样的问题。以下内容对您有用:

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

    如果您的图像类型和/或您将看到的图像已经是张量:

    print(image
    print(type(image))
    

    这是回答相同问题的相关链接:

    https://discuss.pytorch.org/t/typeerror-img-should-be-pil-image-got-class-str/49644

    【讨论】:

    • 我试过这个并得到:``` in () 2 3 image_path = './flowers/test/1/image_06743.jpg' - ---> 4 predict(image_path, model, topk=5) in predict(image_path, model, topk) 11 # Open 12 img = process_image(image_path) ---> 13 img = torch.from_numpy(img).type(torch.FloatTensor) 14 15 # 预处理图像 TypeError: expected np.ndarray (got tuple)```知道为什么它需要一个数组以及如何将其转换为数组吗?
    • 看起来好像您实际上是在将图像路径(即字符串)传递给您的预测函数,因此它会给您该错误。既然是这种情况,OP 的原始代码行应该适合您:img = process_image(Image.open(image)) img = torch.from_numpy(img).type(torch.FloatTensor) 它对他不起作用,因为他的图像输入参数已经是一个 Image.open(image_path) 对象,因为您的是应该打开的图像路径图像并将其转换为数组,然后将其转换为张量@rachelvsamuel
    • 注意:注意 img = process_image(Image.open(image))
    【解决方案5】:

    我也遇到过类似的问题,打开图片解决了如下:

    import io
    from PIL import Image as pil_image
    
    fname = 'my_image.jpg'
    
    with open(fname, 'rb') as f:
        img = pil_image.open(io.BytesIO(f.read()))
        pass
    

    而不是:

    from PIL import Image as pil_image
    
    fname = 'my_image.jpg'
    
    with pil_image.open(fname, 'r') as img:
        pass
    

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多