使用Python绘制FITS格式图像时坐标轴异常,如何调整坐标轴参数
FITS格式图像绘制问题解决方案
问题描述
我想要绘制FITS格式的图像,预期效果如下:
但实际运行代码后得到的结果如下图所示:
我尝试通过imshow修改坐标轴参数,但没有获得更好的效果,当前使用的代码如下:
import matplotlib.pyplot as plt from astropy.visualization import astropy_mpl_style plt.style.use(astropy_mpl_style) from astropy.utils.data import get_pkg_data_filename from astropy.io import fits image_file = get_pkg_data_filename('Or.fits') fits.info(image_file) image_data = fits.getdata(image_file, ext=0) print(image_data.shape) plt.figure() plt.imshow(image_data, cmap='gray') plt.colorbar()
解决方案
问题主要由三个常见原因导致,可按以下要求修改代码:
- 调整imshow的
origin参数为lower,适配FITS格式默认左下角为坐标原点的规则,解决图像上下颠倒问题 - 引入astropy的可视化拉伸工具,适配天文图像的大动态范围,解决灰度显示不清晰问题
- 如果FITS文件头包含WCS天球坐标信息,可通过WCS坐标系投影绘制,让坐标轴显示正确的天球坐标
修改后的可直接运行代码如下:
import matplotlib.pyplot as plt from astropy.visualization import astropy_mpl_style, ZScaleInterval, AsinhStretch, ImageNormalize from astropy.utils.data import get_pkg_data_filename from astropy.io import fits from astropy.wcs import WCS plt.style.use(astropy_mpl_style) image_file = get_pkg_data_filename('Or.fits') # 同时读取数据和头文件 with fits.open(image_file) as hdul: image_data = hdul[0].data # 读取WCS坐标信息(如果存在) wcs = WCS(hdul[0].header) # 配置适配天文图像的归一化参数 norm = ImageNormalize(image_data, interval=ZScaleInterval(), stretch=AsinhStretch()) # 如果不需要WCS坐标,可去掉subplot的projection参数 plt.figure() ax = plt.subplot(projection=wcs) im = ax.imshow(image_data, cmap='gray', norm=norm, origin='lower') plt.colorbar(im) # 配置坐标轴标签 ax.set_xlabel('赤经 (J2000)') ax.set_ylabel('赤纬 (J2000)') plt.show()
补充说明
如果不需要显示天球坐标,只需要像素坐标,去掉代码中WCS相关的部分,仅保留origin='lower'和归一化参数即可达到预期效果。
内容的提问来源于stack exchange,提问作者cacas
相关产品推荐
相关产品推荐

