[python] TypeError: Image data can not convert to float

I am trying to create a 16-bit image like so:

import skimage 
import random
from random import randint                        
xrow=raw_input("Enter the number of rows to be present in image.=>")
row=int(xrow)
ycolumn=raw_input("Enter the number of columns to be present in image.=>")
column=int(ycolumn)

A={}
for x in xrange(1,row):
    for y in xrange(1,column):
        a=randint(0,65535)
        A[x,y]=a 

imshow(A)

But I get the error TypeError: Image data can not convert to float.

This question is related to python image image-processing python-imaging-library

The answer is


In my case image path was wrong! So firstly, you might want to check if image path is correct :)


As for cv2 is concerned.

  1. You might not have provided the right file type while cv2.imread(). eg jpg instead of png.
  2. Or you are providing image path instead of image's array. eg plt.imshow(img_path),

try cv2.imread(img_path) first then plt.imshow(img) or cv2.imshow(img).


try

import skimage
import random
from random import randint
import numpy as np
import matplotlib.pyplot as plt


xrow = raw_input("Enter the number of rows to be present in image.=>")
row = int(xrow)
ycolumn = raw_input("Enter the number of columns to be present in image.=>")
column = int(ycolumn)

A = np.zeros((row,column))
for x in xrange(1, row):
    for y in xrange(1, column):
        a = randint(0, 65535)
        A[x, y] = a

plt.imshow(A)
plt.show()

I guess you may have this problem in Pycharm. If so, you may try this to your problem.

Go to File-Setting-Tools-Python Scientificin Pycharm and remove the option of Show plots in tool window.


First read the image as an array

image = plt.imread(//image_path)
plt.imshow(image)

The problem was that my array was in type u3 i changed it to float and it worked for me . I had a dataframe with Image column having the image/pic data.Reshaping part depends to person to person and image they deal with mine had 9126 size hence it was 96*96.

a = np.array(df_train.iloc[0].Image.split(),dtype='float')
a = a.reshape(96,96)
plt.imshow(a)

The error occurred when I unknowingly tried plotting the image path instead of the image.

My code :

import cv2 as cv
from matplotlib import pyplot as plt
import pytesseract
from resizeimage import resizeimage

img = cv.imread("D:\TemplateMatch\\fitting.png") ------>"THIS IS THE WRONG USAGE"
#cv.rectangle(img,(29,2496),(604,2992),(255,0,0),5)
plt.imshow(img)

Correction: img = cv.imread("fitting.png") --->THIS IS THE RIGHT USAGE"


This happened for me when I was trying to plot an imagePath, instead of the image itself. The fix was to load the image, and plotting it.


I was also getting this error, and the answers given above says that we should upload them first and then use their name instead of a path - but for Kaggle dataset, this is not possible.

Hence the solution I figure out is by reading the the individual image in a loop in mpimg format. Here we can use the path and not just the image name.

I hope it will help you guys.

import matplotlib.image as mpimg
for img in os.listdir("/content/train"): 
  image = mpimg.imread(path)
  plt.imshow(image)
  plt.show()

This question comes up first in the Google search for this type error, but does not have a general answer about the cause of the error. The poster's unique problem was the use of an inappropriate object type as the main argument for plt.imshow(). A more general answer is that plt.imshow() wants an array of floats and if you don't specify a float, numpy, pandas, or whatever else, might infer a different data type somewhere along the line. You can avoid this by specifying a float for the dtype argument is the constructor of the object.

See the Numpy documentation here.

See the Pandas documentation here


Try this

plt.imshow(im.reshape(im.shape[0], im.shape[1]), cmap=plt.cm.Greys)

It would help in some cases.


From what I understand of the scikit-image docs (http://scikit-image.org/docs/dev/index.html), imshow() takes a ndarray as an argument, and not a dictionary:

http://scikit-image.org/docs/dev/api/skimage.io.html?highlight=imshow#skimage.io.imshow

Maybe if you post the whole stack trace, we could see that the TypeError comes somewhere deep from imshow().


Try to use this,

   plt.imshow(numpy.real(A))
   plt.show()

instead of plt.imshow(A)


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to image-processing

Convert np.array of type float64 to type uint8 scaling values dlib installation on Windows 10 OpenCV - Saving images to a particular folder of choice How do I increase the contrast of an image in Python OpenCV OpenCV & Python - Image too big to display TypeError: Image data can not convert to float Extracting text OpenCV c++ and opencv get and set pixel color to Mat cv2.imshow command doesn't work properly in opencv-python How does one convert a grayscale image to RGB in OpenCV (Python)?

Examples related to python-imaging-library

How do I install PIL/Pillow for Python 3.6? TypeError: Image data can not convert to float Combine several images horizontally with Python Generate random colors (RGB) How to show PIL Image in ipython notebook Why can't Python import Image from PIL? Importing images from a directory (Python) to list or dictionary ImportError: No module named Image Installing PIL with pip Image.open() cannot identify image file - Python?