How to save jpegs of FITS files?

https://docs.astropy.org/en/stable/generated/examples/io/plot_fits-image.html#sphx-glr-generated-examples-io-plot-fits-image-py

I have a program that follows closely the link above and I want to saves the FITS matplotlib image as a jpeg file so when I work with my real FITS files later on, I can save them as jpegs.

I tried to save it the usual way:

plt.savefig("output.jpg")

However, after doing this, I find that the output does not look anything like the image
[![It is a completely blank image][1]][1]

Any suggestions would be greatly appreciated.
[1]: https://i.stack.imgur.com/XNRlp.jpg

Probably plt.show() is clearing the image. Try changing the order to call savefig first.

I tried both solutions in the checked answer in the link you posted, but no luck.

import matplotlib.pyplot as plt
from astropy.visualization import astropy_mpl_style
plt.style.use(astropy_mpl_style)

from astropy.utils.data import get_pkg_data_filename
from astropy.io import fits

image_file = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits')

fits.info(image_file)

image_data = fits.getdata(image_file, ext=0)

print(image_data.shape)

plt.figure()
plt.savefig("output.jpg") #save as jpg
plt.imshow(image_data, cmap='gray')
plt.colorbar()
...
print(image_data.shape)

plt.imshow(image_data, cmap='gray')
plt.colorbar()
plt.savefig("output.jpg") #save as jpg

This order (without plt.figure()) works here. What are you using to run it? If it’s something like Jupyter, maybe it does implicit plt.show() and clears it?

2 Likes

I used Jupyter Notebook to run it. Excluding plt.figure() resolved the issue.

Do you know how to make the output file larger and the axes more readable? I tried

#plt.figure()
figure = plt.gcf()


figure.set_size_inches(20, 15)

plt.imshow(image_data, cmap='gray')
plt.colorbar()
plt.savefig("output.jpg", dpi=300) #save as jpg

But that seems to make the axes labels so small

1 Like