78

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.

1
  • 3
    A is a dictionary, yet you are assuming that it's an image type for display. That's why you're getting the TypeError. However, I'm very confused because I don't know which image library you're using. You've imported scikit-image yet you tagged your post as using PIL. In addition, the imshow call is ambiguous because I don't know which package that comes from. None of your import statements makes that clear to me. Please edit your question to address what package imshow comes from and which image library you'd like to use for your post. BTW, images are indexed starting at 0. Commented Aug 31, 2015 at 1:18

20 Answers 20

66

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

Sign up to request clarification or add additional context in comments.

1 Comment

I have the same issue however I am working with RDD, my code works with python 2 but not with python 3, get the same error TypeError: Image data can not convert to float what should I do in this case? I cannot specify dtype for an rdd
45

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.

Comments

28

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"

1 Comment

You can use full paths in imread, either with e.g. 'D:\\path\\to\\img.jpg' or r'D:\path\to\ing.jpg' (both here are windows paths). A single \ can be part of a command, like '\n' for newline. \\escapes this, or use r'string' for a raw string where everything is just interpreted as text.
24

First read the image as an array

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

2 Comments

As this is an older question with a lot of answers, could you provide information on why this answer is better than the many before it, some of which contain signficantly more explanation?
wow, best answer for my problem. Now the question is why imshow doesn't have this default behavior when passed a path
5

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()

3 Comments

Putting an import statement in a loop is a very bad habit. I edited it for you.
Hmm, I didn't realize it yet but now when you have pointed it out I kinda got the reason why you are saying so. Thank you anyways
You just need to first read the image, which was the case in my situation. make sure you read the path first. imread(path)
3

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().

Comments

3

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()

Comments

3

Try to use this,

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

instead of plt.imshow(A)

Comments

1

This happened because you may transfer a wrong type to imshow(), for example I use albumentations.Compose to change image, and the result is a dict rather than numpy.ndarray. so just change

plt.imshow(cv2.cvtColor(aug(image=img), cv2.COLOR_BGR2RGB))

to

plt.imshow(cv2.cvtColor(aug(image=img)['image'], cv2.COLOR_BGR2RGB))

then it works.

1 Comment

This works with albumentations package. Thanks a lot!
0

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.

1 Comment

nice guess! trying this out
0

Try this

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

It would help in some cases.

Comments

0

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

Comments

0

Or maybe the image path contains Chinese characters, changing to English characters will solve this question.

enter image description here

enter image description here

3 Comments

Please don't post important information like code and error messages as images
Please write the code snippet instead of using images.
that's not an answer to this question. read the question before answering.
0

For this kind of error try checking file path or name

1 Comment

Once you've decided to answer for 7+ years olq qustion... you'd better read the previous answers first, IMHO.
0

This problem is due to the missing the parenthesis on the squeeze function.

plt.imshow(image.squeeze)

To solve the problem, add parenthesis to invoke the squeeze function.

plt.imshow(image.squeeze())

Comments

0

For anyone still stuck with this error trying to open an image, my problem was that the image was an .heic file and for whatever reason PIL.Image could not open it.

You can try some of these solutions: How to work with HEIC image file types in Python

I used this library https://docs.wand-py.org/en/0.6.4/ and was able to open the image from s3 as a stream without modifying the image. You could also just open from disk, I was just happened to be using s3.

from io import BytesIO
from wand.image import Image
s3_resource = boto3.resource('s3')

s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket(your_bucket)
object = bucket.Object(your_key)
response = object.get()
file_stream = response['Body'].read()
image = Image(file=BytesIO(file_stream))

Comments

-1

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).

Comments

-1

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)

Comments

-1

Input should be array

plt.imshow(plt.imread('image_path'))

Comments

-2

For an image file in .mat format. I have done the following to show the image using the imshow() function.

mat = scipy.io.loadmat('point05m_matrix.mat')

x = mat.get("matrix")
print(type(x))
print(len(x))

plt.imshow(x, extent=[0,60,0,55], aspect='auto')
plt.show()

1 Comment

that's not answering this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.