将屏蔽图像保存为FITS

时间:2017-09-19 22:35:17

标签: 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。我想我不太理解正确的掩蔽过程。谁能看到我出错的地方?

1 个答案:

答案 0 :(得分:2)

astropy.io.fits仅处理普通数组,这意味着它只会忽略/丢弃mask的{​​{1}}。

根据您的使用情况,您有不同的选择:

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

我实际上并不认为这是可能的。但是像DS9这样的程序可以处理MaskedArray,因此你可以将屏蔽值设置为NaN以显示它们:

NaN

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

如果您想更进一步,可以先使用卷积滤镜替换屏蔽像素,然后再将其写入文件。不确定data_naned = np.where(color_masked.mask, np.nan, color_masked) fits.writeto(filename, data_naned, overwrite=True) 中是否只有一个只替换了屏蔽像素。

将掩码保存为扩展名,以便您可以将其读回

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

astropy

然后,掩码将保存在名为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') 在正常NumPy操作中的行为类似于蒙版数组,但您也可以手动将其转换为蒙版数组:

CCDData
相关问题