我正在处理一个我没写过的NDVI脚本,我正试图让它运行。它遇到的问题是旧的类型错误:无法隐式地将字节对象转换为str。直到昨天我才从未见过结构包,经过相当多的研究,我一般都理解这个概念,但并不完全具体。
我正在处理tiff文件并尝试创建NDVI图像。这是代码示例。如果有人能帮助我理解这一点并帮助我解决问题,我将非常感激!
## The function which loops through the input image and
## calculates the output NDVI value to be outputted.
def calcNDVI(self, filePath, outFilePath):
# Open the inputted dataset
dataset = gdal.Open(filePath, gdal.GA_ReadOnly)
# Check the dataset successfully opened
if dataset is None:
print("The dataset could not be opened")
sys.exit(-1)
# Create the output dataset
outDataset = self.createOutputImage(outFilePath, dataset)
# Check the datasets successfully created
if outDataset is None:
print("Could not create output image")
sys.exit(-1)
# Get hold of the RED and NIR image bands from the image
# Note that the image bands are hard coded to handle
# landsat 8 TIFFs that produce separate images per band
# which are mosaiced together where
# Red = band 1 and NIR = band 2
red_band = dataset.GetRasterBand(1)
nir_band = dataset.GetRasterBand(2)
# Retrieve the number of lines within the image
numLines = red_band.YSize
# Loop through each line in turn:
for line in range(numLines):
# Define variable for output line
outputLine = ''
# Read in data for the current line from the
# image band representing the red wavelength
red_scanline = red_band.ReadRaster(0, line, red_band.XSize, 1, \
red_band.XSize, 1, gdal.GDT_Float32)
# Unpack the line of data to be read as floating point data
red_tuple = struct.unpack('f' * red_band.XSize, red_scanline)
# Read in data for the current line from the
# image band representing the NIR wavelength
nir_scanline = nir_band.ReadRaster(0, line, nir_band.XSize, 1, \
nir_band.XSize, 1, gdal.GDT_Float32)
# Unpack the line of data to be read as floating point data
nir_tuple = struct.unpack('f' * nir_band.XSize, nir_scanline)
# Loop through the columns within the image
for i in range(len(red_tuple)):
# Calculate the NDVI for the current pixel
ndvi_lower = (nir_tuple[i] + red_tuple[i])
ndvi_upper = (nir_tuple[i] - red_tuple[i])
ndvi = 0
# Be careful of zero divide
if ndvi_lower == 0:
ndvi = 0
else:
ndvi = ndvi_upper/ndvi_lower
# Add the current pixel to the output line
outputLine = outputLine + struct.pack('f', ndvi)
# Write the completed line to the output image
outDataset.GetRasterBand(1).WriteRaster(0, line, red_band.XSize, 1, \
outputLine, buf_xsize=red_band.XSize, buf_ysize=1, buf_type = gdal.GDT_Float32)
# Delete the output line following write
del outputLine
运行时的输出:
outputLine = outputLine + struct.pack('f', ndvi)
TypeError: Can't convert 'bytes' object to str implicitly
再一次,非常感谢任何帮助!此外,本网站和其他地方有关于此特定结构错误的几个问题,但没有具体处理图像的任何问题。
谢谢!
答案 0 :(得分:0)
好的我找到了答案,如果有人有类似的问题,这就熬夜了!导致错误的输出行:
outputLine = outputLine + struct.pack('f', ndvi)
可以通过一个非常简单的解决方案来解决:
outputLine = outputLine + str(struct.pack('f', ndvi))
Python无法隐式转换字节对象,但您可以明确地进行转换。