【问题标题】:How to convert image to RGBA in `vips` tool? How to make sure two images have the same number of bands?如何在“vips”工具中将图像转换为 RGBA?如何确保两个图像具有相同数量的波段?
【发布时间】:2015-09-01 17:21:35
【问题描述】:

我正在编写一个 shell 脚本来连接一些图像,我正在使用 vips 命令行,因为它对内存的要求很低(而且我打算处理非常大的图像)。

但是,如果一个图像是 RGB,另一个是 RGBA,它会失败:

$ vips insert foo3.png foo4.png foo.png 64 0 --expand --background '0 0 0 0'
insert: images must have the same number of bands, or one must be single-band

$ file foo?.png
foo3.png: PNG image data, 1 x 1, 8-bit/color RGB, non-interlaced
foo4.png: PNG image data, 1 x 1, 8-bit/color RGBA, non-interlaced

使用vips时如何将输入图像转换为RGBA?我一直在搜索文档,但找不到。

我也愿意使用nip2 工具,它也使用libvips。我不愿意使用 ImageMagick(或类似工具),因为该脚本最终会处理 20k×20k 像素大的图像,这需要数 GB 的 RAM,比我现在的要多。

【问题讨论】:

标签: image vips


【解决方案1】:

开启recent vips versions

vips bandjoin_const source.png dest.png 255

255 表示不透明,0 表示透明。

【讨论】:

    【解决方案2】:

    我会用 pyvips 用 Python 编写整个内容。例如:

    #!/usr/bin/python3
    
    import sys 
    import pyvips
    
    if len(sys.argv) < 3:
        print("usage: join outfile in1 in2 in3 ...")
        sys.exit(1)
    
    def imopen(filename):
        im = pyvips.Image.new_from_file(filename, access="sequential")
        if not im.hasalpha():
            im = im.addalpha()
    
        return im
    
    images = [imopen(filename) for filename in sys.argv[2:]]
    image = images[0]
    for tile in images[1:]:
        image = image.join(tile, "horizontal", expand=True)
    
    image.write_to_file(sys.argv[1])
    

    如果可能的话,我会使用 TIFF 而不是 PNG——PNG 非常慢。

    【讨论】:

    • 如果有图片是 BW 怎么办?我刚开始使用 pyvips,即使在查看文档时,它也完全不明显和令人沮丧。我只是想在 transparent 背景上生成文本。我不在乎在将 alpha() 添加到 text() 输出后只有两个波段,为什么不将它们自动转换为最高数量的波段?
    • 您混合了 RGB 和单色图像?您可以在 new_from_file 之后添加 im = im.colourspace('srgb') 以将所有内容移动到 RGB。
    • 并非总是可以自动转换为最高数量的频段。如果您有 CIELAB 和 RGB 的混合物怎么办?还是高光谱和 CMYK? libvips 将转换为公共空间留给用户,除了将两者都转换为通用数字格式等显而易见的事情。
    【解决方案3】:

    不是最好的解决方案,但作为一种解决方法,如果输入图像足够小:

    convert "foo3.png" "png32:tmp.png"
    vips insert tmp.png foo4.png foo.png 64 0 --expand --background '0 0 0 0'
    

    基本上,我使用 ImageMagick 转换为临时 RGBA 文件,然后在该文件上使用 vips。它只适用于小文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-11
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多