Tuesday 22 October 2019

Using 'gdalwarp' in Python script for Grass


I'm writing a Python script that aims to re-project various LANDSAT tiles into a common projection and then import the tiles into Grass. The script at present is shown below:


#!/usr/bin/python

import os
import sys

import glob
import grass.script as grass

def import_tifs(dirpath):
for dirpath, dirname, filenames in os.walk(dirpath):
for tile in filenames:
if tile.upper().endswith('.TIF'):
full_path = os.path.join(dirpath, tile)
name = os.path.splitext(tile)[0]
rename = name[:-4] + '.' + name[-2]

new_path = os.path.join(dirpath, rename)
re_project = 'EPSG:32643'
grass.message('Importing %s -> %s@%s...' % (tile, name, dirpath))
grass.run_command('gdalwarp',
'-t_srs',
re_project,
full_path,
new_path)
grass.run_command('r.in.gdal',
flags = 'e',

input = full_path,
output = name,
quiet = True,
overwrite = True)

def main():
if len(sys.argv) == 1:
for directory in filter(os.path.isdir, os.listdir(os.getcwd())):
import_tifs(directory)
else:

import_tifs(sys.argv[1])
if __name__ == "__main__":
main()

I'm having real trouble using the 'gdalwarp' command to reproject the LANDSAT tiles. I keep getting the following error:


Traceback (most recent call last):
File "C:/Users/Simon/Documents/import_landsat3.py", line
76, in
main()
File "C:/Users/Simon/Documents/import_landsat3.py", line

73, in main
import_tifs(sys.argv[1])
File "C:/Users/Simon/Documents/import_landsat3.py", line
31, in import_tifs
new_path)
File "C:\GRASS64\etc\python\grass\script\core.py", line
189, in run_command
ps = start_command(*args, **kwargs)
File "C:\GRASS64\etc\python\grass\script\core.py", line
167, in start_command

args = make_command(prog, flags, overwrite, quiet,
verbose, **options)
File "C:\GRASS64\etc\python\grass\script\core.py", line
124, in make_command
raise ScriptError("'-' is not a valid flag")
grass.script.core.ScriptError: "'-' is not a valid flag"

I'm assuming this is related to '-t_srs' but I haven't been able to work out a way around the problem - can anyone suggest how to do this?


Many thanks.



Answer




Have you tried calling gdalwarp using os.sys? Check this post for more details on the topic.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...