How to count the number of pixels with a specific value of a .gif file in QGIS

Try out my code (as script) at the Python Console of QGIS:

from os import path
import struct
from osgeo import gdal

def countRasterValue(val):

    layer = iface.activeLayer()
    provider = layer.dataProvider()

    fmttypes = {'Byte':'B', 'UInt16':'H', 'Int16':'h', 'UInt32':'I', 'Int32':'i', 'Float32':'f', 'Float64':'d'}

    my_path = provider.dataSourceUri()

    (root, filename) = path.split(my_path)

    dataset = gdal.Open(my_path)

    band = dataset.GetRasterBand(1)

    print "rows = %d columns = %d" % (band.YSize, band.XSize)

    BandType = gdal.GetDataTypeName(band.DataType)

    print "Data type = ", BandType

    print "Executing for %s" % filename
    print "in %s" % root

    count_value = 0

    for y in range(band.YSize):

        scanline = band.ReadRaster(0, y, band.XSize, 1, band.XSize, 1, band.DataType)
        values = struct.unpack(fmttypes[BandType] * band.XSize, scanline)

        for value in values:
            if value == val:
                count_value += 1

    print "Raster count = %d of %d" % (count_value, val)

    dataset = None

countRasterValue(1)

I tested my code with a gif (Graphics Interchange Format) raster whose values were between 1 and 3 (see next image).

enter image description here

It worked with a count of 205 for 1 values (red color).

enter image description here


Simpler and faster with gdalnumeric (gdal+numpy):

import gdalnumeric

raster_file = gdalnumeric.LoadFile("/path/to/file.tif")
pixel_count = (raster_file == 1).sum()  # for pixel value = 1
print(pixel_count)

Inside Qgis (for the active layer selected):

import gdalnumeric
layer = iface.activeLayer()
provider = layer.dataProvider()

raster_file = gdalnumeric.LoadFile(provider.dataSourceUri())
pixel_count = (raster_file == 1).sum()  # for pixel value = 1
print(pixel_count)

Tags:

Count

Pixel

Qgis