Skip to content

Instantly share code, notes, and snippets.

@jsundram
Forked from erans/get_lat_lon_exif_pil.py
Last active January 19, 2017 06:16
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 jsundram/3f3af68bd40c183b635e328c342a1b2d to your computer and use it in GitHub Desktop.
Save jsundram/3f3af68bd40c183b635e328c342a1b2d to your computer and use it in GitHub Desktop.
Get Latitude and Longitude from EXIF using PIL
import PIL.Image
from PIL.ExifTags import TAGS, GPSTAGS
from operator import mul
def rekey(d, source):
"""Re-keys a dictionary d to use keynames from source mapping."""
return {encoding.get(k, k):v for (k, v) in d.iteritems()} if d else {}
def get_exif(image):
"""Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""
exif = rekey(image._getexif(), TAGS)
exif['GPSInfo'] = rekey(exif.get('GPSInfo'), GPSTAGS)
return exif
def dms_to_float(ll):
"""Exif lat/long is a tuple of degrees, minutes, seconds,
e.g. ((51, 1), (29, 1), (3108, 100))
Convert that to a floating point number of degrees.
"""
to_float = lambda x: float(x[0]) / float(x[1])
dot = lambda x, y: sum(map(mul, x, y))
return dot(map(to_float, ll), [1, 1/60.0, 1/3600.0])
def get_gps(exif):
"""returns lat, lng from exif dict."""
gps = exif['GPSInfo']
sign = lambda k: 1 if gps.get(k + 'Ref') in {'N', 'E'} else -1
read = lambda k: dms_to_float(gps[k]) * sign(k)
return map(read, ['GPSLatitude', 'GPSLongitude'])
def main(filename):
image = PIL.Image.open(filename)
exif = get_exif(image)
lat, lng = get_gps(exif)
print("lat/lng for %s is (%f, %f)" % (filename, lat, lng))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment