What’s the Best Way to Save Image Metadata Alongside a TIFF?

Problem Formulation

You create images in the Tag Image File Format (TIFF). You want to add custom metadata to the image such as the location or other context information important for post-processing. How can you accomplish this?

Solution

  • Install and import the library tiffile.
  • Use the tiffile.imsave() function to store the file at a given location.
  • As arguments, use the filename as the first positional argument, the image as the second positional argument.
  • Then add your custom metadata as a string for the keyword argument description.
  • You can now retrieve the metadata by calling the one-liner tifffile.TiffFile(filename).pages[0].tags["ImageDescription"].value.

Here’s an example that is a bit more readable:

import json
import numpy as np
import tifffile

image = np.random.randint(0, 255, size=(100, 100), dtype=np.uint8)
filename = 'your_file.tif'

# Create custom description
my_description = "I recorded this image on Mars"

# Write the file
tifffile.imsave(
    filename,
    image,
    description = my_description
)

# Read the file
frames = tifffile.TiffFile(filename)
page = frames.pages[0]

# Print file description
print(page.tags["ImageDescription"].value)

You can try this example in our interactive Jupyter Notebook in your browser to test if this is what you need:

I hope you liked this short tutorial! If you want to boost your Python skills on autopilot, check out my free email academy:

We have cheat sheets! 😉