Medical physicist
Medical physicist

Reputation: 2594

Read tiff tags in Python

I am trying to read the tags of a tiff file in Python. The file is RGB with uint16 values per channel. I am currently using tifffile:

import tifffile

img = tifffile.imread('file.tif')

However, img is a numpy array, which only has pixel values. How can I read, for instance, the x_resolution of the image?

Upvotes: 5

Views: 11128

Answers (3)

Tonechas
Tonechas

Reputation: 13723

Using skimage.external.tifffile is another possible approach:

from skimage.external import tifffile

with tifffile.TiffFile('your_file.tif') as tif:
    imgs = [page.asarray() for page in tif.pages]
    x_res = [page.tags['x_resolution'].value for page in tif.pages]

Edit: the copy of tifffile was removed in version 0.17.1, and tifffile is now installed through pip during the scikit-image installation

Upvotes: 0

Medical physicist
Medical physicist

Reputation: 2594

I found an alternative:

import tifffile
with tifffile.TiffFile('file.tif') as tif:
    tif_tags = {}
    for tag in tif.pages[0].tags.values():
        name, value = tag.name, tag.value
        tif_tags[name] = value
    image = tif.pages[0].asarray()

Upvotes: 8

Alderven
Alderven

Reputation: 8260

Not sure about tifffile lib but you can get x resolution with exifread:

import exifread

with open('image.tif', 'rb') as f:
    tags = exifread.process_file(f)
print(tags['Image XResolution'])

Output:

300

Upvotes: 4

Related Questions