如何使用pickle保存和加载FITS文件的头信息?

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

背景

我想使用Python将FITS数据的头信息转换为字典并保存为二进制文件。当然,二进制数据必须稍后加载。

问题

无法加载保存为pickle文件的FITS头数据字典,我想知道如何解决这个问题。

这是最小的可重现示例和错误消息。

import astropy.io.fits as fits
import numpy as np
import os
import pickle

cwd = os.getcwd()
fits_path = os.path.join(cwd, 'hmi.M_45s.20200101_020130_TAI.2.magnetogram.fits')
path = os.path.join(cwd, 'demo.pkl')
hdul = fits.open(fits_path)
hdul.verify('silentfix')
print(hdul.info())
# hdul[0] is often the primary Header Data Unit (HDU) and hdul[1] is the first extension HDU
hdr = dict(hdul[1].header)
hdr['COMMENT'] = str(hdr['COMMENT'])
img  = np.transpose(hdul[1].data)
hdul.close()

with open(path, 'wb') as f:
    pickle.dump(hdr, f)
with open(path, 'rb') as f:
    hdr_loaded = pickle.load(f)
Filename: cwd\hmi.M_45s.20200101_020130_TAI.2.magnetogram.fits
No.    Name      Ver    Type      Cards   Dimensions   Format
  0  PRIMARY       1 PrimaryHDU       6   ()
  1  COMPRESSED_IMAGE    1 CompImageHDU    114   (4096, 4096)   int32
None
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[49], line 21
     19     pickle.dump(hdr, f)
     20 with open(path, 'rb') as f:
---> 21     hdr_loaded = pickle.load(f)

TypeError: __new__() missing 1 required positional argument: 'table_header'

在我的环境(python 3.9.18)中,转储和加载

img
工作正常,但对于
hdr
则不然。

您可以从这里输入

下载太阳动力观测站(SDO)上的日震和磁成像仪(HMI)提供的FITS数据
hmi.M_45s[2020.01.01_02:01:30_TAI]

到“记录集”并在“通知”中提供您的电子邮件地址。然后点击“检查参数”并“提交”。稍后将显示下载数据的链接。

我搜索的内容

我猜测该问题与 FITS 数据有关。我还发现了类似的问题Pickling an astropy.io.fits.CompImageHDU失败,但我不知道如何修复我的代码。

python pickle astropy fits
1个回答
0
投票

让我简单分享一下我是如何避免这个错误的。

我查看了

hdr
中值的数据类型,发现关键字“HISTORY”的数据类型为
'astropy.io.fits.header._HeaderCommentaryCards'
的值。

.
.
CAMERA <class 'int'>
BUNIT <class 'str'>
ORIGIN <class 'str'>
CONTENT <class 'str'>
QUALITY <class 'int'>
QUALLEV1 <class 'int'>
HISTORY <class 'astropy.io.fits.header._HeaderCommentaryCards'>
COMMENT <class 'str'>
BLD_VERS <class 'str'>
HCAMID <class 'int'>
SOURCE <class 'str'>
.
.

看来“COMMENT”最初采用具有相同数据类型的值。

我删除了具有此数据类型的项目,并且保存和加载过程有效。

这个解决方案看起来有点作弊,因为我只是丢弃了造成麻烦的部分。我这样做是因为问题需要快速解决,而且我现在不需要“历史”信息。

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