Skip to content

Instantly share code, notes, and snippets.

@ar-siddiqui
Created October 26, 2022 16:04
Show Gist options
  • Save ar-siddiqui/c6b8735ecd8f1ea510947d0e7a673efa to your computer and use it in GitHub Desktop.
Save ar-siddiqui/c6b8735ecd8f1ea510947d0e7a673efa to your computer and use it in GitHub Desktop.
Turn GeoTiff to Cloud Optimized GeoTiff
import subprocess
import sys
def create_cog(in_tif: str, out_tif: str):
# TODO for edge cases may need to call gdaladdo twice: first to clear existing ovrs and then to make new ovrs
# TODO parameterize and expose compression options (algorithm, level, predictor)
# TODO are we sure this creates a fully compliant COG? internal tile sizes and regular blocking constraints?
print(f"running gdaladdo on: {in_tif}")
subprocess.check_call(["gdaladdo", "-r", "average", in_tif, "2", "4", "8", "16"])
print(f"running gdal_translate on: {in_tif} -> {out_tif}")
subprocess.check_call(
["gdal_translate", in_tif, out_tif, "-co", "COMPRESS=LZW", "-co", "TILED=YES", "-co", "COPY_SRC_OVERVIEWS=YES"]
)
def Usage():
print("Usage: create_cog.py [inpath] [outpath]")
return 1
def main():
"""Return 0 in case of success, 1 for failure."""
i = 1
inpath = sys.argv[1]
outpath = sys.argv[2]
if not inpath and not outpath:
return Usage()
try:
e_code = 0
create_cog(inpath, outpath)
except Exception as e:
e_code = 1
print(e)
return e_code
if __name__ == "__main__":
sys.exit(main())
@ar-siddiqui
Copy link
Author

sample usage:
In OSGeo4w shell:

python create_cog.py <path_of_tif> <path_of_out_tif>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment