Python PIL For Loop to work with Multi-image TIFF

前端 未结 5 480
清酒与你
清酒与你 2020-12-09 05:33

Each tiff file has 4 images in it. I do not wish to extract and save them if possible, I would just like to use a for loop to look at each of them. (Like look at the pixel [

相关标签:
5条回答
  • 2020-12-09 05:41

    Thanks to the answers on this thread I wrote this python module for reading and operating on multipage tiff files: https://github.com/mpascucci/multipagetiff

    It also allows to color-code the image stack "depth-wise" and make z-projections.

    Hope it can help

    0 讨论(0)
  • 2020-12-09 05:42

    Had to do the same thing today,

    I followed @stochastic_zeitgeist's code, with an improvement (don't do manual loop to read per-pixel) to speed thing up.

    from PIL import Image
    import numpy as np
    
    def read_tiff(path):
        """
        path - Path to the multipage-tiff file
        """
        img = Image.open(path)
        images = []
        for i in range(img.n_frames):
            img.seek(i)
            images.append(np.array(img))
        return np.array(images)
    
    0 讨论(0)
  • 2020-12-09 05:48

    You can use the "seek" method of a PIL image to have access to the different pages of a tif (or frames of an animated gif).

    from PIL import Image
    
    img = Image.open('multipage.tif')
    
    for i in range(4):
        try:
            img.seek(i)
            print img.getpixel( (0, 0))
        except EOFError:
            # Not enough frames in img
            break
    
    0 讨论(0)
  • 2020-12-09 05:58

    Here's a method that reads a multipage tiff and returns the images as a numpy array

    from PIL import Image
    import numpy as np
    
    def read_tiff(path, n_images):
        """
        path - Path to the multipage-tiff file
        n_images - Number of pages in the tiff file
        """
        img = Image.open(path)
        images = []
        for i in range(n_images):
            try:
                img.seek(i)
                slice_ = np.zeros((img.height, img.width))
                for j in range(slice_.shape[0]):
                    for k in range(slice_.shape[1]):
                        slice_[j,k] = img.getpixel((j, k))
    
                images.append(slice_)
    
            except EOFError:
                # Not enough frames in img
                break
    
        return np.array(images)
    
    0 讨论(0)
  • 2020-12-09 06:08

    Rather than looping until an EOFError, one can iterate over the image pages using PIL.ImageSequence (which effectively is equivalent as seen on the source code).

    from PIL import Image, ImageSequence
    
    im = Image.open("multipage.tif")
    
    for i, page in enumerate(ImageSequence.Iterator(im)):
        page.save("page%d.png" % i)
    
    0 讨论(0)
提交回复
热议问题