Can't get GPS coordinates from from EXIF data in python (Pillow or pyexiv2)

1.2k Views Asked by At

I'm trying to extract GPS coordinates from a JPG image but I don't get much information with pillow.

This is my 1st attempt:

from PIL import Image
from PIL.ExifTags import TAGS

my_img = Image.open("IMG_0547.jpg")

exif_data = my_img.getexif()
for tag_id in exif_data:
    tag = TAGS.get(tag_id, tag_id)
    data = exif_data.get(tag_id)

    print(f"{tag:16}: {data}")

Output:

TileWidth       : 512
TileLength      : 512
GPSInfo         : 1996
ResolutionUnit  : 2
ExifOffset      : 216
Make            : Apple
Model           : iPhone XS
Software        : 13.6
Orientation     : 1
DateTime        : 2020:08:13 21:01:41
XResolution     : 72.0
YResolution     : 72.0

Download the image from here

I also tried using pyexiv2 but I get this error for only o line of code metadata = pyexiv2.ImageMetadata('IMG_0547.jpg') which makes no sense because ImageMetadata is listed in the official documentation here

Traceback (most recent call last):
  File "maps.py", line 17, in <module>
    metadata = pyexiv2.ImageMetadata('IMG_0547.jpg')
AttributeError: module 'pyexiv2' has no attribute 'ImageMetadata'

Can someone please help me get the coordinates?

2

There are 2 best solutions below

0
On

A little late but this is what I used recently to get image metadata. I also modified it with modify_iptc and modify_xmp (not posted here). pyexiv2 Rev on PyPI

import pyexiv2 

filename = r"C:\mydjifolder\Junk\DJI_0001.JPG"

img_meta = pyexiv2.Image(filename)

exif_dict = img_meta.read_exif()
xmp_dict = img_meta.read_xmp()
iptc_dict = img_meta.read_iptc()
print("\n**** IPTC Tags metadata ****")
for key, value in iptc_dict.items():
    print(f"TAG {key} = \t\t {value}")

print("**** EXIF Tags metadata ****")
for key, value in exif_dict.items():
    print(f"TAG {key} = \t\t {value}")


print("\n**** XMP Tags metadata ****")
for key, value in xmp_dict.items():
    if key == "Exif.Photo.MakerNote":
        continue
    print(f"TAG {key} = \t\t {value}")
    

print(xmp_dict["Xmp.xmp.CreateDate"])
print(iptc_dict["Iptc.Application2.DateCreated"])
img_meta.close
0
On

Pillow's Github has an explanation. The number in GPSInfo is merely a kind of offset (see https://photo.stackexchange.com/a/27724).

To find the content of GPSInfo, we can use PIL.Image.Exif.get_ifd:

from PIL import ExifTags, Image

GPSINFO_TAG = next(
    tag for tag, name in TAGS.items() if name == "GPSInfo"
)  # should be 34853

path = "my_geotagged_image.jpg"
image = Image.open(path)
info = image.getexif()

gpsinfo = info.get_ifd(GPSINFO_TAG)

Then proceed like here: Interpreting GPS info of exif data from photo in python