使用Astropy保存已编辑的.fits文件时,如何保存标题? [英] How to conserve header when saving an edited .fits file with Astropy?

查看:405
本文介绍了使用Astropy保存已编辑的.fits文件时,如何保存标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm editing a .fits file I have in python but I want the header to stay the exact same. This is the code:

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')

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

All this is fine and does exactly what I want it to do except that it does not conserve the header after it saves the new file. Is there any way to fix this such that the original header file is not lost?

推荐答案

首先不要这样做:

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

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

As explained in the warning here, this kind of usage is discouraged (newer versions of the library have a caching mechanism that makes this less inefficient than it used to be, but it's still a problem). This is because the first one returns just the data array from the file, and the latter returns just the header from a file. At that point there's no longer any association between them; it's just a plain Numpy ndarray and a plain Header and their associations with a specific file are not tracked.

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

You can return the full HDUList data structure which represents the HDUs in a file, and for each HDU there's an HDU object associating headers with their arrays.

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

In your example you can just open the file, modify the data array in-place, and then use the .writeto method on it to write it to a new file, or if you open it with mode='update' you can modify the existing file in-place. E.g.

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')

在您的代码中也没有明确的理由

There's also no clear reason for doing this in your code

newim = np.copy(im)

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

Unless you have a specific reason to keep an unmodified copy of the original array in memory, you can just directly modify the original array in-place.

这篇关于使用Astropy保存已编辑的.fits文件时,如何保存标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆