How to resolve : "IndexError: band index 1 out of range (not in ())". Raster. Rasterio

How to resolve : "IndexError: band index 1 out of range (not in ())". Raster. Rasterio

我正在尝试绘制 MODIS 数据产品 MOD09GQ。以下是我的代码和控制台输出:

import rasterio
from rasterio.plot import show
import numpy as np
import matplotlib.pyplot as plt

filepath1 = '/Users/sayantanmandal/Projects/MODIS/MOD09GQ.A2010200.h26v06.061.2021166023144.hdf'
with rasterio.open(filepath1) as modis:
    print(modis.profile)
    print(modis.crs)
    show(modis)

控制台输出:

{'driver': 'HDF4', 'dtype': 'float_', 'nodata': None, 'width': 512, 'height': 512, 'count': 0, 'crs': None, 'transform': Affine(1.0, 0.0, 0.0,
       0.0, 1.0, 0.0), 'tiled': False}
None
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~/opt/miniconda3/lib/python3.9/site-packages/rasterio/plot.py in show(source, with_bounds, contour, contour_label_kws, ax, title, transform, adjust, **kwargs)
    101                 # Gather the indexes of the RGB channels in that order
--> 102                 rgb_indexes = [source_colorinterp[ci] for ci in
    103                                (colorinterp.red, colorinterp.green, colorinterp.blue)]

~/opt/miniconda3/lib/python3.9/site-packages/rasterio/plot.py in <listcomp>(.0)
    101                 # Gather the indexes of the RGB channels in that order
--> 102                 rgb_indexes = [source_colorinterp[ci] for ci in
    103                                (colorinterp.red, colorinterp.green, colorinterp.blue)]

KeyError: <ColorInterp.red: 3>

During handling of the above exception, another exception occurred:

IndexError                                Traceback (most recent call last)
/var/folders/bt/kqf88mw53h55m9mj35rkwt6h0000gn/T/ipykernel_3220/591497476.py in <module>
      3     print(modis.profile)
      4     print(modis.crs)
----> 5     show(modis)

~/opt/miniconda3/lib/python3.9/site-packages/rasterio/plot.py in show(source, with_bounds, contour, contour_label_kws, ax, title, transform, adjust, **kwargs)
    109 
    110             except KeyError:
--> 111                 arr = source.read(1, masked=True)
    112     else:
    113         # The source is a numpy array reshape it to image if it has 3+ bands

rasterio/_io.pyx in rasterio._io.DatasetReaderBase.read()

IndexError: band index 1 out of range (not in ())

一开始我以为可能是图像对所选区域没有任何值。但是当我在 QGIS 中打开这个文件时,我确实得到了一张多波段图像。我可能在假设一些事情上是错误的,并且可能会抛出错误的行话,因为这个主题对我来说非常新。知道可能导致此错误的原因是什么吗?谢谢

我不知道你说的数据。

你的数据有多少波段? 如果您查看配置文件结果,结果为 0。
(如果只有一个波段,它应该产生 1。)

您可能唯一的问题是您的数据是否组织成 rasterio 理解的数组。

Rasterio 理解(波段、高度、宽度)。

检查这是什么print(modis.read().shape)

如果出来的不一样,用numpy改一下,让rasterio能看懂。

已解决此问题。

import rioxarray as rxr

modis = rxr.open_rasterio('/Users/sayantanmandal/Projects/MODIS/MOD09GQ. 
        A2010200.h26v06.061.2021166023144.hdf', masked = True)

type(modis)

控制台输出:

xarray.core.dataset.Dataset