TransWikia.com

Deleting GDAL created raster

Geographic Information Systems Asked by D_C on June 22, 2021

I am simply trying to delete a TIF that I created with GDAL. I have tried, simply, to use shutil which errors with:

NotADirectoryError: [WinError 267] The directory name is invalid:
‘T:/p003M01p0001/extent_files/t215_E.tif’

My first attempt was to use:

filename = out_loc + '/' + temp_tif
driver = ogr.GetDriverByName("GTiff")
if os.path.exists(filename):
    driver.DeleteDataSource(filename)

but this just resulted in a None driver for some reason (AttributeError: ‘NoneType’ object has no attribute ‘DeleteDataSource’). This proves os recognizes the file exists (so why does shutil not work?). I have confirmed the existence of the GTiff driver using:

driver_list = []
for i in range(gdal.GetDriverCount()):
    driver = gdal.GetDriver(i)
    driver_list.append(driver.GetDescription())
    print(gdal.GetDriver(i).ShortName)

I am a bit perplexed that ogr couldn’t delete it, but even more perplexed on why shutil doesn’t recognize that it exists. There must be something I am doing wrong creating the tiff.

The overall purpose of the following code is to get the boundary of valid TIF values.

Current code:

from osgeo import gdal, osr
from osgeo.gdalconst import GA_Update
import ogr
from core.gdal_functions import GDALFunc

input_tif = 'T:/p003M01p0001/t215.tif'
out_loc = 'T:/p003M01p0001/extent_files'
copy_tif = out_loc + '/t215_E.tif'
temp_tif = out_loc + '/shaded.tif'
shp = out_loc + '/t215_Ex.shp'

# get copy of tif
src_ds = gdal.Open(input_tif, gdal.GA_ReadOnly)
srs = osr.SpatialReference()
srs.ImportFromWkt(src_ds.GetProjectionRef())
dst_ds = src_ds.GetDriver().CreateCopy(copy_tif, src_ds, 0)
dst_ds = None
src_ds = None

# Edit data to remove 0 to turn it into nodata
nodata = 0
ras = gdal.Open(copy_tif, GA_Update)
for i in range(1, ras.RasterCount + 1):
    ras.GetRasterBand(i).SetNoDataValue(nodata)
ras = None

# create temp tif of where actual values exist
drv = ogr.GetDriverByName('ESRI Shapefile')
outfile = drv.CreateDataSource(shp)

outlayer = outfile.CreateLayer('polygonized raster', srs=srs)
newField = ogr.FieldDefn('DN', ogr.OFTReal)
outlayer.CreateField(newField)
command = 'python C:/Users/david/AppData/Local/Programs/Python/Python38/Lib/site-packages/osgeo/scripts/gdal_calc.py ' 
          '-A {infile} --A_band=1 --outfile {outfile} --calc="(A>0)*1" --quiet'.format(infile=copy_tif, outfile=temp_tif)

process = subprocess.Popen(command, shell=True)
while process.poll() is None:
    time.sleep(0.5)

#create polygon extent
tif = gdal.Open(temp_tif)
band = tif.GetRasterBand(1)
gdal.Polygonize(band, None, outlayer, 0)
outfile = None
tif = None


shutil.rmtree(copy_tif)

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