我是一个初学者,正在学习编码图像分类器。我的目标是创建一个预测函数。
有什么建议可以解决吗?
在这个项目中,我想使用预测功能来识别不同的花卉种类。所以我以后可以检查他们的标签。
试图修复:不幸的是,该错误仍然持续存在。我已经尝试过这些代码:
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')
答案 0 :(得分:1)
尝试使用函数YOLOv3
darknet53.conv.74
obj.data
obj.names
Tank.zip
yolov3.weights
yolov3_custom.cfg
yolov3_custom1.cfg.txt
将JpegImageFile转换为numpy数组,然后就可以使用图像了。
答案 1 :(得分:0)
什么是image
?它来自哪里?
似乎已经Image.open()
编辑过,您正尝试重新读取它,就像它是文件还是路径一样。
答案 2 :(得分:0)
尝试打开已调用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
答案 3 :(得分:0)
打开后将图像转换为RGB为我解决了这个问题
PIL.Image.open(image_path).convert('RGB')
答案 4 :(得分:0)
我遇到了类似的问题,通过如下打开图片解决了:
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