TypeError: img should be PIL Image. Got <class 'str'>

i am a beginner in Pytorch using to detect image class and facing this error i don’t know how to resolve this error

here is code

sm = nn.Softmax(dim = 1)

data=test_transforms(image)

data.unsqueeze_(0)
data=Variable(data)
data = data.type(torch.FloatTensor)

classifier.eval()
output = classifier(data)

print(labels[output.cpu().data.numpy().argmax()])

facing this error


TypeError Traceback (most recent call last)
in
1 sm = nn.Softmax(dim = 1)
2
----> 3 data=test_transforms(image)
4
5 data.unsqueeze_(0)

~.conda\envs\tensorflow\lib\site-packages\torchvision\transforms\transforms.py in call(self, img)
58 def call(self, img):
59 for t in self.transforms:
—> 60 img = t(img)
61 return img
62

~.conda\envs\tensorflow\lib\site-packages\torchvision\transforms\transforms.py in call(self, img)
193 PIL Image: Rescaled image.
194 “”"
→ 195 return F.resize(img, self.size, self.interpolation)
196
197 def repr(self):

~.conda\envs\tensorflow\lib\site-packages\torchvision\transforms\functional.py in resize(img, size, interpolation)
227 “”"
228 if not _is_pil_image(img):
→ 229 raise TypeError(‘img should be PIL Image. Got {}’.format(type(img)))
230 if not (isinstance(size, int) or (isinstance(size, Iterable) and len(size) == 2)):
231 raise TypeError(‘Got inappropriate size arg: {}’.format(size))

TypeError: img should be PIL Image. Got <class ‘str’>

Based on the error message it seems you might be passing the path or image name as image, while an already loaded PIL.Image is expected.
If that’s the case, try to load the image before passing it to the transformation via im = PIL.Image.open(image_path).

got this error after changing code

sm = nn.Softmax(dim = 1)

data=test_transforms(PIL.Image.open(image_path)) #im = PIL.Image.open(image_path)

data.unsqueeze_(0)
data=Variable(data)
data = data.type(torch.FloatTensor)

classifier.eval()
output = classifier(data)

print(labels[output.cpu().data.numpy().argmax()])

got this error

NameError Traceback (most recent call last)
in
1 sm = nn.Softmax(dim = 1)
2
----> 3 data=test_transforms(PIL.Image.open(image_path)) #im = PIL.Image.open(image_path)
4
5 data.unsqueeze_(0)

NameError: name ‘PIL’ is not defined

You would have to either import PIL directly or from PIL import Image and call Image.open.