使用Astropy保存编辑的.fits文件时如何保存标题?

问题描述 投票:0回答:1

我正在编辑我在python中拥有的.fits文件,但我希望标题保持完全相同。这是代码:

import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt

# read in the fits file
im = fits.getdata('myfile.fits')
header = fits.getheader('myfile.fits')

ID = 1234

newim = np.copy(im)

newim[newim == ID] = 0
newim[newim == 0] = -99
newim[newim > -99] = 0
newim[newim == -99] = 1

plt.imshow(newim,cmap='gray', origin='lower')
plt.colorbar()


hdu = fits.PrimaryHDU(newim)
hdu.writeto('mynewfile.fits')

所有这些都很好,并且完全按照我想要的去做,只是它在保存新文件后不保留标题。有什么方法可以解决此问题,以使原始头文件不会丢失?

python astropy fits
1个回答
0
投票

首先不要这样做:

im = fits.getdata('myfile.fits')
header = fits.getheader('myfile.fits')

如警告here中所述,不鼓励使用这种方法(较新版本的库具有缓存机制,该机制使效率比以前降低了,但仍然是一个问题)。这是因为第一个仅从文件返回数据数组,而第二个仅从文件返回标题。到那时,它们之间不再有任何关联。它只是一个普通的Numpy ndarray和一个普通的Header,并且不会跟踪它们与特定文件的关联。

[您可以返回完整的HDUList数据结构,该结构表示文件中的HDU,并且对于每个HDU,都有一个HDU对象将标头与其数组相关联。

在您的示例中,您可以打开文件,就地修改数据数组,然后在其上使用HDUList方法将其写入新文件,或者如果您使用.writeto打开它,则可以修改现有文件就位。例如:

mode='update'

也没有明确的理由在您的代码中执行此操作

hdul = fits.open('old.fits')
# modify the data in the primary HDU; this is just an in-memory operation and will not change the data on disk
hdul[0].data +=1
hdul.writeto('new.fits')

除非有特殊原因要在内存中保留原始数组的未修改副本,否则可以直接就地修改原始数组。

© www.soinside.com 2019 - 2024. All rights reserved.