简体   繁体   中英

How do I display an image in a plot using Python?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM