gdal.Open IndexError:列表索引超出范围

时间:2018-10-16 08:27:07

标签: python gdal

我是新来的,希望能找到帮助。

我使用以下代码从Sentinel 2-A计算NDVI

import glob
import numpy as np
from osgeo import gdal 

in_dir = 'C:\\temp\\'

# Search directory for desired bands
red_file = glob.glob(in_dir + '**B04.jp2') # red band
nir_file = glob.glob(in_dir + '**B08.jp2') # nir band

# Define a function to calculate NDVI using band arrays for red, NIR bands
def ndvi(red, nir):
    return ((nir - red)/(nir + red))
    #return (NIR.astype(float) - RED.astype(float)) / (NIR+RED)


# Open each band using gdal
red_link = gdal.Open(red_file[0])
nir_link = gdal.Open(nir_file[0])

# read in each band as array and convert to float for calculations
red = red_link.ReadAsArray().astype(np.float)
nir = nir_link.ReadAsArray().astype(np.float)

# Call the ndvi() function on red, NIR bands
ndvi2 = ndvi(red, nir)

# Create output filename based on input name
outfile_name = red_file[0].split('_B')[0] + '_NDVI.tif'

x_pixels = ndvi2.shape[0] # number of pixels in x
y_pixels = ndvi2.shape[1] # number of pixels in y

# Set up output GeoTIFF
driver = gdal.GetDriverByName('GTiff')

# Create driver using output filename, x and y pixels, # of bands, and datatype
ndvi_data = driver.Create(outfile_name,x_pixels, y_pixels, 1,gdal.GDT_Float32)

# Set NDVI array as the 1 output raster band
ndvi_data.GetRasterBand(1).WriteArray(ndvi2)

# Setting up the coordinate reference system of the output GeoTIFF
geotrans=red_link.GetGeoTransform() # Grab input GeoTranform information
proj=red_link.GetProjection() # Grab projection information from input file

# now set GeoTransform parameters and projection on the output file
ndvi_data.SetGeoTransform(geotrans)
ndvi_data.SetProjection(proj)
ndvi_data.FlushCache()
ndvi_data=None
###############################################################################

我收到以下IndexError:

Traceback (most recent call last):
  File "C:\temp\NDVI3.py", line 31, in <module>
    red_link = gdal.Open(red_file[0])
IndexError: list index out of range

有人知道如何解决此错误吗?可能是我的GDAL版本无法识别jp2格式吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您说得对,glob的输出为空!如果我这样定义目录,则会出现e问题:

# Search directory for desired bands
red_file = glob.glob(in_dir + '**B04.jp2') # red band
nir_file = glob.glob(in_dir + '**B08.jp2') # nir band

要测试它,我用以下方法解决了它:

red_file = glob.glob('C:\\temp\\T32TMT_20180326T103021_B04_10m.jp2') # red band
nir_file = glob.glob('C:\\temp\\T32TMT_20180326T103021_B08_10m.jp2') # nir band

但是现在我得到一个问题,gdal.Open不能按预期工作。在gdal.Open之后,又出现了一个空列表,出现在以下错误消息中:

Traceback (most recent call last):
  File "C:\temp\NDVI3.py", line 52, in <module>
    red = red_link.ReadAsArray().astype(np.float)
AttributeError: 'NoneType' object has no attribute 'ReadAsArray'

现在我再问一遍,是否可能是我的GDAL版本(2.2.3)无法识别jp2格式?