gdal.Open IndexError: список индексов вне диапазона - PullRequest
0 голосов
/ 16 октября 2018

Я новичок здесь и надеюсь, что найду некоторую помощь.

Я работаю со следующим кодом для вычисления NDVI из Sentinel 2-A

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 голосов
/ 16 октября 2018

Вы правы, вывод glob пуст!Существует проблема с каталогом, если я определю его следующим образом:

# 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

, чтобы проверить его, я решил:не работает, как предполагалось.После 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формат?

...