python - 如何修复“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')
解决方案
打开后将图像转换为 RGB 为我解决了这个问题
PIL.Image.open(image_path).convert('RGB')
推荐阅读
- r - 如何使用 dplyr 使用行数据创建新列
- google-sheets - Google 表格 - 随机化和冻结查询的列
- node.js - 希望数字限制为最多 2 位数字以及最多 7 个小数点 - ReactJS
- validation - 通过代理验证 Istio 令牌
- javascript - 如何在 react-native-slider 的最后一个值处添加“+”符号?
- json - 验证 json 架构时出现错误“数据应该是对象”
- reactjs - 有没有办法在胜利折线图上的最后一个数据点上绘制一个点以响应本机
- maven - 带有 JSTL 1.2 的 Maven 项目显示 JasperException
- python - 如何在 discord.py 中为按钮添加权限
- reactjs - 减少 Firestore 中的文档读取,响应应用程序