[GIS] proper use of python subprocess for GDAL

gdalgeotiff-tiffjpeg 2000python

I need to process some sentinel-2 files which are in jp2 format using python. I first want to clip the jp2 files and save the result as geotiff with the same CRS. But some of the modules I use (e.g., rasterio for clip) don't like jp2 format so I try to convert the jp2 to geotiff. I am able to do so using QGIS translate tool which is essentially GDAL translate. However, when I try to use the translate tool in python:

import geojson, gdal, subprocess

tif_file = r"C:\Users\Administrator\L2A_B04_10m.tif"
jp2_file = r"C:\Users\Administrator\L2A_T29RNP_20170422T110651_B04_10m.jp2"

args = ['gdal_translate', '-of', 'Gtiff', jp2_file , tif_file]
subprocess.Popen(args)

I get a file without CRS. I tried to embed the CRS in the args but I can't figure out a way to do so, I don't get any error but it seems that the code is ignoring my tries, like:

args = ['gdal_translate', '-a_srs','ESPG:4326', '-of', 'Gtiff', jp2_file , tif_file]
subprocess.Popen(args)

results: nothing happens, no error, and no file is created

also:

args = ['gdal_translate', '-a_srs ESPG:4326', '-of', 'Gtiff', jp2_file , tif_file]
subprocess.Popen(args)

also:

args = ['gdal_translate', '-a_srs', '+proj=longlat +ellps=WGS84', '-of', 'Gtiff', jp2_file , tif_file]
subprocess.Popen(args)

and:

args = ['gdal_translate', '-a_srs +proj=longlat +ellps=WGS84', '-of', 'Gtiff', jp2_file , tif_file]
subprocess.Popen(args)

What am I missing? or, is there another easier way to clip jp2 format using python?

I'm using python 2.7 on anaconda on win10, gdal 2.2.3

Best Answer

import os
import subprocess

os.chdir("working directory")

# Option 1  List of arguments
args = args = ['gdal_translate', '-a_srs','ESPG:4326', '-of', 'Gtiff', jp2_file , tif_file]
result = subprocess.call(args)

# Option 2  String
result = subprocess.call('gdal_translate -a_srs ESPG:4326 -of Gtiff input.jp2 output.tif')

You can either pass a string or a list of arguments. However try calling subprocess.call() instead of subprocess.Popen(). In the string you'll have to change the file names respectively.

Update:

Try calling gdal_warp as follows:

subprocess.call('gdal_warp -t_srs ESPG:4326 -of Gtiff input.jp2 output.tif')

Additionaly, there are other creation options -co you might be interested in. Check the following link: http://www.gdal.org/gdalwarp.html

Related Question