python - 将蒙版图像保存为 FITS

标签 python mask astropy fits

我从一些 FITS 文件构建了一个图像,我想将生成的蒙版图像另存为另一个 FITS 文件。这是我的代码:

import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
#from astropy.nddata import CCDData
from ccdproc import CCDData

hdulist1 = fits.open('wise_neowise_w1-MJpersr.fits')
hdulist2 = fits.open('wise_neowise_w2-MJpersr.fits')

data1_raw = hdulist1[0].data
data2_raw = hdulist2[0].data

#   Hide negative values in order to take logs
#   Where {condition}==True, return data_raw, else return np.nan
data1 = np.where(data1_raw >= 0, data1_raw, np.nan)
data2 = np.where(data2_raw >= 0, data2_raw, np.nan)

#   Calculation and image subtraction
w1mag = -2.5 * (np.log10(data1) - 9.0)
w2mag = -2.5 * (np.log10(data2) - 9.0)
color = w1mag - w2mag

##   Find upper and lower 5th %ile of pixels
mask_percent = 5
masked_value_lower = np.nanpercentile(color, mask_percent)
masked_value_upper = np.nanpercentile(color, (100 - mask_percent))

##   Mask out the upper and lower 5% of pixels
##   Need to hide values outside the range [lower, upper]
color_masked = np.ma.masked_outside(color, masked_value_lower, masked_value_upper)
color_masked = np.ma.masked_invalid(color_masked)

plt.imshow(color)
plt.title('color')
plt.savefig('color.png', overwrite = True)
plt.imshow(color_masked)
plt.title('color_masked')
plt.savefig('color_masked.png', overwrite = True)

fits.writeto('color.fits',
             color,
             overwrite = True)
ccd = CCDData(color_masked, unit = 'adu')
ccd.write('color_masked.fits', overwrite = True))

hdulist1.close()
hdulist2.close()

当我使用 matplotlib.pyplot imshow 图像 colorcolor_masked 时,它们看起来和我预期的一样: enter image description here enter image description here 但是,我的两个输出文件 color_masked.fits == color.fits。我想不知何故我不太了解屏蔽过程。谁能看出我哪里出错了?

最佳答案

astropy.io.fits 只处理普通数组,这意味着它只是忽略/丢弃 MaskedArraymask

根据您的用例,您有不同的选择:

保存文件以便其他 FITS 程序识别掩码

其实我认为这是不可能的。但是有些程序(如 DS9)可以处理 NaN,因此您可以将屏蔽值设置为 NaN 以便显示它们:

data_naned = np.where(color_masked.mask, np.nan, color_masked)
fits.writeto(filename, data_naned, overwrite=True)

它们仍然显示为“亮白点”,但不影响色阶。

如果您想更进一步,您可以在将被屏蔽的像素写入文件之前使用卷积过滤器替换它们。不确定 astropy 中是否有一个只替换蒙版像素。

将掩码保存为扩展名以便您可以读回它们

你可以使用 astropy.nddata.CCDData (自 astropy 2.0 起可用)将其保存为带掩码的 FITS 文件:

from astropy.nddata import CCDData

ccd = CCDData(color_masked, unit='adu')
ccd.write('color_masked.fits', overwrite=True)

然后掩码将保存在名为'MASK' 的扩展名中,也可以使用CCDData 读取它:

ccd2 = CCDData.read('color_masked.fits')

CCDData 在正常的 NumPy 操作中表现得像一个掩码数组,但您也可以手动将其转换为掩码数组:

import numpy as np
marr = np.asanyarray(ccd2)

关于python - 将蒙版图像保存为 FITS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46310663/

相关文章:

python - 错误 - 值错误 : invalid literal for int() with base 10: ' '

numpy - 提取一个numpy数组的边界

c - 我怎样才能屏蔽位?

python - 显示具有多个 channel 的拟合图像

python - 裁剪适合文件后坐标不保存

python - 使用字典/表的第一列作为索引/键

python - 比较两个字典的键值并返回一个有差异的新字典

python - 如何使用 plt.gca() 从 matplotlib 散点图中获取 x 和 y 坐标?

python - 与平台无关的方式来获取图片文件夹?

java - 在 Java 中屏蔽字符串的最佳方法是什么?