You can use rasterio to interface with NumPy arrays. To read a raster to an array:
import rasterio
with rasterio.open('/path/to/raster.tif', 'r') as ds:
arr = ds.read() # read all raster values
print(arr.shape) # this is a 3D numpy array, with dimensions [band, row, col]
This will read everything into a 3D numpy array arr
, with dimensions [band, row, col]
.
Here is an advanced example to read, edit a pixel, then save it back to the raster:
with rasterio.open('/path/to/raster.tif', 'r+') as ds:
arr = ds.read() # read all raster values
arr[0, 10, 20] = 3 # change a pixel value on band 1, row 11, column 21
ds.write(arr)
The raster will be written and closed at the end of the "with" statement.