A while back I threw together an experimental application – and keeping with the theme of GPS in the last post I thought I’d share another little gem which could prove a really cool feature in future apps.

Below I’ve outlined some code you can use to extract the EXIF data from a digital camera that is GPS enabled and grab the GPS coordinates to map onto a google map using pymaps as described in this previous post.

To get started on this I recommend installing PIL (the python image library) – it’s really usefull and has all the functions we need to pull our EXIF data, you can download it here.

Once you’ve installed PIL and you know it’s all working, you can use the code below to grab the exif data out of a file:

def get_exif(fn):
    from PIL import Image
    from PIL.ExifTags import TAGS
    ret = {}
    try:    
        i = Image.open(fn)
        info = i._getexif()
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            ret[decoded] = value
    except:
        ret = ret
       
    return ret

Once you’ve got your exit data – here’s a usefull little function you can use to extract and decipher the data into something actually useful. The extracted information is actually in DMS format, so you can use the getcords() function described previously to get hold of Google Maps-compatible decimal coordinates:

def getcords_exif(exif):
    lat = 0.0
    lon = 0.0
   
    if exif['GPSInfo']:        
        # Latitude
        cords = exif['GPSInfo']
        ind = cords[1]
        d = cords[2][0][0]
        m = cords[2][1][0]
        s = cords[2][2][0]
       
        #Note: we get decimal versions here!
        lat = float(getcords(d, m ,s, ind))
       
        #Longitutude
        ind = cords[3]
        d = cords[4][0][0]
        m = cords[4][1][0]
        s = cords[4][2][0]
       
        lon = float(getcords(d, m ,s, ind))
       
    return lat, lon

I found while testing that this works fine with Nokia phones, but fails with iPhone images that are supposedly geotagged. Interestingly, using an EXIF viewer with those files showed non-standard exif data. It would be interesting to find out why they aren’t encoded properly?

Either way – the PIL library can get more than just the GPS info, it is possble to pull all kinds of information such as the make & model of the camera, time / date of capture etc.

I’m itching to implement this in a website – Flickr already does, but I think it’s just a cool feature ;-)