Create a multiframe .tif file
Asked Answered
G

2

8

I have pixel data that I want to use to create a new .tif image that has multiple frames. How would I go about doing this? I have tried python PIL however I have only found it supports multiple frame reading not writing. See below for my attempt that didn't work.

new_Image = Image.new("I;16", (num_pixels,num_rows))

for frame in range((len(final_rows)/num_rows)):
    pixels = new_Image.load()
    for row in range(num_rows):
        row_pixel = final_rows[row].getPixels()
        for pixel in range(num_pixels):
            pixels[pixel,row] = row_pixel[pixel]
    print frame
    new_Image.seek(frame)
Guadalajara answered 23/10, 2013 at 14:29 Comment(0)
A
9

For example, using numpy and scikit-image with FreeImage plugin:

import numpy as np
from skimage.io._plugins import freeimage_plugin as fi
image = np.zeros((32, 256, 256), 'uint16')
fi.write_multipage(image, 'multipage.tif')

Or save it uncompressed using numpy and tifffile.py:

import numpy as np
from tifffile import imsave
image = np.zeros((32, 256, 256), 'uint16')
imsave('multipage.tif', image)

This assumes that all pages have the same data shape and type and no additional tags need to be written.

Ardell answered 23/10, 2013 at 22:49 Comment(1)
AttributeError: module 'skimage.io._plugins.freeimage_plugin' has no attribute 'write_multipage'Archibold
F
1

I found the following solution easier:

from PIL import Image
 
def save_as_tif(framelist, name):
        imlist = [Image.fromarray(fr) for fr in framelist]
        imlist[0].save(name, compression="tiff_deflate", save_all=True,
                       append_images=imlist[1:])

framelist: can be either a list in which each element is a 2d frame or a 3d numpy array where first dimansion is frame number.

name: output filename (e.g. 'test.tif')

Source: here

Fulltime answered 19/6 at 21:43 Comment(1)
Good find! One thing I might do differently is replace the explicit indices with multi-assignment (imlist = -> first, *rest =; imlist[0] -> first; imlist[1:] -> rest), but that's just a coding style preference.Crosspatch

© 2022 - 2024 — McMap. All rights reserved.