Search code examples
pythonimageopencvcomputer-visiontiff

how to import multiple layers from tif file with opencv


I'm using python (cv2) to import a .tif file with three layers, but I only seem to be able to import one layer. How can i separately import all three layers?

import cv2

img = cv2.imread('LanB2_KD1P2_31603_gut_2.tif', cv2.IMREAD_COLOR)

#extract blue channel
blue_channel = img[:,:,0]

#write blue channel to greyscale image
cv2.imwrite('blue_channel.jpg',blue_channel)

this extracts the blue channel from the first layer but idk how to get the other layers


Solution

  • You can simply use cv2.split for splitting image channels.

    import cv2
    img = cv2.imread('LanB2_KD1P2_31603_gut_2.tif', cv2.IMREAD_COLOR)
    
    b,g,r=cv2.split(img)
    
    ### saving files
    cv2.imwrite('blue_channel.jpg', b)
    cv2.imwrite('green_channel.jpg',g)
    cv2.imwrite('red_channel.jpg',r)
    

    EDIT 1: If you want to split multiple images in a TIF file and save as them as separate files as suggested by @fmw42 , here is the code for that.

    import os
    from PIL import Image
    
    def tifToImage(tifPath,imageFormat,folderPath):
        """ Function to convert tif to image
    
        Args:
            tifPath (str): path of input tif
            imageFormat (str): format to save image
            folderPath (str): Folder to save images
        Returns:
            int: 0 if successful
        """
        print('tiftoimage: {}'.format(tifPath))
        sep='/' if '/' in tifPath else '\\'
        fileName=tifPath.split(sep)[-1][:-4]
        ### Loading tiff image
        tiffstack= Image.open(tifPath)
        tiffstack.load()
    
        ### Saving each image to output folder
        for i in range(tiffstack.n_frames):
            tiffstack.seek(i)
            pageName= fileName + '_{:05d}.{}'.format(i+1,imageFormat)
            imagePath = os.path.join(folderPath,pageName)
            tiffstack.save(imagePath)
        return 0
    

    The function call will be something like

    tifToImage('LanB2_KD1P2_31603_gut_2.tif','jpg','out_folder')