Search code examples
pythonastropyfits

astropy FITS with multiple headers


I'm trying to create a FITS file in Python but I appear to be having problems when compiling the headers and PrimaryHDU together.

I've made a simple example which will give the error that I'm getting:

import numpy as np
from astropy.io import fits

a = np.ones([5,5])
hdu = fits.PrimaryHDU(a)
hdr = fits.Header()
hdr['NPIX1'] = 60
hdr['NPIX2'] = 60
hdr['CRPIX1'] = 0
hdr['CRPIX2'] = 0
primary_hdu = fits.PrimaryHDU(header=hdr)
hdul = fits.HDUList([primary_hdu, hdu])
hdul.writeto('table4.fits')

When running this code, I get the following error:

VerifyError: Verification reported errors: HDUList's element 1 is not an extension HDU. Note: astropy.io.fits uses zero-based indexing.

I've seen some posts which claim this could be to do with the PrimaryHDU needing to be the first in the HDUList when exporting but looking at my code, I believe I'm doing that already.

Any help would be greatly appreciated here, thanks.


Solution

  • Notice the error message:

    VerifyError: Verification reported errors: HDUList's element 1 is not an extension HDU. Note: astropy.io.fits uses zero-based indexing.

    The second item in the HDUList is also a PrimaryHDU, which is not a valid extension HDU (Primary here essentially means first and unique).

    Make that HDU an ImageHDU, and things will work:

    import numpy as np
    from astropy.io import fits
    
    a = np.ones([5,5])
    hdu = fits.ImageHDU(a)     # Don't use a `PrimaryHDU` here
    hdr = fits.Header()
    hdr['NPIX1'] = 60
    hdr['NPIX2'] = 60
    hdr['CRPIX1'] = 0
    hdr['CRPIX2'] = 0
    primary_hdu = fits.PrimaryHDU(header=hdr)
    hdul = fits.HDUList([primary_hdu, hdu])
    hdul.writeto('table4.fits')