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

Python OpenCV Error: “TypeError: Image data cannot be converted to float”

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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()

这是我一直在犯的错误…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Traceback (most recent call last):


File"C:\Users\jweir\source
epos\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

有人能给我解释一下为什么我会犯这个错误,它是什么意思,以及如何解决它吗?


你实际上不是在看图像。

查看在Matplotlib中显示None会发生什么:

1
plt.imshow(None)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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是否存在。注意不同的扩展名。为什么文件名要写两次(和不同的方式)?只需写:

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

请注意,即使在cv2.imread()中放置了一个伪文件,生成的图像也只是None,在matplotlib尝试绘制之前,它不会在任何后续函数调用中出错。如果你看完书后再去看一看,你会发现是去看一看(0),而且读得不好。