Typeerror: Image Data Can Not Convert to Float

Google Colab: TypeError: Image data of dtype object cannot be converted to float

The issue in hand is related to the path of the image.

Your cv2.imread path and the path variable possibly point to different locations. Try locating the image you want in the file browser. If you then right click on it, you would get the ability to copy the path of the file. You must use that path to load the image and it would work.

path='/content/group.jpg'
img = cv2.imread(path)

plt.imshow(img)
plt.show()

TypeError: Image data can not convert to float on plt.imshow()

You are trying to apply an image filter to a matplotlib plot. That is not supposed to work. plt.imshow() returns an matplotlib.image.AxesImage, which is a complex class an as such cannot be converted to float.

Instead you should of course apply the filter to the image itself.

img = ...
plt.imshow(img, clim=(0.064, 0.068))
mod_img = ndimage.median_filter(img, 20)
plt.imshow(mod_img)

TypeError: Image data cannot be converted to float // When importing .png images

The OpenCV part doesn't work because you omitted the slash at the start of the path ahead of Users/marius.... It should be:

imgs = cv2.imread('/Users/marius/Desktop/PDF/imgvh/1.png')

The matplotlib part doesn't work because it should be:

imgs = cv2.imread('/Users/marius...')

plt.imshow(imgs)
plt.show()

Image data cannot be converted to float

So, I tried to reproduced the error in your code here and was successful in doing that. You are getting error because of these lines in your code:

a = random.choice(os.listdir("./dogImages/train/{}/".format(class_name[idx])))
imshow(a)

random.choice(os.listdir("./dogImages/train/{}/".format(class_name[idx]))) basically returns an image filename, which is a string. You are not reading the image, just passing the filename to imshow function, which is incorrect. Check below figures for clarification.

Code with error:

enter image description here

Code without error:

enter image description here

Hence, change your predict_do_breed function to following:

def predict_dog_breed(img,model,class_name):
image = Image.open(img).convert('RGB')
transform = transforms.Compose([transforms.RandomResizedCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])])
image = transform(image)
test_image = image.unsqueeze(0)
net.eval()
output = net(test_image)
idx = torch.argmax(output)
a = random.choice(os.listdir("./dogImages/train/{}/".format(class_name[idx])))
print(a)
img = cv2.imread("./dogImages/train/{}/".format(class_name[idx])+a)
imshow(img)
return class_name[idx]

In the above code, cv2.imread function has been used to read the image filename, outputted by random.choice(os.listdir("./dogImages/train/{}/".format(class_name[idx]))).



Related Topics



Leave a reply



Submit