1

I imported matplotlib.pyplot and also NumPy

I wanted to display an image from my desktop to the plot but I get a TypeError.

code :

img = (image) ( here do we need to give the location of the file or the file directly)

imshow(img, extent=[-25,25,-25,25], cmap = cm.bone)
colorbar()


Error: TypeError: Image data can not convert to float

I am using Pycharm as my ide.

3
  • I removed the matlab tag, since your question doesn't seem to have anything to do with matlab. Also, take a look at imread. Commented Jan 6, 2016 at 10:19
  • 1
    Have you tried this Commented Jan 6, 2016 at 10:23
  • Thanks Andras and avstenit, it did work with "imread". cheers :) Commented Jan 6, 2016 at 11:18

2 Answers 2

5

You are a bit ambiguous about

here do we need to give the location of the file or the file directly

No you don't. You need to use some imaging library to read an image. img="C:\image.jpg" does not read an image!

For example, to read a 'png' image, you could:

# Copypaste from docs
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img=mpimg.imread('myimage.png')
# end
# from now on you can use img as an image, but make sure you know what you are doing!
imgplot=plt.imshow(img)
plt.show()

Read more at Image tutorial at matplotlib's doc

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

2 Comments

Note that I don't think you actually need to import numpy for this, and I have a hunch that imread and imshow are already in matplotlib.pyplot. (But you need mpimg.imshow otherwise.)
@moooeeeep probably yeah. First 4 lines are a copy paste from the docs, next line a copypaste from the OP. I guess errors are in the OPs line.
0

Is img a numpy array of the right type?

If you read the image using pillow,etc. and have an Image object you have to get the numpy array from it ( img.getdata() )

X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)

Display the image in X to current axes. X may be a float array, a uint8 array or a PIL image. If X is an array, it can have the following shapes:

MxN – luminance (grayscale, float array only) MxNx3 – RGB (float or uint8 array) MxNx4 – RGBA (float or uint8 array) The value for each component of MxNx3 and MxNx4 float arrays should be in the range 0.0 to 1.0;

Either normalize img so it's between 0.0 and 1.0 or convert it to uint8 ( img=np.array(img, dtype=np.uint8) ).

1 Comment

yes it gave me an Value error when i used a JPG file, it tells me to use pillow for handling different type of files. It gives me a suggestion to use only PNG

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.