我是gdal的新手。我正在尝试计算NDVI。但我有一些问题,所以我尝试做一些简单的测试,但是 “dataset.GetRasterBand(1).WriteRaster(...)”不起作用,这导致空图像
我的代码是:
#A function to create the output image
def createOutputImage(self, outFilename, rb_ds):
# Define the image driver to be used
# This defines the output file format TIF
driver = gdal.GetDriverByName( "Gtiff" )
# Check that this driver can create a new file.
metadata = driver.GetMetadata()
if metadata.has_key(gdal.DCAP_CREATE) and metadata[gdal.DCAP_CREATE] == 'YES':
print 'Driver GTiff supports Create() method.'
else:
print 'Driver GTIFF does not support Create()'
sys.exit(-1)
# Get the spatial information from the input file
geoTransform = rb_ds.GetGeoTransform()
geoProjection = rb_ds.GetProjection()
# Create an output file of the same size as the inputted
# image, but with only 1 output image band.
newDataset = driver.Create( outFilename, rb_ds.RasterXSize, \
rb_ds.RasterYSize, 1, gdal.GDT_Float32)
# Define the spatial information for the new image.
newDataset.SetGeoTransform(geoTransform)
newDataset.SetProjection(geoProjection)
return newDataset
# The function which loops through the input image and
# calculates the output NDVI value to be outputted.
def calcNDVI(self, red_band, NIR_band, outFilePath):
# Open the red band dataset
red_band_dataset = gdal.Open( red_band, gdal.GA_ReadOnly )
nir_band_dataset = gdal.Open( NIR_band, gdal.GA_ReadOnly )
# Check the dataset was successfully opened
if (red_band_dataset is None) or (nir_band_dataset is None):
print "The datasets could not openned"
sys.exit(-1)
# Create the output dataset
outDataset = self.createOutputImage(outFilePath, red_band_dataset)
# Check the datasets was successfully created.
if outDataset is None:
print 'Could not create output image'
sys.exit(-1)
# Load de two band
red = red_band_dataset.GetRasterBand(1)
for line in range(red.YSize):
# read a line
red_scanline = red.ReadRaster(0, line, red.XSize, 1, red.XSize, 1, gdal.GDT_Float32)
outDataset.GetRasterBand(1).WriteRaster(0,line,red.XSize, 1, red_scanline, buf_xsize=red.XSize,buf_ysize=1, buf_type=gdal.GDT_Float32)
del outputLine
print "NDVI calculate correct"
我是从红色(图像)到outputDataset的行的复制行,但我有一个空图像
由于
答案 0 :(得分:0)
如果没有提供输出(“NDVI计算正确”打印吗?),看起来这个程序在尝试del outputLine
时会抛出错误,因为outputLine
未声明。此崩溃将导致创建的图像写入一行,否则tiff将为空白。