Getting GPS EXIF Data with Python

Did you know that you can get EXIF data from JPG image files using the Python programming language? You can use Pillow, the Python Imaging Library's friendly fork to do so. You can read an article about that on this website if you want to.

Here is some example code for getting regular EXIF data from a JPG file:

# exif_getter.py

from PIL import Image
from PIL.ExifTags import TAGS


def get_exif(image_file_path):
    exif_table = {}
    image = Image.open(image_file_path)
    info = image.getexif()
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        exif_table[decoded] = value
    return exif_table


if __name__ == "__main__":
    exif = get_exif("bridge.JPG")
    print(exif)

This code was run using the following image:

Mile long bridge

In this article, you will focus on how to extract GPS tags from an image. These are special EXIF tags that are only present if the camera that took the photo had its location information turned on for the camera. You can also add GPS tags on your computer after the fact.

For example, I added GPS tags to this photo of Jester Park, which is in Granger, IA:

To get access to those tags, you'll need to take the earlier code example and do some minor adjustments:

# gps_exif_getter.py

from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS


def get_exif(image_file_path):
    exif_table = {}
    image = Image.open(image_file_path)
    info = image.getexif()
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        exif_table[decoded] = value

    gps_info = {}
    for key in exif_table['GPSInfo'].keys():
        decode = GPSTAGS.get(key,key)
        gps_info[decode] = exif_table['GPSInfo'][key]

    return gps_info


if __name__ == "__main__":
    exif = get_exif("jester.jpg")
    print(exif)

To get access to the GPS tags, you need to import GPSTAGS from PIL.ExifTags. Then after parsing the regular tags from the file, you add a second loop to look for the "GPSInfo" tag. If that's present, then you have GPS tags that you can extract.

When you run this code, you should see the following output:

{'GPSLatitudeRef': 'N',
 'GPSLatitude': (41.0, 47.0, 2.17),
 'GPSLongitudeRef': 'W',
 'GPSLongitude': (93.0, 46.0, 42.09)}

You can take this information and use it to load a Google map with Python or work with one of the popular GIS-related Python libraries.

Related Reading

Copyright © 2024 Mouse Vs Python | Powered by Pythonlibrary