Python 3: How to change image data in GDAL?

不想你离开。 提交于 2019-12-06 00:34:57

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).

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!