pyvips 可以做到这一点。例如:
import sys
import numpy as np
import pyvips
image = pyvips.Image.new_from_file(sys.argv[1], access="sequential")
for y in range(0, image.height, 100):
area_height = min(image.height - y, 100)
area = image.crop(0, y, image.width, area_height)
array = np.ndarray(buffer=area.write_to_memory(),
dtype=np.uint8,
shape=[area.height, area.width, area.bands])
new_from_file 的 access 选项打开顺序模式:pyvips 只会按需从文件中加载像素,但限制是您必须从上到下读取像素。
循环以 100 条扫描线为单位向下运行图像。当然,你可以调整它。
我可以这样运行:
$ vipsheader eso1242a-pyr.tif
eso1242a-pyr.tif: 108199x81503 uchar, 3 bands, srgb, tiffload_stream
$ /usr/bin/time -f %M:%e ./sections.py ~/pics/eso1242a-pyr.tif
273388:479.50
因此,在这台可悲的旧笔记本电脑上,扫描一张 108,000 x 82,000 像素的图像需要 8 分钟,并且需要 270mb 的峰值内存。
你在做什么处理?您可能可以在 pyvips 中完成所有操作。它比 numpy 快很多。