简体   繁体   English

Python 3:如何在GDAL中更改图像数据?

[英]Python 3: How to change image data in GDAL?

I have a GeoTIFF image that contains a color table and a single raster band with 8-bit table keys, and that uses LZW compression, that I load with gdal.Open . 我有一个GeoTIFF图像,其中包含一个颜色表和一个带有8位表键的光栅带,并使用LZW压缩,我用gdal.Open加载。 I also have a numpy array containing 24-bit RGB-values (for a blurred version of the image), corresponding to three 8-bit raster bands. 我还有一个包含24位RGB值的numpy数组(对于图像的模糊版本),对应于三个8位光栅带。 I need to substitute these three raster bands for the raster band that is currently in the image, and then save the image (preferably as a new file if possible). 我需要将这三个栅格波段替换为当前在图像中的栅格波段,然后保存图像(如果可能,最好保存为新文件)。 How do I do that? 我怎么做?

I would like to keep the data in the numpy array in RGB form, so I would like to end up with three raster band instead of one. 我想将数据保存在RGB格式的numpy数组中,所以我想最终得到三个栅格带而不是一个。 I see that there is an AddBand method, but how do I remove an existing band (or modify it, since the bands happen to have the same bit-depth)? 我看到有一个AddBand方法,但是如何删除现有的波段(或修改它,因为波段碰巧具有相同的位深度)? Also, if I make the image contain three bands instead of just one, do I need to do something more to specify that the three bands represent R, G and B? 另外,如果我让图像包含三个波段而不是一个波段,我是否需要做更多的事情来指定三个波段代表R,G和B?

The way I would do it, to just create a fresh copy of your template raster with the new values ... If you want to avoid having copies at all costs, you could also overwrite. 我会这样做,只需使用新值创建模板栅格的新副本......如果您想不惜一切代价避免复制,也可以覆盖。 But creating a copy is less error prone, and you can retain the original. 但创建副本不易出错,您可以保留原始副本。

This function assumes that you have an array arr , which has three bands in the third dimension (so 2nd axis). 此函数假定您有一个数组arr ,它在第三维中有三个波段(因此第二轴)。

import gdal

def createRGB(template,arr,filename):
    '''Creates a copy of a 3-band raster with values from array

    Arguments:

        template: Path to template raster
        arr: Value array with dimensions (r,c,3)
        filename: Output filename for new raster 
    '''

    # Open template
    t = gdal.Open(template)

    # Get geotiff driver
    driver = gdal.GetDriverByName('GTiff')

    # Create new raster
    r = driver.Create(filename, t.RasterXSize, t.RasterYSize, 3, gdal.GDT_Byte,['COMPRESS=LZW'])

    # Set metadata
    r.SetGeoTransform(t.GetGeoTransform())
    r.SetProjection(t.GetProjection())

    # loop through bands and write new values
    for bix in range(3):

        rb = self.raster.GetRasterBand(bix+1)

        # Write array
        rb.WriteArray(arr[...,bix])

    # Close datasets
    t = None
    r = None
    rb = None

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

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