I am a beginner and I am learning to code an image classifier. My goal is to create a predict function.
In this project, I want to use the predict function to recognize different flower species. So I could check their labels later.
Attempt to fix: Unfortunately, the error is still persistent. I have already tried these codes:
AttributeError: ‘JpegImageFile’ object has no attribute ‘read’
Code
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
Passing
probs, classes = predict(image, model)
print(probs)
print(classes)
Errors
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'
I want to have these similar result:
tensor([[ 0.5607, 0.3446, 0.0552, 0.0227, 0.0054]], device='cuda:0')
tensor([[ 8, 1, 31, 24, 7]], device='cuda:0')