[英]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.我正在使用 python (cv2) 导入具有三层的 .tif 文件,但我似乎只能导入一层。 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这会从第一层中提取蓝色通道,但不知道如何获取其他层
You can simply use cv2.split
for splitting image channels.您可以简单地使用cv2.split
来分割图像通道。
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.编辑 1:如果您想在 TIF 文件中拆分多个图像并将它们另存为 @fmw42 建议的单独文件,这里是代码。
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 function 调用将类似于
tifToImage('LanB2_KD1P2_31603_gut_2.tif','jpg','out_folder')
Much simpler, you can use cv2.imreadmulti:简单得多,您可以使用 cv2.imreadmulti:
ret, image = cv2.imreadmulti('LanB2_KD1P2_31603_gut_2.tif', [], cv2.IMREAD_ANYCOLOR)
You can then access each layer by their indexes (eg. image[0]).然后,您可以通过索引访问每一层(例如 image[0])。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.