繁体   English   中英

如何读取 python 中的大 tif 文件?

[英]How to read a big tif file in python?

我正在从http://oceancolor.gsfc.nasa.gov/DOCS/DistFromCoast/加载一个 tiff 文件

from PIL import Image
im = Image.open('GMT_intermediate_coast_distance_01d.tif')

数据很大( im.size=(36000, 18000) 1.3GB),常规转换不起作用; 即, imarray.shape返回()

import numpy as np 
imarray=np.zeros(im.size)
imarray=np.array(im)

如何将此 tiff 文件转换为numpy.array

到目前为止,我已经测试了许多替代方案,但即使使用巨大的 16 位图像,也只有gdal始终有效。

您可以使用以下内容打开图像:

from osgeo import gdal
import numpy as np
ds = gdal.Open("name.tif")
channel = np.array(ds.GetRasterBand(1).ReadAsArray())

愿你没有太多的内存用于这个图像。你至少需要一些超过 1.3GB 的可用内存。

我不知道你对图像做了什么,你把整个读到你的记忆中,但我建议你尽可能一点一点地阅读它以避免炸毁你的电脑。 您可以使用Image.getdata()每次返回一个像素。

还可以在此链接上阅读更多有关Image.open内容:

http://www.pythonware.com/library/pil/handbook/

我有 1 到 3 GB 的巨大 tif 文件,并且在手动将 Image.py 源代码中的 MAX_IMAGE_PIXELS 的值更改为任意大数后,最终设法使用 Image.open() 打开它们:

from PIL import Image
im = np.asarray(Image.open("location/image.tif")

对于 Python 32 位 2.7 版,您受到在给定时间可以添加到堆栈的字节数的限制。 一种选择是分部分读入图像,然后调整各个块的大小并将它们重新组合成需要较少 RAM 的图像。

我建议为此使用软件包libtiffopencv

    import os
    os.environ["PATH"] += os.pathsep + "C:\\Program Files (x86)\\GnuWin32\\bin"
    import numpy as np
    import libtiff
    import cv2

    tif = libtiff.TIFF.open("HUGETIFFILE.tif", 'r')
    width = tif.GetField("ImageWidth")
    height = tif.GetField("ImageLength")
    bits = tif.GetField('BitsPerSample')
    sample_format = tif.GetField('SampleFormat')
    
    ResizeFactor = 10 #Reduce Image Size by 10
    Chunks = 8 #Read Image in 8 Chunks to prevent Memory Error (can be increased for 
    # bigger files)

    ReadStrip = tif.ReadEncodedStrip
    typ = tif.get_numpy_type(bits, sample_format)


    #ReadStrip
    newarr = np.zeros((1, width/ResizeFactor), typ)
    for ii in range(0,Chunks):
        pos = 0
        arr = np.empty((height/Chunks, width), typ)
        size = arr.nbytes
        for strip in range((ii*tif.NumberOfStrips()/Chunks),((ii+1)*tif.NumberOfStrips()/Chunks)):
            elem = ReadStrip(strip, arr.ctypes.data + pos, max(size-pos, 0))
            pos = pos + elem

        resized = cv2.resize(arr, (0,0), fx=float(1)/float(ResizeFactor), fy=float(1)/float(ResizeFactor))

        # Now remove the large array to free up Memory for the next chunk
        del arr
        # Finally recombine the individual resized chunks into the final resized image.
        newarr = np.vstack((newarr,resized))

    newarr = np.delete(newarr, (0), axis=0)
    cv2.imwrite('resized.tif', newarr)

您可以尝试使用“dask”库:

import dask_image.imread

ds = dask_image.imread.imread('name.tif')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM