Monday, June 5, 2017

Hack a FITs Image Header

If you are familiar with the python programming language, you could use the astropy module to view and manipulate fits files. Say you want to view the header of the file 'image.fits', then you do:
from astropy.io.fits import getheader

header = getheader('image.fits') # Load the data
print header                     # Print the header to screen
If you want to modify a particular key of the header, you do:
header['key'] = 'new_key'
View .fits file
My personal favorite GUI for viewing '.fits' files is DS9. Once installed you can view a file by typing ds9 /path/to/file.fits. Alternatively you can just use the menu in the GUI to load the image. Once you load the image in the viewer, you can view the header information by using the very top menu bar and going to 'File -> Display Header'. Unfortunately, I dont believe you can modify the header in DS9.
Modify fits header
For modifying the fits header, I found the easiest is to use astropy (a python package). Since you're using Ubuntu you should be able to download it via apt-get, so hopefully pretty easily. To actually edit the fits header, you can do the following in a python script, or from the interpreter (here's some additional help):
# Import the astropy fits tools
from astropy.io import fits

# Open the file header for viewing and load the header
hdulist = fits.open('yourfile.fits')
header = hdulist[0].header

# Print the header keys from the file to the terminal
header.keys

# Modify the key called 'NAXIS1' to have a value of 100
header['NAXIS1'] = '100'

# Modify the key called 'NAXIS1' and give it a comment
header['NAXIS1'] = ('100','This value has been modified!')

# Add a new key to the header
header.set('NEWKEY','50.5')

# Save the new file
hdulist.writeto('MyNewFile.fits')

# Make sure to close the file
hdulist.close()
You could also throw this in a loop for multiple file manipulation.

No comments: