11

I have a raster file where all cells have values between -3 and 7, no data value is -9999. How can I calculate the number of cells with a specific value, e.g. 6? Can I use the calculator?

16

Two possible easy ways:
1.)

  • Install the QGIS raster calculator if it isn't already available (you did not specify which QGIS version you are using)
  • Use the QGIS raster calculator with a formula like this "Corine@1" = 23. This will extract all cells with value 23 into a new raster
  • Then use the "Raster Layer statistics" tool within the SEXTANTE toolbox for QGIS to calculate the total sum of cells.

enter image description here

2.) If you want a more sophisticated overview over the number of raster cells you could use the LecoS plugin for QGIS.

  • Make sure you have installed Numpy, Scipy and PIL on your computer. Find an instruction how to do it on Windows on my Blog or here.
  • Download LecoS from the Plugin installer and enable it. No errors should pop up.
  • Run the Landcover statistics tool (Menu Raster -> Landscape Ecology -> Landcover statistics) with your raster shape. Make sure that your shape has a correct projection, a set no-data value and also square raster cells.
  • Choose the options as displayed below. You can save the results in a .csv file. The outputs contains the total landcover (cellnumber * raster cellsize^2) for all your landcover classes. enter image description here
  • 1
    Just to note that these days the toolbox is called Processing. – Luís de Sousa Jul 20 '16 at 12:40
9

EDIT 3: I converted the code below into quite usable SEXTANTE script that give following output: enter image description here

Detailed instruction and the download link can be found here.


You can use python console for this task. Copy code provided below, paste it into a text file and save it as "some_script.py" for example. Next time you will need to count cell values open python console in QGIS, hit 'show editor' button and open this script there. Then replace 'raster_path' in the forth row in script with actual path to your raster and save changes. Then run script and in the console output (to the left from editor on screenshot below) you will see number of cells for every value you have in the raster.

Note that you will need to have python-numpy installed for this script to work.

EDIT: Also, if you don't need exact values but you would rather want to see distribution of values, you may use approach described here.

EDIT 2: more advance version of script provided. Now it works with multi band rasters and processes NaN values.

from osgeo import gdal
import sys
import math

path = "raster_path"

gdalData = gdal.Open(path)
if gdalData is None:
  sys.exit( "ERROR: can't open raster" )

# get width and heights of the raster
xsize = gdalData.RasterXSize
ysize = gdalData.RasterYSize

# get number of bands
bands = gdalData.RasterCount

# process the raster
for i in xrange(1, bands + 1):
  band_i = gdalData.GetRasterBand(i)
  raster = band_i.ReadAsArray()

  # create dictionary for unique values count
  count = {}

  # count unique values for the given band
  for col in range( xsize ):
    for row in range( ysize ):
      cell_value = raster[row, col]

      # check if cell_value is NaN
      if math.isnan(cell_value):
        cell_value = 'Null'

      # add cell_value to dictionary
      try:
        count[cell_value] += 1
      except:
        count[cell_value] = 1

  # print results sorted by cell_value
  for key in sorted(count.iterkeys()):
    print "band #%s - %s: %s" %(i, key, count[key])

enter image description here

  • It's actually much easier than using a loop. You can get the counts directly using numpy: count = dict(zip(*numpy.unique(a, return_counts=True))). You may need to ensure you're running 64-bit Python to avoid memory errors, though. Although I haven't tested how that handles NaN. – jpmc26 May 12 '18 at 6:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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