图像数据无法转换为浮点型 [英] Image data cannot be converted to float

查看:174
本文介绍了图像数据无法转换为浮点型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用CNN模型训练后,我有一个用于预测犬种的代码,我从下面的函数中获得了类索引.我想显示从该函数获取的class idx文件夹中的随机图像.

I have a code for predicting dog breed after training on CNN model, I get the class index from the below function. I want to display an random image from the class idx folder obtained from the function.

    class_name = [item for item in loaders['train'].dataset.classes]

      def predict_dog_breed(img,model,class_names):
           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])))
          imshow(a)
          return class_name[idx]

当我尝试显示随机图像时,出现以下错误:

When I tried to display the random image, I am getting the below error:

对于os.listdir('./images')中img_file的

TypeError跟踪(最近一次调用最近)为1:2 image = os.path.join('./images',img_file)----> 3 dog_or_human(image)

TypeError Traceback (most recent call last) in 1 for img_file in os.listdir('./images'): 2 image = os.path.join('./images', img_file) ----> 3 dog_or_human(image)

5 plt.show()6如果dog_detector(img)== True:----> 7predict_dog = predict_dog_breed(img,net,class_name)8print(检测到狗!品种是{}".format(predict_dog))9 elif face_detector(img)> 0:

in dog_or_human(img) 5 plt.show() 6 if dog_detector(img) == True: ----> 7 predict_dog = predict_dog_breed(img, net, class_name) 8 print("Dog Detected!The breed is {}".format(predict_dog)) 9 elif face_detector(img) > 0:

predict_dog_breed(img,model,class_name)18 a = random.choice(os.listdir("./dogImages/train/{}/".format(class_name [idx])))19 print(a )---> 20 imshow(a)21 #subdir =''.join([["/dogImages/train/",class_name [idx]])22 #print(文件)

in predict_dog_breed(img, model, class_name) 18 a = random.choice(os.listdir("./dogImages/train/{}/".format(class_name[idx]))) 19 print(a) ---> 20 imshow(a) 21 #subdir = ''.join(["/dogImages/train/", class_name[idx]]) 22 #print(file)

〜/Library/Python/3.7/lib/python/site-packages/matplotlib/pyplot.py in imshow(X,cmap,norm,aspect,插值,alpha,vmin,vmax,原点,范围,形状,filternorm ,filterrad,imlim,resample,url,data,** kwargs)2697 filternorm = filternorm,filterrad = filterrad,imlim = imlim,2698 resample = resample,url = url,**({{data:data}如果有data不是-> 2699其他{}),** kwargs)2700 sci(__ ret)2701 return __ret

~/Library/Python/3.7/lib/python/site-packages/matplotlib/pyplot.py in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, data, **kwargs) 2697 filternorm=filternorm, filterrad=filterrad, imlim=imlim, 2698 resample=resample, url=url, **({"data": data} if data is not -> 2699 None else {}), **kwargs) 2700 sci(__ret) 2701 return __ret

〜/Library/Python/3.7/lib/python/site-packages/matplotlib/init.py内部的(ax,data,* args,** kwargs)1808"Matplotlib列表!" %(label_namer,func.name),1809 RuntimeWarning,stacklevel = 2)-> 1810 return func(ax,* args,** kwargs)1811 1812 inner.doc = _add_data_doc(inner.doc,

~/Library/Python/3.7/lib/python/site-packages/matplotlib/init.py in inner(ax, data, *args, **kwargs) 1808 "the Matplotlib list!)" % (label_namer, func.name), 1809 RuntimeWarning, stacklevel=2) -> 1810 return func(ax, *args, **kwargs) 1811 1812 inner.doc = _add_data_doc(inner.doc,

〜/Library/Python/3.7/lib/python/site-packages/matplotlib/axes/_axes.py在imshow中(self,X,cmap,norm,aspect,插值,alpha,vmin,vmax,原点,范围,形状,filternorm,filterrad,imlim,resample,url,** kwargs)5492 resample = resample,** kwargs)5493->如果im.get_clip_path()为None,则5549 im.set_data(X)5495 im.set_alpha(alpha)5496:

~/Library/Python/3.7/lib/python/site-packages/matplotlib/axes/_axes.py in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs) 5492 resample=resample, **kwargs) 5493 -> 5494 im.set_data(X) 5495 im.set_alpha(alpha) 5496 if im.get_clip_path() is None:

〜/Library/Python/3.7/lib/python/site-packages/matplotlib/image.py在set_data(self,A)中632 if(self._A.dtype!= np.uint8和633 not np.can_cast (self._A.dtype,float,"same_kind")):-> 634引发TypeError(图像数据无法转换为float")635636否则(self._A.ndim == 2

~/Library/Python/3.7/lib/python/site-packages/matplotlib/image.py in set_data(self, A) 632 if (self._A.dtype != np.uint8 and 633 not np.can_cast(self._A.dtype, float, "same_kind")): --> 634 raise TypeError("Image data cannot be converted to float") 635 636 if not (self._A.ndim == 2

TypeError:图像数据无法转换为浮点数

TypeError: Image data cannot be converted to float

对此有任何帮助,将不胜感激!

Any help on this would be appreciated!

推荐答案

因此,我尝试在您的代码中重现错误

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])))基本上返回图像文件名,它是一个字符串.您不是在读取图像,只是将文件名传递给imshow函数,这是不正确的.请检查以下数字以进行澄清.

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.

错误代码:

没有错误的代码:

因此,将您的predict_do_breed函数更改为以下内容:

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]

在上面的代码中,已使用cv2.imread函数读取由random.choice(os.listdir("./dogImages/train/{}/".format(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]))).

这篇关于图像数据无法转换为浮点型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆