[AstroPy] Coding in Python to Read/Write a fits file.

Peter Erwin erwin at mpe.mpg.de
Wed Apr 8 08:27:51 EDT 2009

On Apr 8, 2009, at 1:50 PM, Wayne Watson wrote:


> This is close to what I'm looking for. That is, executable Python  
> code,
> and not interactive code one enters line by line. Right now I'm  
> lacking
> a way to read, say, a jpg, fits, or gif file, and convert it to fits.
> I'm also lacking a way to convert the internal image format to fits.  
> The
> latter is very important. The internal format is simple. An image
> 640x480 pixels and 8-bits deep, b/w. jpg, etc. is already done for
> writing the internal file.  For fits files, I'd like to write very
> simple headers that have, say, lat/long of observer, a time stamp, and
> some other assorted items.

*Writing* a FITS file using pyfits is not very difficult.  The bare- 
description of this is in the pyfits manual ("Create FITS Images from  
on p.10, I think).  Since you're working with images, you need to have  
the image
data as a 2D numpy array (the example on p.10 uses a 1-D array).

(Pyfits manual available here: http://www.stsci.edu/resources/software_hardware/pyfits 

Since you say that the existing Python code handles the "internal image
format", then it must somewhere have the data in a Python data  
perhaps as a list of lists, or perhaps as a Python array.  You'll need  
go into this existing code and find out what the internal format is;  
you'll have some idea of how to convert it to a numpy array.  It might  
as simple as
    image_for_fits = numpy.array(image_oldformat)

Since your data is 8 bit, it would make sense to use a numpy *integer*
array; I believe pyfits is smart enough to save the result as an integer
FITS file.

The Pyfits manual also explains how to add header keywords (see the
chapter on Headers).

(Note that the Pyfits manual is still based on version 1.0, and so it  
refers to
"numarray" instead of "numpy"; you should just mentally substitute  
wherever you see "numarray" in the text.  The manual also has problems  
the chapter numbers, which don't agree between the Table of Contents and
the actual main text.  But this is a minor issue.)

As for jpeg, gif, etc. -- you have to find some Python code that can  
read those
formats (Python Imaging Library, perhaps?).  Once they've been read  
in, however,
you should be able to convert the resulting data structure to a numpy  
and then you can write it as a FITS file.



Peter Erwin                   Max-Planck-Insitute for Extraterrestrial
erwin at mpe.mpg.de              Physics, Giessenbachstrasse
tel. +49 (0)89 30000 3695     85748 Garching, Germany
fax  +49 (0)89 30000 3495     http://www.mpe.mpg.de/~erwin

More information about the AstroPy mailing list