What's the best way to split a multi-page TIFF with python? PIL doesn't seem to have support for multi-page images, and I haven't found an exact port for libtiff for python. Would PyLibTiff be the way to go? Can somebody provide a simple example of how I could parse multiple pages within a TIFF?
Now, browse and select a multipage TIFF file. You can add multiple TIFF images to it for conversion. Next, select output format as JPG or PNG. In case you want to split TIFF into separate PDF files, you can select the convert to format as Each page as separate PDF files.
A project (disclosure: which I am one of the main authors, this question was one of the things that prompted me to work on it) which makes this is easy is PIMS. The core of PIMS is essentially a cleaned up and generalized version of the following class.
A class to do basic frame extraction + simple iteration.
import PIL.Image
class Stack_wrapper(object):
def __init__(self,fname):
'''fname is the full path '''
self.im = PIL.Image.open(fname)
self.im.seek(0)
# get image dimensions from the meta data the order is flipped
# due to row major v col major ordering in tiffs and numpy
self.im_sz = [self.im.tag[0x101][0],
self.im.tag[0x100][0]]
self.cur = self.im.tell()
def get_frame(self,j):
'''Extracts the jth frame from the image sequence.
if the frame does not exist return None'''
try:
self.im.seek(j)
except EOFError:
return None
self.cur = self.im.tell()
return np.reshape(self.im.getdata(),self.im_sz)
def __iter__(self):
self.im.seek(0)
self.old = self.cur
self.cur = self.im.tell()
return self
def next(self):
try:
self.im.seek(self.cur)
self.cur = self.im.tell()+1
except EOFError:
self.im.seek(self.old)
self.cur = self.im.tell()
raise StopIteration
return np.reshape(self.im.getdata(),self.im_sz)
Imagemagick worked for me real good. Wnen splitting a tiff file, basically converting from tiff to tiff, one can use a flag to force saving output files to individual tiff files. To do that, try
convert input.tif output-%d.tif
The %d operator is a C-Printf style %d. So, if you need a 3 field running sequence, you can say
convert input.tif output-%3d.tif
and so on.. %d is replaced by "scene" number of the image. Now, scene numbers may or may not always start with 0 (or 1, if you want it that way). To setup a sequence the way you want, try
convert input.tif -scene 1 output-%3d.tif
This would start the sequence right from the count you provided.
convert -scene 1 input.TIF output-%d.TIF
output-1.TIF
output-2.TIF
output-3.TIF
Magick indeed!! :)
This link to documentation has more details. This works on my windows machine too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With