-
-
Save jsundram/3f3af68bd40c183b635e328c342a1b2d to your computer and use it in GitHub Desktop.
Get Latitude and Longitude from EXIF using PIL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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