Paula Hwang
Paula Hwang

Reputation: 123

How to fix "AttributeError: 'JpegImageFile' object has no attribute 'read'?

I am a beginner and I am learning to code an image classifier. My goal is to create a predict function.

Any suggestion to fix it?

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:

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

This is the error that I need to fix now.

AttributeError: 'JpegImageFile' object has no attribute 'read'

Code:

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

Error:

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'

All I want is to get these similar result. Thank you!

tensor([[ 0.5607,  0.3446,  0.0552,  0.0227,  0.0054]], device='cuda:0')   
tensor([[  8,   1,  31,  24,   7]], device='cuda:0')

Upvotes: 12

Views: 36813

Answers (5)

Wok
Wok

Reputation: 5303

I have faced a similar issue and solved it by opening the image as follows:

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

rather than:

from PIL import Image as pil_image

fname = 'my_image.jpg'

with pil_image.open(fname, 'r') as img:
    pass

Upvotes: 0

matusko
matusko

Reputation: 3767

Converting image to RGB after openning solved the issue for me

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

Upvotes: 4

Kate pom
Kate pom

Reputation: 39

Try to use function numpy.asarray(image) to convert JpegImageFile into numpy array and then you will be able to work with image.

Upvotes: 1

gutscdav000
gutscdav000

Reputation: 366

I had the same issue when Trying to open an image that had already had Image.open() called on it. the following will work for you:

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

if you the type of the image and/or the image you will see it is already a tensor:

print(image
print(type(image))

here is a related link that is answering the same questions:

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

Upvotes: 0

AKX
AKX

Reputation: 168863

What is image? Where does it come from?

It looks like it's something that's already been Image.open()ed, and you're attempting to re-read it, as if it were a file or a path.

Upvotes: 1

Related Questions