Skip to content

Instantly share code, notes, and snippets.

@moshekaplan
Forked from erans/get_lat_lon_exif_pil.py
Last active July 25, 2019 10:13
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save moshekaplan/5330395 to your computer and use it in GitHub Desktop.
Save moshekaplan/5330395 to your computer and use it in GitHub Desktop.
import sys
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
def get_exif_data(image):
"""Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""
exif_data = {}
info = image._getexif()
if info:
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if decoded == "GPSInfo":
gps_data = {}
for gps_tag in value:
sub_decoded = GPSTAGS.get(gps_tag, gps_tag)
gps_data[sub_decoded] = value[gps_tag]
exif_data[decoded] = gps_data
else:
exif_data[decoded] = value
return exif_data
def _convert_to_degress(value):
"""Helper function to convert the GPS coordinates stored in the EXIF to degress in float format"""
deg_num, deg_denom = value[0]
d = float(deg_num) / float(deg_denom)
min_num, min_denom = value[1]
m = float(min_num) / float(min_denom)
sec_num, sec_denom = value[2]
s = float(sec_num) / float(sec_denom)
return d + (m / 60.0) + (s / 3600.0)
def get_lat_lon(exif_data):
"""Returns the latitude and longitude, if available, from the provided exif_data (obtained through get_exif_data above)"""
lat = None
lon = None
if "GPSInfo" in exif_data:
gps_info = exif_data["GPSInfo"]
gps_latitude = gps_info.get("GPSLatitude")
gps_latitude_ref = gps_info.get('GPSLatitudeRef')
gps_longitude = gps_info.get('GPSLongitude')
gps_longitude_ref = gps_info.get('GPSLongitudeRef')
if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:
lat = _convert_to_degress(gps_latitude)
if gps_latitude_ref != "N":
lat *= -1
lon = _convert_to_degress(gps_longitude)
if gps_longitude_ref != "E":
lon *= -1
return lat, lon
################
# Example ######
################
if __name__ == "__main__":
# load an image through PIL's Image object
if len(sys.argv) < 2:
print "Error! No image file specified!"
print "Usage: %s <filename>" % sys.argv[0]
sys.exit(1)
image = Image.open(sys.argv[1])
exif_data = get_exif_data(image)
print get_lat_lon(exif_data)
@cleder
Copy link

cleder commented Jul 15, 2013

sec_num, sec_denom = value[1]
must be
sec_num, sec_denom = value[2]

-> https://github.com/collective/collective.geo.exif/blob/master/collective/geo/exif/readexif.py

@vnagendra
Copy link

If you are using something like ExifTool to write data, it is easier (script-wise) to NOT populate N and E if the values are positive (that was my case anyway). I think those are safe assumptions to make IMO. I suggest the following changes

    if gps_info is not None:
        gps_latitude = gps_info.get("GPSLatitude", None)
        gps_latitude_ref = gps_info.get('GPSLatitudeRef', 'N')
        gps_longitude = gps_info.get('GPSLongitude', None)
        gps_longitude_ref = gps_info.get('GPSLongitudeRef', 'E')

@moshekaplan
Copy link
Author

@cleder : The evil copy-paste strikes again! Fixed now, thanks.

@femmebot
Copy link

Could you offer some direction on how I might modify this script to extract lat/long from a batch of images? I'm new to Python (Python3, at that).

@maxbellec
Copy link

you can do much much shorter and clear :

import PIL.Image

get_float = lambda x: float(x[0]) / float(x[1])
def convert_to_degrees(value):
    d = get_float(value[0])
    m = get_float(value[1])
    s = get_float(value[2])
    return d + (m / 60.0) + (s / 3600.0)

def get_lat_lon(info):
    try:
        gps_latitude = info[34853][2]
        gps_latitude_ref = info[34853][1]
        gps_longitude = info[34853][4]
        gps_longitude_ref = info[34853][3]
        lat = convert_to_degrees(gps_latitude)
        if gps_longitude_ref != "N":
            lat *= -1

        lon = convert_to_degrees(gps_longitude)
        if gps_longitude_ref != "E":
            lon *= -1
        return lat, lon
    except KeyError:
        return None

@BigglesZX
Copy link

This was super useful, thank you.

@NandiniCS
Copy link

from using (lat,long) values,could you have any idea about how to find location of each pixel values of that image or grids of image??

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