# Count pixels per class instance of a raster classification

I have a fairly easy problem but I can not find any algorithm for it. I have this kmeans classification of a windspeed pattern from a model output:

What I want now is to count the pixels in each patch of the classification. Basically meaning I want to count the coherent pixels of each instance. It would be furthermore awesome to have an algorithm to describe the shape of the instances. What I have found so far is a CNN which does an instance segmentation.
OpenCV instance segmentation

Now I wonder if there is something out there which does the job easier than a NN. Any algorithm/language is welcome!

Here is the dataset which is plotted: Dropbox Link to .npy file

• 2 things: [1] Image looks python - can you provide the associated array of the image that you've plotted - that'll help with finding a solution [2] Do you need a unique number for each isolated patch (i.e. so that a given patch count relates to the contiguous cells of a given classification) or a count of the number of pixels per classification group for the image generally? – ChrisWills Mar 29 at 9:56
• [1] did so see edit. [2] the first one: I need the count of each isolated patch doesn't matter which class it belongs to. – benschbob91 Mar 30 at 2:14
• Does this help? stackoverflow.com/questions/39346545/… – ChrisWills Mar 30 at 15:24

This solution, using a combination of gdal and python, will count the number of pixels per class (discrete dataset):

``````import gdal
import numpy as np

file = 'path to input image'

# Open the image and read in the values as an array
dataset = gdal.Open(file)
band = dataset.GetRasterBand(1)
Cols = dataset.RasterXSize
Rows = dataset.RasterYSize
data = band.ReadAsArray(0, 0, Cols, Rows).astype(np.float)

# subset the array to only contain classification values equal to 1
class1 = data[data==1]

# Repeat this for all classification values
class2 = data[data==2]
class3 = data[data==3]

# print the length of class1 (the number of pixels
with a classification value of 1)

print(len(class1))
print(len(class2))
print(len(class3))
``````

If you have a continuous dataset, you can count the number of pixels within a range instead using:

``````class1 = np.where((data>0) & (data< 1), 1, 0)
print(np.sum(class1))
``````
• This answer provides only the number of cells in one class. I need the number of cells in an instance of those classes. That is what i meant by "patch". – benschbob91 Mar 30 at 2:12
• @benschbob91 I see. I do have a solution for this but it requires rather specific software (RSGISLib). I think the easiest thing would be to represent connected pixels as objects and then count the pixels in each. A long way round would be to vectorize the dataset and then use zonal stats (count) – Nathan Thomas Mar 30 at 18:47
• – Nathan Thomas Mar 30 at 18:50