[GIS] How to count raster pixels inside a vector/polygon layer in QGIS

classificationcountqgisrasterzonal statistics

I have a binary raster (two classes) and I would like to count the pixels of each class contained in a polygon.
My goal is to know the amount of pixels of each class of the raster contained in the polygon. So I can then calculate the percentage of each class.

I cannot vectorize/polygonize the raster, because its so huge and it takes so long. Also using clipper function to extract a new raster from the polygon is not optimal, as I have lots of polygons…

Is there any plugin or something, that can tell me that the area selected by the polygon has X amount of pixels/values of each class? I just want to know the amount of white and black pixels in the selected area!

EDIT: Ive thought that I can use ZonalStatistics plugin, to count all pixels in the polygon. then, extract with raster calculation one of the pixels, and then use ZonalStatistics count again to count the remaining pixels.

However, how can I delete in a binary raster (values 1 and 2) all pixels of value 1 (set them to nodata)?

Best Answer

you can set the values of either 1 or 2 to null with grass tool r.null enter image description here

after that you can use the zonal statistics plug in as you described

another approach could be to clip your raster to the polygons size and then have a look at it's properties and compute it's histogram. The histogram should only have two peaks at 1 and 2 telling you the count of pixels (couldn't test this solution as I didn't have a raster with only 1 and 2 values)