I want to reclassify a raster based on equal intervals. For example, if the value is in the first interval, the raster cell should be ouput as 1; the second interval should be a 2, etc. So far I've using this bit of code, which kind of works, but it doesn't handle negative numbers at all (the raster I'm using has a range of -0.4 to 1).

How can I get this working as intended?

import rasterio
import numpy as np

def reclass(inRaster, outRaster, mode, classes):
    with rasterio.open(inRaster) as src:
        # Read as numpy array
        array = src.read()
        profile = src.profile

        # mask nodata values
        m_array = np.ma.masked_array(array, array == np.amin(array))
        if mode == 'EqualInterval':
            amin, amax = np.amin(m_array), np.amax(m_array)
            interval = (amax - amin) / classes

            for x in range(classes):
                if x == 0:
                    m_array[np.where(m_array < interval)] = x
                    m_array[np.where((m_array >= (interval * x)) & (m_array <= (interval * (x+1))))] = x

    with rasterio.open(outRaster, 'w', **profile) as dst:
        # Write to disk

reclass(inraster, outraster, 'EqualInterval', 6)

1 Answer 1


Try np.linspace() to create the bins at the specified interval, then np.digitize() to return the indices to the appropriate bins (i.e. the class)

bins = np.linspace(np.min(m_array), np.max(m_array), num=classes)
i = np.digitize(data, bins)

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.