Skip to content

Instantly share code, notes, and snippets.

@jgomezdans
Created July 20, 2012 18:35
Show Gist options
  • Save jgomezdans/3152468 to your computer and use it in GitHub Desktop.
Save jgomezdans/3152468 to your computer and use it in GitHub Desktop.
A script to stitch files with GDAL tools.
#!/bin/bash
# This script stitches, reprojects and builds a multi-band TIF file
# from MODIS HDF product data. The script is geared towards the
# MODIS GPP product (MOD17), although it is easy to modify it to work
# with other products.
# Author: J Gómez-Dans (NCEO/UCL)
# URL: http://jgomezdans.github.com/stitching-together-modis-data.html
tile1=$1
tile2=$2
year=$3
# First grab the available dates for one tile
# Modify for other MODIS products other than MOD17
hdf_tile1=(`ls MOD17A2.A${year}*${tile1}*.hdf`)
\rm -rf file_list.txt
# Loop through datasets in time...
for t1 in "${hdf_tile1[@]}"
do
t2=`echo $t1| awk -F"." -v other_tile=$tile2 \
'{printf( "%s.%s.%s.*\n", $1,$2,other_tile)}'`
t2=`ls $t2`
output_fname=`echo $t1| awk -F"." '{printf( "%s.%s\n", $1,$2)}'`
echo ${t1} ${t2} ${output_fname}
# Modify for other MODIS products other than MOD17
gdalbuildvrt ${output_fname}_mosaic_sinu.vrt \
'HDF4_EOS:EOS_GRID:"'${t1}'":MOD_Grid_MOD17A2:Gpp_1km' \
'HDF4_EOS:EOS_GRID:"'${t2}'":MOD_Grid_MOD17A2:Gpp_1km'
# Change the output EPSG to something else if appropriate
gdalwarp -of VRT -t_srs "EPSG:27700" ${output_fname}_mosaic_sinu.vrt \
${output_fname}_mosaic.vrt
# Change the output window to something sensible if you use other
# regions etc.
gdal_translate -of VRT \
-projwin -246410.748854375 1294822.36205397 901561.991813587 34610.1630877961 \
${output_fname}_mosaic.vrt ${output_fname}.vrt
echo ${output_fname}.vrt >> file_list.txt
done
# Let's build the multi-band raster
gdalbuildvrt -separate -input_file_list file_list.txt MOD17A2.${year}.vrt
gdal_translate -of GTiff -co "COMPRESS=LZW" -co "TILED=YES" \
MOD17A2.${year}.vrt MOD17A2.${year}.tif
@w1malik
Copy link

w1malik commented Sep 28, 2018

Nice script but I tried to run this clip for 6 modis tiles and I edited the following 3 lines of codes with t3, t4, t5, t6 which becomes 15 lines.
t2=echo $t1| awk -F"." -v other_tile=$tile2 \ '{printf( "%s.%s.%s.*\n", $1,$2,other_tile)}'
t2=ls $t2
Although, I edited your code like this way and it works for me.
But I want to know, can I use assigning multiple variable in awk script e.g., t2=`echo $t1| awk -F"." -v other_tile=$tile2 $tile3 $tile4 $tile5 $tile6 as for my case of stitching 6 tiles rather to repeat these 3 lines of codes. And how about memory space of resulting output, I took only 5K disk space. Is this Ok for very less memory on disk for all 6 modis tiles.
How can I set nodata value to be not included into the output (for my case using MYD13Q1, setting Fill value =-3000 and valid range -2000 to 10000).

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