Skip to content

Instantly share code, notes, and snippets.

@dwtkns
Last active November 12, 2015 03:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwtkns/3e7346af9999ea959356 to your computer and use it in GitHub Desktop.
Save dwtkns/3e7346af9999ea959356 to your computer and use it in GitHub Desktop.
Copies georeferencing information from one file to another via PAM .aux.xml files
#!/usr/bin/env python
# This script copies georeferencing information from one file to another that has none,
# via the creation of an .aux.xml file (so it should work with any image format).
# This is useful if, for example, you've edited a GeoTIFF in Photoshop,
# and saved the result as a JPG that you'd still like to be geo-aware for use
# with GDAL or QGIS.
# Requires GDAL command line tools, because re-making gdalbuildvrt in python
# sounded super hard.
import sys
from subprocess import check_output
import xml.etree.ElementTree as et
if len(sys.argv)<2:
sys.exit('Usage: copygeo.py <georeferenced input file> <non-georeferenced output file>');
inputFile = sys.argv[1]
outputFile = sys.argv[2] + '.aux.xml'
# make a VRT file from the first argument, using gdalbuildvrt command line tool
vrt = check_output(['gdalbuildvrt', '-q', '/vsistdout/', inputFile])
# parse vrt as xml
vrt = et.fromstring(vrt)
# grab the <SRS> and <GeoTransform> tags from the VRT (they're in the format we want for a PAM .aux.xml file)
# this assumes there's only one SRS and GeoTransform tag. reasonable assumption? i'm not sure.
for SRS in vrt.findall('SRS'):
SRS=SRS.text
for GeoTransform in vrt.findall('GeoTransform'):
GeoTransform=GeoTransform.text
# build a PAM file manually
PAMstring = (''+
'<PAMDataset>\n'+
' <SRS>'+SRS+'</SRS>\n'+
' <GeoTransform>'+GeoTransform+'</GeoTransform>\n'+
' <Metadata>\n'+
' <MDI key="AREA_OR_POINT">Area</MDI>\n'+
' </Metadata>\n'+
' <PAMRasterBand band="1">\n'+
' <Metadata domain="IMAGE_STRUCTURE">\n'+
' <MDI key="COMPRESSION">JPEG</MDI>\n'+
' </Metadata>\n'+
' <Metadata>\n'+
' <MDI key="LAYER_TYPE">athematic</MDI>\n'+
' </Metadata>\n'+
' </PAMRasterBand>\n'+
'</PAMDataset>\n'+
'')
f = open(outputFile,"w")
f.write(PAMstring)
f.close()
@dwtkns
Copy link
Author

dwtkns commented Nov 11, 2015

i dunno if all that junk with key="COMPRESSION" and LAYER_TYPE athematic is necessary, but it seemed to work fine so i left it in! ¯_(ツ)_/¯

@dwtkns
Copy link
Author

dwtkns commented Nov 12, 2015

Don't use this, use rio edit-info unreferenced.jpg --like referenced.tif --all

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