gpt4 book ai didi

python - 如何修复 "AttributeError: ' JpegImageFile' 对象没有属性 'read' ?

转载 作者:太空宇宙 更新时间:2023-11-03 20:40:45 25 4
gpt4 key购买 nike

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

有什么解决办法吗?

在这个项目中,我想使用预测函数来识别不同的花卉种类。这样我以后就可以检查他们的标签。

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

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

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

AttributeError: 'JpegImageFile' object has no attribute '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')

最佳答案

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

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

关于python - 如何修复 "AttributeError: ' JpegImageFile' 对象没有属性 'read' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56880941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com