编辑配合标题

此示例说明如何使用编辑配合标头中的值 astropy.io.fits .

By: Adrian Price-Whelan

许可证:BSD

from astropy.io import fits

下载FITS文件:

from astropy.utils.data import get_pkg_data_filename

fits_file = get_pkg_data_filename('tutorials/FITS-Header/input_file.fits')

查看FITS文件的内容

fits.info(fits_file)
Filename: /home/bk/.astropy/cache/download/url/519010d87325a22575dc1d16f3a05d26/contents
No.    Name      Ver    Type      Cards   Dimensions   Format
  0  PRIMARY       1 PrimaryHDU       7   (100, 100)   float64
  1                1 ImageHDU         7   (128, 128)   float64

看看这两个扩展名的标题:

print("Before modifications:")
print()
print("Extension 0:")
print(repr(fits.getheader(fits_file, 0)))
print()
print("Extension 1:")
print(repr(fits.getheader(fits_file, 1)))
Before modifications:

Extension 0:
SIMPLE  =                    T / conforms to FITS standard
BITPIX  =                  -64 / array data type
NAXIS   =                    2 / number of array dimensions
NAXIS1  =                  100
NAXIS2  =                  100
EXTEND  =                    T
OBJECT  = 'KITTEN  '

Extension 1:
XTENSION= 'IMAGE   '           / Image extension
BITPIX  =                  -64 / array data type
NAXIS   =                    2 / number of array dimensions
NAXIS1  =                  128
NAXIS2  =                  128
PCOUNT  =                    0 / number of parameters
GCOUNT  =                    1 / number of groups

astropy.io.fits 提供了一个面向对象的接口,用于读取FITS文件并与之交互,但对于小型操作(如本例)来说,使用 convenience functions .

若要编辑扩展名0的标头中的单个标头值,请使用 setval() 功能。例如,将OBJECT关键字设置为“M31”:

fits.setval(fits_file, 'OBJECT', value='M31')

在没有额外参数的情况下,这将修改扩展名0的头,但可以使用 ext 关键字参数。例如,我们可以指定扩展名1:

fits.setval(fits_file, 'OBJECT', value='M31', ext=1)

这也可以用来创建一个新的关键字-值对(FITS行话中的“card”):

fits.setval(fits_file, 'ANEWKEY', value='some value')

同样,这对于一次性修改很有用,但对于在同一文件中编辑多个标题之类的操作来说可能效率低下,因为 setval() 每次调用时加载整个文件。要进行多次修改,最好加载文件一次:

with fits.open(fits_file, 'update') as f:
    for hdu in f:
        hdu.header['OBJECT'] = 'CAT'

print("After modifications:")
print()
print("Extension 0:")
print(repr(fits.getheader(fits_file, 0)))
print()
print("Extension 1:")
print(repr(fits.getheader(fits_file, 1)))
After modifications:

Extension 0:
SIMPLE  =                    T / conforms to FITS standard
BITPIX  =                  -64 / array data type
NAXIS   =                    2 / number of array dimensions
NAXIS1  =                  100
NAXIS2  =                  100
EXTEND  =                    T
OBJECT  = 'CAT     '
ANEWKEY = 'some value'

Extension 1:
XTENSION= 'IMAGE   '           / Image extension
BITPIX  =                  -64 / array data type
NAXIS   =                    2 / number of array dimensions
NAXIS1  =                  128
NAXIS2  =                  128
PCOUNT  =                    0 / number of parameters
GCOUNT  =                    1 / number of groups
OBJECT  = 'CAT     '

Total running time of the script: (0分1.437秒)

Gallery generated by Sphinx-Gallery