Skip to content

Instantly share code, notes, and snippets.

@iliion
Created November 13, 2024 18:53
Show Gist options
  • Save iliion/d75365991ba5c7a98e1e8320b54ff7e0 to your computer and use it in GitHub Desktop.
Save iliion/d75365991ba5c7a98e1e8320b54ff7e0 to your computer and use it in GitHub Desktop.
Reproject geotiffs using gdalwarp
#!/bin/bash
set -x
set -e
set -u
set -o pipefail
# Check if the correct number of arguments is provided
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <input_folder> <output_folder> <projection>"
exit 1
fi
input_folder=$1
output_folder=$2
dst_crs=$3
# Get the directory of the current script
folder="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Delete any existing tmp_anagrafica.jsonl files in the folder
find "$folder" -name tmp_anagrafica.jsonl -delete
# Iterate through all files in the input directory
find "$input_folder" -maxdepth 1 -type f -print0 | while IFS= read -r -d '' file; do
echo "Processing file: $file"
nome=$(basename "$file")
# Check if the file is supported by GDAL
if gdalinfo "$file" >/dev/null 2>&1; then
echo "The file '$file' is a supported format."
# Extract the projection of the file
projection=$(gdalsrsinfo -o PROJJSON "$file" | jq -r '.id.code')
echo "Projection: $projection"
# Extract the format of the file
formato=$(gdalinfo -json "$file" | jq -r '.driverLongName')
echo "Format: $formato"
# Append file details to tmp_anagrafica.jsonl
echo '{"nome": "'"$nome"'", "projection": "'"$projection"'", "formato": "'"$formato"'", "file": "'"$file"'"}' >>"$folder"/tmp_anagrafica.jsonl
else
echo "Error: The file '$file' is not recognized as a supported format."
fi
done
# Filter the JSONL file to exclude files with projection 4326 and already processed files
jq -c 'select(.projection != "4326")' "$folder"/tmp_anagrafica.jsonl | while read -r line; do
nome=$(echo "$line" | jq -r '.nome')
file=$(echo "$line" | jq -r '.file')
extension="${file##*.}"
nome_no_ext="${nome%.*}"
output_file="$output_folder/${nome_no_ext}_$dst_crs.$extension"
if [ ! -f "$output_file" ]; then
echo "$line" >> "$folder"/filtered_anagrafica.jsonl
fi
done
# Reproject files to the specified projection
while read -r line; do
echo "Reprojecting: $line"
nome=$(echo "$line" | jq -r '.nome')
file=$(echo "$line" | jq -r '.file')
extension="${file##*.}"
nome_no_ext="${nome%.*}"
output_file="$output_folder/${nome_no_ext}_$dst_crs.$extension"
if [ ! -f "$output_file" ]; then
gdalwarp -dstalpha -t_srs "$dst_crs" "$file" "$output_file"
fi
done <"$folder"/filtered_anagrafica.jsonl
@iliion
Copy link
Author

iliion commented Nov 13, 2024

Reproject geotiffs using gdalwarp.

Usage: ./script.sh /path/to/input/folder /path/to/output/folder EPSG:4326

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