[英]how can I load a single tif image in parts into numpy array without loading the whole image into memory?
所以有一個 4GB 的 .TIF 圖像需要處理,作為內存限制,我無法將整個圖像加載到 numpy 數組中,所以我需要從硬盤中延遲加載它。 所以基本上我需要並且需要在python中完成作為項目要求。 我也嘗試在 PyPi tifffile 中尋找 tifffile 庫,但我發現沒有任何用處,請幫忙。
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 分鍾,並且需要 270 MB 的內存峰值。
你在做什么處理? 您也許可以在 pyvips 中完成所有操作。 它比numpy快得多。
import pyvips
img = pyvips.Image.new_from_file("space.tif", access='sequential')
out = img.resize(0.01, kernel = "linear")
out.write_to_file("resied_image.jpg")
如果您想將文件轉換為其他尺寸較小的格式,此代碼就足夠了,並且可以幫助您在沒有任何內存峰值的情況下完成此操作,並且時間很短...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.