gustavgans
gustavgans

Reputation: 5191

Update a tif using gdal

I have a geotif and want to update the value of one pixel/cell. What is the best way (resource safe) to save this change? Do I have to use the WriteArray() function or is there a better solution for updating the same tif?

ds = gdal.Open("test.tif")
data = ds.ReadAsArray()

data[0][0] = 1

Upvotes: 0

Views: 3472

Answers (1)

Kersten
Kersten

Reputation: 984

If you open the dataset with the option GA_Update, instead of GA_ReadOnly you can update it directly. Also keep in mind that ReadAsArray() returns a numpy ndarray, which you have to adress with data[0, 0] instead of data[0][0].

ds = gdal.Open("test.tif", GA_Update)
data = ds.ReadAsArray()

data[0, 0] = 1

ds.GetRasterBand(1).WriteArray(data)

# close the dataset to flush it to disk
ds = None

If your image has one band this code will work. If it has multiple bands, say 5, ReadAsArray() will return a 3-dimensional array and you have to loop through your bands to write them.

for band in range(5):
    ds.GetRasterBand(band+1).WriteArray(data[band, :, :]) 

Upvotes: 4

Related Questions