Reading long exif tags in python

1.5k views Asked by At

I'm trying to read the EXIF info for microscope images like this one: https://dl.dropboxusercontent.com/u/3816350/E3-9.tif

I am most interested in the "Image Description" tag because it contains information about the scale of the image. I have successfully loaded the EXIF info using the exifread package:

import exifread

f = open('E3-9.tif', 'rb')
exif_info = exifread.process_file(f)

for tag in exif_info.keys():
    print "Key: %s, value %s" % (tag, exif_info[tag])

However, the Image Description is cutoff in the output and I cannot figure out how to display the entire "Image ImageDescription" field. Any idea how I can do this?

BTW, I tried using PIL to read the EXIF info (as described here) using this code:

from PIL import Image
from PIL.ExifTags import TAGS

img = Image.open('E3-9.tif')
exif_data = img._getexif()

But I get the following error:

Traceback (most recent call last):
  File "/Users/..../2014-01-02 - Read scale from tif file.py", line 22, in <module>
    exif_data = img._getexif()
  File "/Users/danhickstein/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/PIL/Image.py", line 512, in __getattr__
    raise AttributeError(name)
AttributeError: _getexif

I have also tried exiftool on the command line, but it also slightly cuts off the Image Description field.

Any tips would be appreciated.

3

There are 3 answers

0
DanHickstein On BEST ANSWER

Here is the hilariously slow and inefficient method of calling exiftool on the command line using subprocess.check_output. Not my finest hour, but it works:

import matplotlib.pyplot as plt
import subprocess, glob, re

def get_magnification(filename):
    p = subprocess.check_output('exiftool -tab %s'%filename,shell=True) 

    xpix = float(re.findall('XpixCal=\d*.\d*',p)[0][8:])
    ypix = float(re.findall('YpixCal=\d*.\d*',p)[0][8:])

    mag = int(re.findall('p.\d+',p)[0][2:])

    return xpix,ypix,mag

xpix,ypix,mag = get_magnification('E3-9.tif')

print 'X pixels per nm: %.3f'%(xpix)
print 'Y pixels per nm: %.3f'%(ypix)
print 'Magnification:   %ix'%(mag)
3
Jacob Budin On

The metadata you're looking may be part of the image's IPTC metadata, not EXIF. If so, you'll need a different Python module to read it. Take a look at "Exif manipulation library for python [closed]" for recommendations that include IPTC data.

0
user4816636 On

You have to use exif_info[tag].values to get the full ImageDescription