[GIS] raster calculation using rasterio

pythonpython-2.7raster-calculatorrasterio

I have a multi image tif with 7 bands and I try to use rastrio package to create a simple calculation.
I follow the docs but that not work for me.

any idea ?

here the code:

with rasterio.open('L7.tif') as src:
    #b1, b2, b3, b4, b5 = src.read()
    blue = src.read_band(1)
    green = src.read_band(2)
    red = src.read_band(3)
    nir = src.read_band(4)
    profile = src.profile
    profile.update(
        dtype=rasterio.float64,
        count=1,
        compress='lzw')

MI = numpy.zeros(blue.shape)
MI = (blue *green*red *nir  )

with rasterio.open('ndvi_python.tif', 'w', **profile) as dst:
    dst.write(NDMI.astype(rasterio.float64), 1)

error :

    blue = src.read_band(1)
AttributeError: 'DatasetReader' object has no attribute 'read_band'

if I try to :

with rasterio.open('L7.tif') as src:
    b1, b2, b3, b4, b5 = src.read()

then I take this error :

    b1, b2, b3, b4, b5 = src.read()
ValueError: need more than 1 value to unpack

Best Answer

You should be using read() method when using Rasterio version 1.0a12 (Rasterio reference).

The raster array for a raster band can be accessed by calling dataset.read() with the band’s index number. Following the GDAL convention, bands are indexed from 1.

The following is now the preferred method to read raster bands (Rasterio reference):

import rasterio

with rasterio.open('tests/data/RGB.byte.tif') as src:
    data = src.read((1, 2, 3))
    band1 = src.read(1)

This will return a Numpy N-D array of the form:

>>> band1
array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint16)