我试图用PIL / Pillow输出生成的大图像,但是当图像尺寸变大时会中断。
因此,根据我在SO上阅读的内容,我正在尝试使用Vips。
我生成的数据是numpy的RGB值数组。我想将其转换为Vips图像,以便保存。但是我不知道如何将像素数据转换为Vips。
import numpy
import gi
gi.require_version('Vips', '8.0')
from gi.repository import Vips
WIDTH=32768
HEIGHT=32768
UCHAR=Vips.BandFormat.UCHAR
# Create an RGB black image
black_space = numpy.zeros( ( WIDTH, HEIGHT, 3 ), dtype=numpy.uint8 )
# this doesn't work
vips_image = Vips.Image.new_from_memory( black_space, WIDTH, HEIGHT, bands=3, format=UCHAR )
vips_image.write_to_file( "space_32k.tiff" )
当然,创建Vips图像时它会失败并显示错误:
Traceback (most recent call last):
File "./bad_vips.py", line 14, in <module>
vips_image = Vips.Image.new_from_memory( black_space, WIDTH, HEIGHT, bands=3, format=UCHAR )
TypeError: Item 0: expected int argument
是否有一种转换numpy数组的方法,使其可与Vips一起使用?
我也尝试传递black_space.data
,但随后得到:
NotImplementedError: Item 0: multi-dimensional sub-views are not implemented
答案 0 :(得分:1)
您正在使用旧的libvips Python接口-现在有一个更新的接口,它好很多了:
https://github.com/libvips/pyvips
此处的文档:
https://libvips.github.io/pyvips/
a section关于链接libvips和numpy。您的示例为:
import numpy
import pyvips
WIDTH = 100
HEIGHT = 100
# Create an RGB black image
black_space = numpy.zeros((WIDTH, HEIGHT, 3), dtype=numpy.uint8)
# reshape into a huge linear array
linear = black_space.reshape(WIDTH * HEIGHT * 3)
vips_image = pyvips.Image.new_from_memory(linear.data, \
WIDTH, HEIGHT, bands=3, format="uchar")
vips_image.write_to_file("huge.tif")
reshape
是免费的(我认为),因此应该高效。回购中还有一个示例程序:
https://github.com/libvips/pyvips/blob/master/examples/pil-numpy-pyvips.py