2

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

1 Answer 1

3

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)
2
  • thank you do much now working but I have one more question.i take this message RuntimeWarning: divide by zero encountered in divide NDMI = (blue *green*red *nir ) I think is fro this line numpy.zeros(blue.shape) any idea what is this ?
    – Mar
    Commented Feb 2, 2018 at 15:25
  • I would recommend opening a new question with the code that is causing the error. I do not think I would be able to address your question properly in the comments.
    – Aaron
    Commented Feb 2, 2018 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.