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

Peter Erwin erwin@mpe.mpg...
Wed Apr 8 07:27:51 CDT 2009


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

[snip]

> 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- 
bones
description of this is in the pyfits manual ("Create FITS Images from  
Scratch",
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  
structure,
perhaps as a list of lists, or perhaps as a Python array.  You'll need  
to
go into this existing code and find out what the internal format is;  
then
you'll have some idea of how to convert it to a numpy array.  It might  
be
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  
"numpy"
wherever you see "numarray" in the text.  The manual also has problems  
with
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  
array,
and then you can write it as a FITS file.

cheers,

Peter

=============================================================
Peter Erwin                   Max-Planck-Insitute for Extraterrestrial
erwin@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