You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中C#使用nom-tam-fits库ReadHDU读取FITS图像失败求助

解决nom-tam-fits中ReadHDU返回null引发空引用异常的问题

问题根源

你先调用了f.Read(),这个方法会一次性读取FITS文件里的所有HDU,读完后文件指针已移动到文件末尾。此时再调用f.ReadHDU(),因无更多HDU可读取,所以返回null——而nom-tam-fits库的设计就是在无更多HDU时返回null,不会抛出异常,这才导致后续访问hdu.Kernel时触发空引用异常。

解决方案

方案1:复用已读取的HDU数组

既然已经通过f.Read()拿到了所有HDU,直接从数组里筛选出ImageHDU类型的元素即可:

Fits f = new Fits(Application.dataPath + "/FITS/SMC-J1634.fits");
BasicHDU[] hdus = f.Read();

Debug.Log("HDUS Length" + hdus.Length.ToString());
for (int i = 0; i < hdus.Length; i++)
{
    Debug.Log(hdus[i].Origin);
    // 检查当前HDU是否为图像类型
    if (hdus[i] is ImageHDU imageHdu)
    {
        int[][] img = (int[][])imageHdu.Kernel;
        // 在这里处理图像数据
        break;
    }
}

方案2:逐个读取HDU(不提前读全部)

如果不需要一次性加载所有HDU,直接循环调用ReadHDU()直到返回null,同时判断类型:

Fits f = new Fits(Application.dataPath + "/FITS/SMC-J1634.fits");
BasicHDU currentHdu;

while ((currentHdu = f.ReadHDU()) != null)
{
    Debug.Log(currentHdu.Origin);
    if (currentHdu is ImageHDU imageHdu)
    {
        int[][] img = (int[][])imageHdu.Kernel;
        // 处理图像数据
        break;
    }
}

注意事项

nom-tam-fits的ReadHDU()方法在无更多HDU可读时返回null是既定设计,并非bug。后续使用该方法时,一定要先判断返回值是否为null,再访问其属性或方法,避免空引用异常。

内容的提问来源于stack exchange,提问作者Destined

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:59:53