Astronomy example 1

Downloading images and writing FITS files

For examples, documentation, tutorials, etc, see Astropy at

In [1]:
import scipy as sp

import urllib                  # For retrieving an image from a URL

import matplotlib as mpl       # As of July 2017 Bucknell computers use v. 2.x 
import matplotlib.pyplot as plt

# Following is an Ipython magic command that puts figures in the  notebook.
# For figures in separate windows, comment out following line and uncomment
# the next line
# Must come before defaults are changed.
%matplotlib notebook

# As of Aug. 2017 reverting to 1.x defaults.
# In 2.x text.ustex requires dvipng, texlive-latex-extra, and texlive-fonts-recommended, 
# which don't seem to be universal
# See'classic')
# M.L. modifications of matplotlib defaults using syntax of v.2.0 
# More info at
# Changes can also be put in matplotlibrc file, or effected using mpl.rcParams[]
plt.rc('figure', figsize = (6, 4.5))            # Reduces overall size of figures
plt.rc('axes', labelsize=16, titlesize=14)
plt.rc('figure', autolayout = True)             # Adjusts supblot parameters for new size

#import matplotlib.image as mpimg
from PIL import Image
from import fits
from import download_file
from astropy.visualization import astropy_mpl_style

Retrieve and display a JPG image

  • Download image from the web, and store it as a local file
  • "Open" the image
  • Determine the size
  • Display
In [2]:
image ='Hs-2009-14-a-web.jpg')
xsize, ysize = image.size

print("Image size: {} x {}".format(xsize, ysize))
plt.grid(color = 'w')
Image size: 400 x 232

Separate colors

In [3]:
r, g, b = image.split()
r_data = sp.array(r.getdata()) # data is now an array of length ysize*xsize
g_data = sp.array(g.getdata())
b_data = sp.array(b.getdata())
In [4]:
r_data = r_data.reshape(ysize, xsize)
g_data = g_data.reshape(ysize, xsize)
b_data = b_data.reshape(ysize, xsize)

plt.grid(color = 'b')
plt.imshow(r_data, cmap='Greys');

plt.grid(color = 'b')
plt.imshow(g_data, cmap='Greys');

plt.grid(color = 'b')
plt.imshow(b_data, cmap='Greys');