18

How can I read metada, like coordinates, from a TIFF image in Python? I tried foo._getexif() from PIL, but got the message:

AttributeError: 'TiffImageFile' object has no attribute '_getexif'

Is it possible to get it with PIL?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Filipe Vargas
  • 193
  • 1
  • 1
  • 7

3 Answers3

21
from PIL import Image
from PIL.TiffTags import TAGS

with Image.open('image.tif') as img:
    meta_dict = {TAGS[key] : img.tag[key] for key in img.tag.iterkeys()}

_getexif() is only meant to be used with JPEG. JPEG requires unpacking of the metadata, TIFF does not. That said, PIL does not naively read Exif tags or directory (less straightforward) TIFF metadata.

Martin
  • 326
  • 3
  • 6
11

ExifRead will do the trick for what you want. Try:

import exifread
# Open image file for reading (binary mode)
f = open('image.tif', 'rb')

# Return Exif tags
tags = exifread.process_file(f)

# Print the tag/ value pairs
for tag in tags.keys():
    if tag not in ('JPEGThumbnail', 'TIFFThumbnail', 'Filename', 'EXIF MakerNote'):
        print "Key: %s, value %s" % (tag, tags[tag])
Landini135
  • 177
  • 2
  • 8
  • I use Landini135's code above, but I get only the coordinates of the upper left corner... I need also (at least) the down right corner's coordinates in order to calculate all the 4 coordinates that I need... Why is this happening? With gdalinfo (on terminal) I get the whole 4 corners' coordinates for the same .tiff image (but they can't be used from terminal obviously....). – just_learning Sep 21 '21 at 16:28
  • 1
    You just need to multiply the x and y pixel size by the number of pixels to get the bottom right. This is common, GDAL just does this automatically. – Landini135 Jan 07 '22 at 14:58
5

Since the first answer didn't work for me, I made the following adjustment:

from PIL import Image
from PIL.TiffTags import TAGS

img = Image.open('test.tif')
meta_dict = {TAGS[key] : img.tag[key] for key in img.tag_v2}

Here are some links that I found useful:

https://pillow.readthedocs.io/en/stable/_modules/PIL/TiffTags.html https://hhsprings.bitbucket.io/docs/programming/examples/python/PIL/ExifTags.html https://github.com/python-pillow/Pillow/issues/4940