If I do the following commands in iPython or just Python,
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('stinkbug.png')
imgplot = plt.imshow(img)
then nothing happens (no image appear anywhere).
But if I do the following commands:
import scipy.misc as misc
img=misc.imread('stinkbug.png')
misc.imshow(img)
then image appears inside separate window of ImageMagick.
Also, I can run ipython with qtconsole and will see image with first code.
What are the difference between two different ways of diplaying images? Can they be unified, i.e. work in similar way in both consoles? Is it possible to make first code work in normal ipython/python?
Add plt.show(imgplot) at the end of your code.
One line is missing to show the plot window:
plt.show()
Related
I have recently attempted to save images in Spyder using the pyplot.savefig() command as follows (imported from matplotlib), but it doesn't work:
E.g. code:
filename = 'myImage.png'
#images contain the image shown in the Spyder Plots pane
pyplot.imshow(images)
pyplot.savefig(filename)
I am aware that the Plots pane has a Save button, but I want to save the image programmatically (using Python).
Please advise.
Thanks!
Use plt.imsave() to save the image. Here is the code:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('test.png')
plt.imshow(img)
plt.imsave("myImage.png", img)
plt.show()
I have a simple script that reads and shows images in Matplotlib.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
baseimg = '/home/ahmad/Downloads/mnist/trainingSample/img_0.jpg'
img = mpimg.imread(baseimg)
plt.imshow(img)
plt.show()
It is working on Jupyter Notebook but when I run it in VS Code, it runs but does not show any image. Is there some problem in my code or how to fix it. Thanks
I'm trying to use astropy 2.0.11 with python 2.7.15 to edit a fits image by applying a log stretch to it and change the contrast, and I have't been able to figure it out.
I've been trying to follow the tutorials on the astropy website for opening and manipulating fits files, but I'm wondering if the tutorials will only work for the latest version of astropy and on python 3?
Sorry about the organization of my code. This is prototype code and I'm just trying to test a few things and get this to work.
import time
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import astropy.visualization
from astropy.io import fits
from astropy.utils.data import download_file
from astropy.visualization import astropy_mpl_style
plt.style.use(astropy_mpl_style)
from astropy.utils.data import get_pkg_data_filename
def main():
#My own fits file
#fitsImage = get_pkg_data_filename("C:\\20180807T000456.fits")
fitsImage = download_file('http://data.astropy.org/tutorials/FITS-images/HorseHead.fits', cache=True )
hdu_list = fits.open(fitsImage)
hdu_list.info()
#norm = ImageNormalize(stretch=LogStretch())
image_data = fits.getdata(fitsImage)
print(type(image_data))
print(image_data.shape)
hdu_list.close()
plt.figure()
plt.imshow(image_data, cmap='gray', norm=LogNorm())
plt.colorbar()
# I chose the tick marks based on the histogram above
cbar = plt.colorbar(ticks=[5.e3,1.e4,2.e4])
cbar.ax.set_yticklabels(['5,000','10,000','20,000'])
time.sleep(10)
I am also unable to get the image to display with the plt.imshow()
Any insight would be helpful
You're so close! I ran your code in Python 2.7 and all you need to do is add
plt.show()
before time.sleep(10) (any reason you're including this?) and you get
Also, I don't think you need to include the colorbar and yticklabels, plt.imshow automatically adds the colorbar with the lognorm scale (I commented that section out when I got the image).
I am trying to read a png image in python. The imread function in scipy is being deprecated and they recommend using imageio library.
However, I am would rather restrict my usage of external libraries to scipy, numpy and matplotlib libraries. Thus, using imageio or scikit image is not a good option for me.
Are there any methods in python or scipy, numpy or matplotlib to read images, which are not being deprecated?
With matplotlib you can use (as shown in the matplotlib documentation)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('image_name.png')
And plot the image if you want
imgplot = plt.imshow(img)
You can also use Pillow like this:
from PIL import Image
image = Image.open("image_path.jpg")
image.show()
import matplotlib.pyplot as plt
image = plt.imread('images/my_image4.jpg')
plt.imshow(image)
Using 'matplotlib.pyplot.imread' is recommended by warning messages in jupyter.
If you just want to read an image in Python using the specified
libraries only, I will go with matplotlib
In matplotlib :
import matplotlib.image
read_img = matplotlib.image.imread('your_image.png')
For the better answer, you can use these lines of code.
Here is the example maybe help you :
import cv2
image = cv2.imread('/home/pictures/1.jpg')
plt.imshow(image)
plt.show()
In imread() you can pass the directory .so you can also use str() and + to combine dynamic directories and fixed directory like this:
path = '/home/pictures/'
for i in range(2) :
image = cv2.imread(str(path)+'1.jpg')
plt.imshow(image)
plt.show()
Both are the same.
From documentation:
Matplotlib can only read PNGs natively. Further image formats are supported via the optional dependency on Pillow.
So in case of PNG we may use plt.imread(). In other cases it's probably better to use Pillow directly.
you can try to use cv2 like this
import cv2
image= cv2.imread('image page')
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
I read all answers but I think one of the best method is using openCV library.
import cv2
img = cv2.imread('your_image.png',0)
and for displaying the image, use the following code :
from matplotlib import pyplot as plt
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
Easy way
from IPython.display import Image
Image(filename ="Covid.jpg" size )
I am running into a problem viewing images with astropy. Here is my code:
from astropy.io import fits
import matplotlib.pyplot as plt
hdu_list=fits.open("500m2deep.fit")
image_data=hdu_list[0].data
hdu_list.close()
plt.imshow(image_data,cmap='gray')
plt.show()
Opening the file works fine, I can display the entries of image_data and alike. But the picture doesn't show if I use imshow. It displays the following error:
C:\Python27\lib\site-packages\IPython\core\formatters.py:239: FormatterWarning: Exception in image/png formatter:
FormatterWarning,
If I use, as suggested on some sites, %matplotlib inline, or something similar, this error disappears, but no image shows at all, the program runs, terminates, no picture pops up. I also tried adding something like plt.figure() before imshow() but that doesn't help either.
This happens if I use Spyder, Ipython, or Ipython Notebook. I am using the newest version of python(x,y) for all of this.
How can I display the pictures?
Maybe too late to be a useful solution for you, but mayb someone else can profit.
I recently ran into the same issue on Ubuntu 16.04, python 3.5 and Astropy 1.1.1 using the sample code from the astropy website (first and last line added by me), which is:
#!/usr/bin/python3
import matplotlib.pyplot as plt
from astropy.wcs import WCS
from astropy.io import fits
from astropy.utils.data import get_pkg_data_filename
filename = get_pkg_data_filename('galactic_center/gc_msx_e.fits')
hdu = fits.open(filename)[0]
wcs = WCS(hdu.header)
plt.subplot(projection=wcs)
plt.imshow(hdu.data, vmin=-2.e-5, vmax=2.e-4, origin='lower')
plt.grid(color='white', ls='solid')
plt.xlabel('Galactic Longitude')
plt.ylabel('Galactic Latitude')
plt.show()
It did open the figure window, but did not display any image data.
Updating the astropy version to 1.3 (which also updated numpy to 1.11.3) fixed the issue. Now it works fine.