Skip to content

Instantly share code, notes, and snippets.

@maphew
Created Jun 24, 2021
Embed
What would you like to do?
Compress to Cloud Geotiff stub in ArcGIS Pro python toolbox (rename to *.pyt to get Pro to recognize it)
# -*- coding: utf-8 -*-
import arcpy
from osgeo import gdal
gdal.UseExceptions()
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "Toolbox"
self.alias = "toolbox"
# List of tool classes associated with this toolbox
self.tools = [Tool]
class Tool(object):
def __init__(self):
"""Gdal to Cloud Geotiff translator."""
self.label = "GdalToCog"
self.description = "Compress a raster to Cloud Optimized Geotiff, using the options that work best for our imagery at Environment Yukon"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
params = []
params += [arcpy.Parameter(
displayName = "Input Raster",
name = "in_raster",
datatype="GPRasterLayer",
parameterType="Required",
direction="Input"
)]
params += [arcpy.Parameter(
displayName="Output Raster",
name="out_raster",
datatype="DERasterDataset",
parameterType="Required",
direction="Output"
)]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""Source code (adapted from 'gdal-to-cog.py')"""
infile = parameters[0].valueAsText
outfile = parameters[1].valueAsText
gdal.SetConfigOption('GDAL_CACHEMAX','30%')
options = ["COMPRESS=ZSTD", "PREDICTOR=YES", "LEVEL=17", "BIGTIFF=YES",
"NUM_THREADS=ALL_CPUS",]
def progress_cb(complete, message, cb_data):
'''Emit progress report in numbers for 10% intervals and dots for 3%'''
if int(complete*100) % 10 == 0:
print(f'{complete*100:.0f}', end='', flush=True)
elif int(complete*100) % 3 == 0:
print(f'{cb_data}', end='', flush=True)
arcpy.AddMessage(f'Translating {infile} to {outfile}')
gdal.Translate(outfile, infile, creationOptions=options,
format="COG",
callback=progress_cb,
callback_data='.'
)
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment