I have few hundred raster files and I want to count the number of pixels having values within a specific range. Following code works well when using == operator e.g., raster_file == 25, but gives totally wrong results when I use a range e.g., (raster_file >= 0) & (raster_file <= 25)

import os, sys
import numpy as np
import gdalnumeric
path = ('dir')
for rasters in os.listdir(path):
    raster_file = gdalnumeric.LoadFile(rasters)
    pixel_count = ((raster_file =>0) & (raster_file <= 25)).sum()

1 Answer 1


Your syntax is incorrect, it should be:

((raster_file <=0) + (raster_file >= 25)).sum()
  • Syntax runs perfectly. And I was able to figure out where the problem was. I checked for the no-data value of the raster files and that was unfortunately set to 0 and these zeros were counted as data. Jan 13, 2022 at 17:15

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