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

2024/10/15 4:25:00

So I am trying to create a Python Program to detect similar details in two images using Python's OpenCV. I have the two images and they are in my current directory, and they exist (see the code in lines 6-17). But I am getting the following error when I try running it.

import numpy as np
import matplotlib.pyplot as plt
import cv2
import ospath1 = "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()

Here is the error I keep on getting...

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 innerreturn func(ax, *args, **kwargs)File "C:\Program Files\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 5194, in imshowim.set_data(X)File "C:\Program Files\Python36\lib\site-packages\matplotlib\image.py", line 600, in set_dataraise TypeError("Image data cannot be converted to float")
TypeError: Image data cannot be converted to float

Can someone please explpain to me why I am getting this error, what it means, and how to fix it.

Answer

You're not actually reading in an image.

Check out what happens if you try to display None in matplotlib:

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  

You're reading WIN_20171207_13_51_33_Pro.jpeg but you're checking if WIN_20171207_13_51_33_Pro.jpg exists. Note the different extensions. Why do you have the filename written twice (and differently)? Just simply write:

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

Note that even if you put a bogus file into cv2.imread(), the resulting image will just be None, which doesn't error in any of the subsequent function calls until matplotlib tries to draw it. If you print(img1) after reading, you'll see it's None and not reading properly.

https://en.xdnf.cn/q/69328.html

Related Q&A

Specify timestamp on each packet in Scapy?

With Scapy, when I create a packet and write it to a pcap file, it sets the timestamp of the packet to the current time.This is my current usage. 1335494712.991895 being the time I created the packet:&…

Converting a dataframe to dictionary with multiple values

I have a dataframe likeSr.No ID A B C D1 Tom Earth English BMW2 Tom Mars Spanish BMW Green 3 Michael Mercury Hindi …

How do I create KeyPoints to compute SIFT?

I am using OpenCV-Python.I have identified corner points using cv2.cornerHarris. The output is of type dst.I need to compute SIFT features of the corner points. The input to sift.compute() has to be of…

Error in Tensorboards(PyTorch) add_graph

Im following this Pytorchs Tensorboard documentation. I have the following code: model = torchvision.models.resnet50(False) writer.add_graph(model)It throws the following error:_ = model(*args) # dont…

Population must be a sequence or set. For dicts, use list(d)

I try to excute this code and I get the error bellow, I get the error in the random function and I dont know how to fix it, please help me.def load_data(sample_split=0.3, usage=Training, to_cat=True, v…

Why do imports fail in setuptools entry_point scripts, but not in python interpreter?

I have the following project structure:project |-project.py |-__init__.py |-setup.py |-lib|-__init__.py|-project|-__init__.py|-tools.pywith project.py:from project.lib import *def main():print("ma…

msgpack unserialising dict key strings to bytes

I am having issues with msgpack in python. It seems that when serialising a dict, if the keys are strings str, they are not unserialised properly and causing KeyError exceptions to be raised.Example:&g…

Better solution for Python Threading.Event semi-busy waiting

Im using pretty standard Threading.Event: Main thread gets to a point where its in a loop that runs:event.wait(60)The other blocks on a request until a reply is available and then initiates a:event.set…

\ufeff Invalid character in identifier

I have the following code :import urllib.requesttry:url = "https://www.google.com/search?q=test"headers = {}usag = Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:25.0) Gecko/20100101 Firefo…

Python multiprocessing - Passing a list of dicts to a pool

This question may be a duplicate. However, I read lot of stuff around on this topic, and I didnt find one that matches my case - or at least, I didnt understood it.Sorry for the inconvenance.What Im tr…