how to import multiple layers from tif file with opencv

試著忘記壹切 提交于 2021-02-10 16:54:14

问题


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


回答1:


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')


来源:https://stackoverflow.com/questions/63092811/how-to-import-multiple-layers-from-tif-file-with-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!