Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created August 11, 2012 18:53
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save tmcw/3326365 to your computer and use it in GitHub Desktop.
Save tmcw/3326365 to your computer and use it in GitHub Desktop.
geo-assign any arbitrary image to a geotiff usable in tilemill
import subprocess
import sys, re
MERC = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs'
infile = sys.argv[1]
info_output = subprocess.Popen(['gdalinfo', infile], stdout=subprocess.PIPE).communicate()[0]
size_is_re = re.compile('Size is (?P<width>\d+), (?P<height>\d+)')
size_is = filter(lambda x: x, map(lambda x: size_is_re.match(x), info_output.split('\n')))
if (len(size_is) != 1):
raise 'Could not parse gdalinfo output for image size'
size = [float(size_is[0].group('width')), float(size_is[0].group('height'))]
aspect_ratio = size[1] / size[0]
# the full world dimension
dim = 20037508.34 * 2
if (aspect_ratio > 1):
h = dim
w = dim / aspect_ratio
else:
h = dim * aspect_ratio
w = dim
res = subprocess.call(['gdal_translate', '-a_ullr', str(-w/2), str(-h/2), str(w/2), str(h/2), '-a_srs', MERC, infile, '%s.tif' % infile])
if res != 0:
raise 'An error occurred upon calling gdal_translate'
@timoha
Copy link

timoha commented Apr 19, 2013

I'm having an issue with importing generated tif into QGIS. Once I add it as a waster layer, the image appears upside down. Is it something I have to configure in QGIS or modify your script. Thanks!

@timoha
Copy link

timoha commented Apr 22, 2013

Should be

['gdal_translate', '-a_ullr', str(-w/2), str(h/2), str(w/2), str(-h/2), '-a_srs', MERC, infile, '%s.tif' % infile]

This way the corner coordinates are correct

@nicowernli
Copy link

When trying to upload the generated tif to MapBox I get the following error:
Error creating Mapnik Datasource: Invalid raster: invalid pixelsize in geotransform array

Do you have any idea what might be causing this issue?

@brunob
Copy link

brunob commented Jul 28, 2021

Hi Tom, i've updated this useful script to make it work with python 3 here https://gist.github.com/brunob/d852eb9711d6dc3325e98db437f4c71c

Feel free to report the small change i've made to your original gist, so that people can find a working script more easily :)

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