TypeError: Image data can not be converted to float

1

I have a problem with the following code:

import cv2 
import matplotlib.pyplot as plt

img1 = cv2.imread('images\colombia_city.jpg')
img2 = cv2.imread('images\colombia_city_2.jpg')

#img = img1 + img2
#img = cv2.add(img1,img2)
abc = cv2.addWeighted(img1,0.7,img2,0.3,55)

plt.imshow(abc)
plt.show()
plt.title("Weighted"); plt.axes()
plt.waitforbuttonpress()

According to Visual Studio the problem is in

  

plt.imshow (abc)

But when I try the program in another IDE, this runs normally

    
asked by Raul Juliao 18.02.2018 в 01:50
source

1 answer

2

The first possibility in which you have to think about these cases because it is the simplest and most common is that you are not passing a correct path to cv2.imread .

Interestingly, if cv2.imread does not receive a correct route, it does not bother to throw an exception or a misnomer, simply returns None . In this case two images are used, if only one of the routes was incorrect the code would throw an exception, but in abc = cv2.addWeighted(img1,0.7,img2,0.3,55) because it is with an array on one side and None on the other and that if not It looks good and tells us something like:

  

The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function cv :: arithm_op

But if both routes are wrong cv2.addWeighted does not fail, it just returns another None . This is when plt.imshow reaches an object None and as expects an array of floats throws the exception shown:

  

TypeError: Image data can not convert to float

To rule out this possibility we can do the following:

import cv2 
import matplotlib.pyplot as plt

img1 = cv2.imread(r"images\colombia_city.jpg")
img2 = cv2.imread(r"images\colombia_city.jpg")

assert(img1 is not None), "img1 no existe, compruebe la ruta"
assert(img2 is not None), "img2 no existe, compruebe la ruta"


abc = cv2.addWeighted(img1,0.7,img2,0.3,55)

plt.imshow(img1)
plt.title("Weighted")
plt.axes()
plt.show()
  

Note: When routes are passed, \ should not be used as a directory separator. The inverse bar ( \ ) indicates an escape sequence, which implies that, for example, in "imagenes\nueva.jpg" the set \n is taken as a line break. Instead you should use raw strings ( r"imagenes\nueva.jpg" ), escape the backslash ( "imagenes\nueva.jpg" ) or use the Unix-like style "imagenes/nueva.jpg"

    
answered by 22.03.2018 в 08:54