Python OpenCV错误:" TypeError:图像数据无法转换为float"

时间:2017-12-07 22:28:48

标签: python opencv

所以我试图创建一个Python程序,使用Python的OpenCV检测两个图像中的类似细节。我有两个图像,它们在我当前的目录中,它们存在(参见第6-17行中的代码)。但是当我尝试运行它时,我收到以下错误。

import numpy as np
import matplotlib.pyplot as plt
import cv2
import os

path1 = "WIN_20171207_13_51_33_Pro.jpg"
path2 = "WIN_20171207_13_51_43_Pro.jpg"

if os.path.isfile(path1):
    img1 = cv2.imread('WIN_20171207_13_51_33_Pro.jpeg',0)
else:
    print ("The file " + path1 + " does not exist.")

if os.path.isfile(path2):
    img2 = cv2.imread('WIN_20171207_13_51_43_Pro.jpeg',0)
else:
    print ("The file " + path2 + " does not exist.")

orb = cv2.ORB_create()

kpl1, des1 = orb.detectAndCompute(img1,None)
kpl2, des2 = orb.detectAndCompute(img2,None)

bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x:x.distance)

img3 = cv2.drawMatches(img1,kpl1,img2,kpl2,matches[:10],None, flags=2)

plt.imshow (img3)
plt.show()

这是我一直在犯的错误......

Traceback (most recent call last):


File "C:\Users\jweir\source\repos\BruteForceFeatureDetection\BruteForceFeatureDetection\BruteForceFeatureDetection.py", line 31, in <module>
    plt.imshow (img3)
  File "C:\Program Files\Python36\lib\site-packages\matplotlib\pyplot.py", line 3080, in imshow
    **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\matplotlib\__init__.py", line 1710, in inner
    return func(ax, *args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 5194, in imshow
    im.set_data(X)
  File "C:\Program Files\Python36\lib\site-packages\matplotlib\image.py", line 600, in set_data
    raise TypeError("Image data cannot be converted to float")
TypeError: Image data cannot be converted to float

有人可以向我展示为什么我会收到此错误,意味着什么,以及如何解决此错误。

2 个答案:

答案 0 :(得分:10)

你实际上并没有在图像中阅读。

如果您尝试在matplotlib中显示None,请查看会发生什么:

plt.imshow(None)
Traceback (most recent call last):  

 File ".../example.py", line 16, in <module>  
   plt.imshow(None)  
 File ".../matplotlib/pyplot.py", line 3157, in imshow  
   **kwargs)  
 File ".../matplotlib/__init__.py", line 1898, in inner  
   return func(ax, *args, **kwargs)  
 File ".../matplotlib/axes/_axes.py", line 5124, in imshow  
   im.set_data(X)  
 File ".../matplotlib/image.py", line 596, in set_data  
   raise TypeError("Image data can not convert to float")  

TypeError: Image data can not convert to float  

您正在阅读WIN_20171207_13_51_33_Pro.jpeg但是您正在检查WIN_20171207_13_51_33_Pro.jpg是否存在。请注意不同的扩展名。为什么你有两次(和不同的)文件名?只需写一下:

if os.path.isfile(path1):
    img1 = cv2.imread(path1, 0)
else:
    print ("The file " + path1 + " does not exist.")

请注意,即使您将伪造的文件放入cv2.imread(),生成的图像也只是None,在任何后续函数调用中都没有错误,直到matplotlib尝试绘制它。如果您在阅读后print(img1),则会看到它None并且无法正确阅读。

答案 1 :(得分:0)

我不知道这是否与您的情况有关,但由于我们以字符串类型分配文件路径,例如 cv2.imread("filepathHere"),如果在其导致的文件路径中出现诸如“\b”或“\r”之类的参数程序来弹出这样的错误。

之前遇到这样的错误,我把文件名从file/brick.png改成ibrick.png,问题解决了。