AttributeError: 'str' object has no attribute 'size'

I noticed that other people are able to successfully avoid the “str’ object has no attribute ‘size’” error message, but I’m getting it for some reason. What is the reason for that and how can I correct that?

Error message:


AttributeError Traceback (most recent call last)
in ()
5 test_image_index = 28
6 test_image = test_dir + “/” + str(test_image_index) + “/image_05230.jpg”
----> 7 img = process_image(test_image)
8 #test_image = images.to(‘cuda’)
9

in process_image(image)
7
8 # scale
----> 9 img_w, img_h = image.size
10
11 if(img_w > img_h):

AttributeError: ‘str’ object has no attribute ‘size’

Code Reference 1:

TODO: Display an image along with the top 5 classes

Get and process a Test Image

torch.set_default_tensor_type(‘torch.cuda.FloatTensor’)

test_image_index = 28
test_image = test_dir + “/” + str(test_image_index) + “/image_05230.jpg”
img = process_image(test_image)
#test_image = images.to(‘cuda’)

Display test image, with Label as title

label = cat_to_name.get(str(test_image_index))
print(label)
ax = imshow(img, ax=plt).title(label)

Run image through model

probs, classes = predict(test_image, model)
print(“Probs:”,probs)
print(“Class:”,classes)

Code Reference 2:

def process_image(image):
‘’’ Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
‘’’

# TODO: Process a PIL image for use in a PyTorch model

# scale

img_w, img_h = image.size
if(img_w > img_h):
image = image.resize(size=(int((img_w256)/img_h),256))
elif(img_w < img_h):
image = image.resize(size=(256,int((img_w
256)/img_h)))

# crop
img_w_new, img_h_new = image.size
c1 = int(img_w_new/2-112)
c2 = int(img_h_new/2-112)
c3 = int(img_w_new/2+112)
c4 = int(img_h_new/2+112)

image = image.crop((c1, c2, c3, c4)) # Getting (224, 224) image

# normalize
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
image_array = np.array(image) / 255
image_norm = (image_array - mean) / std

# reorder dimension
image_trans = image_norm.transpose((2,0,1))

return torch.from_numpy(image_trans) # converting ndarray to tensor

It seems you are passing the image path to process_image instead of an PIL.Image.
Try to load the image and pass it to the function:

from PIL import Image

test_image_path = ...
test_image = Image.open(test_image_path)
process_image(test_image)