Re-order 张 FITS header

Re-order cards in a FITS header

我正在尝试修改 FITS 图像并相应地修改其 header,然后将其保存到新的 FITS 文件中

from astropy.io import fits
from astropy.utils.data import get_pkg_data_filename

# Open FITS file
image_file = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits')
cube = fits.open(image_file)[0]

# Modify the cube
cube.header.remove('NAXIS2')

# ...

cube.header['NAXIS2'] = 5

# Save the new FITS file
hdu = fits.PrimaryHDU(cube.data)
hdu.header = cube.header
hdu.writeto('new.fits', overwrite=True)

但是,这个returns出现如下错误:

VerifyError: 
Verification reported errors:
HDU 0:
    'NAXIS2' card at the wrong place (card 159).
    'EXTEND' card at the wrong place (card 160).
Note: astropy.io.fits uses zero-based indexing.

如何在 header 中以正确的顺序放置卡片?或者有没有办法直接在正确的地方设置卡片?


注意:这显然不是修改 header 中字段的最佳方法,但它是重现我遇到的错误的最短示例。 我不想知道如何修改字段,我想知道如何在 header 中的正确位置获取新字段。

Header class 有一个 insert 功能,可以在给定卡片之前或之后添加卡片。

cube.header.insert('EXTEND', ('NAXIS2', 5))

将在 'EXTEND' 卡片之前添加价值 5'NAXIS2' 卡片。

通过使用 after=True 关键字,还可以在给定卡片之后立即设置新卡片。所以做同样事情的另一种方法是:

cube.header.insert('NAXIS1', ('NAXIS2', 5), after=True)

通过此修改,hdu.writeto(...) 不再引发错误。