如何将输入 *.tif 文件堆叠到新的 output.tif 光栅文件

how to stack input *.tif files to a new output.tif raster file

我想堆叠光栅文件 (.tiff) 并创建一个新光栅 (.tiff)。 输入的栅格文件是 RGB,需要在不改变颜色的情况下进行组合。 谁能帮我把它们堆叠起来并合并成一个新的 RGB 文件?

清除问题的示例: inputfile1.tif 包含红色 A inputfile2.tif 包含蓝色 C inputfile3.tif 包含绿色 S …… inputfile15.tif 包含紫色 X

outputfile.tif包含红A,蓝C,绿S,...,紫X

This is how I want to stack the raster data

假设您有一个名为 tiffs 的文件夹,其中包含以下图像:

inputfile01.tif

inputfile02.tif

inputfile03.tif

inputfile15.tif

以下脚本使用第三方模块PIL打开您的.tif图像,并生成合成图像。您没有指定它们应该如何缝合在一起,所以这个脚本只是将它们从左到右放在一行中。它按照 pathlib.Path.glob 发现图像文件路径的顺序插入它们 - 在本例中是按字典顺序(这就是为什么我在通常只有一个数字的文件名中添加前导零的原因)。

def main():

    from PIL import Image
    from pathlib import Path
    from itertools import accumulate

    paths = Path("tiffs").glob("*.tif")

    images = list(map(Image.open, paths))

    offsets = list(accumulate((image.size[0] for image in images), initial=0))

    width = offsets[-1]
    height = max(image.size[1] for image in images)

    composite = Image.new("RGB", (width, height))

    for x_offset, image in zip(offsets, images):
        composite.paste(image, (x_offset, 0))
        image.close()

    composite.show()
    
    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

输出:

这应该适用于具有任何文件名的任意数量的图像。