TransWikia.com

Iterate through each raster for executing an equation to calculate index using Python

Geographic Information Systems Asked on October 6, 2020

I am working with multiple rasters, and in need to execute an equation on each raster, and save them on a date-wise for each raster in an out specified folder. Input Rasters are as follows

"S1A_IW_GRDH_1SDV_20150226T003942_20150226T004007_004787_005F2A_8D84.VV" # out name for this raster 20150226

"S1A_IW_GRDH_1SDV_20150230T003942_20150226T004007_004787_005F2A_8D84.VV" # out name for this raster 20150230.

Below code, I am trying to execute, but its giving error

dates   = []                        # empty lists to start
Rasters = []

for thisFile in os.listdir(r'D:C1'):
    fN, fE = os.path.splitext(thisFile) # break into name and extension
    if fE.upper() == '.TIF':
        Rasters.append(thisFile)

for ThisRaster in Rasters:
    RasterNameSplit = ThisRaster.split('_')
    if len(RasterNameSplit) > 5: # omit non-conforming names
        ThisDateString  = '_'.join(RasterNameSplit[:9]) # Will take only 9th from raster e.g 20150226
        if not ThisDateString in dates:
            dates.append(ThisDateString)

# validate the dates
ValidDates=[]
for ThisDateString in dates:
    L8_red = 'S1A_IW_GRDH_1SDV_{}_20150226T004007_004787_005F2A_8D84.VV.tif'.format(ThisDateString)
    if os.path.exists(os.path.join(r'D:C1',L8_red)):
        ValidDates.append(ThisDateString) # both red and nir bands exist

for ThisDateString in ValidDates:
    L8_red = ''S1A_IW_GRDH_1SDV_{}_20150226T004007_004787_005F2A_8D84.VV.tif''.format(ThisDateString)
    outFile = "out_{}.tif".format(ThisDateString) # make the name unique

# open
redds = gdal.Open(os.path.join(r'D:C1',L8_red))
    
redband = redds.GetRasterBand(1)

red = redband.ReadAsArray()

red = red.astype(np.float64)

#The actual calculation
def SR_pqa(red):
    SR = Abs((red - ( -22.97)) / (- 0.01 - (-22.97)))
    return SR

SR = SR_pqa(red)

#Write the out file
driver = gdal.GetDriverByName("GTiff")
dsOut = driver.Create("out.tif", redds.RasterXSize, redds.RasterYSize, 1, gdal.GDT_Float32)
CopyDatasetInfo(redds,dsOut)
bandOut=dsOut.GetRasterBand(1)
BandWriteArray(bandOut, SR) 

Error message:

AttributeError                            Traceback (most recent call last)
<ipython-input-4-4787ad7a0460> in <module>
     30     # rest of your script
     31 
---> 32 redband = redds.GetRasterBand(1)
     33 
     34 red = redband.ReadAsArray()

AttributeError: 'NoneType' object has no attribute 'GetRasterBand'

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP