您可以在不加载整个图像的情况下遍历图像中的像素吗? [英] Can you loop through pixels in an image without loading the whole image?
问题描述
我有一些非常大的图像.我不想将整个图像加载到内存中,我只想按行顺序对图像进行一次遍历.是否可以在 Python/scipy 中做到这一点?
I have some very large images. I don't want to load the whole image into memory, I just want to make a single pass through the image in row order. Is it possible to do this in Python/scipy?
我使用的是 .PNG,但我可以将它们转换为 PPM、BMP 或其他无损格式.
I'm using .PNG, but I could convert them to PPM, BMP or something else lossless.
推荐答案
GDAL (带有Python绑定)提供一些非常好的驱动程序.虽然它是一个地理空间包,但它可以很好地与 BMP 和 PNG 一起使用.此示例显示如何逐行加载 PNG:
GDAL (with Python bindings) offers some very good drivers for this. Although its a geospatial package, it works fine with BMP and PNG for example. This example show how to load a PNG row by row:
import gdal
# only loads the dataset
ds = gdal.Open('D:\\my_large_image.png')
# read 1 row at the time
for row in range(ds.RasterYSize):
row_data = ds.ReadAsArray(0,row,ds.RasterXSize,1)
ds = None # this closes the file
因此,它为您提供了一个Numpy数组,因此可以进行处理.您可以用类似的方式编写任何结果.
It gives you a Numpy array as a result, so ready for procesing. You could write any result in a similar fashion.
print type(row_data)
<type 'numpy.ndarray'>
print row_data.shape
(3, 1, 763)
print row_data
[[[ 0 0 255 ..., 230 230 0]]
[[ 0 0 252 ..., 232 233 0]]
[[ 0 0 252 ..., 232 233 0]]]
如果 PIL 或其他东西可以做到的话,安装一个专门用于阅读的包可能有点矫枉过正.但是它是一个可靠的选择,我已经像这样处理了30000 * 30000像素的图像.
Installing a package specific for reading might be a bit overkill if PIL or something else can do it. But its a robust option, i have processed images of 30000*30000 pixels like this.
这篇关于您可以在不加载整个图像的情况下遍历图像中的像素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!