Clear Filters
Clear Filters

How to find the percentage/number of pixels in each class of an indexed image?

2 views (last 30 days)
I have a cropped indexed image with 7 classes and I have to find the percentage/number of pixels in each class.
fcls = readgeoraster('Cropped_FCLS.tif');
fcls(fcls==0)=NaN;
figure, imagesc(fcls)
colormap(jet(numel(classNames))); %% the classNames are a part of a larger code
colorbar('Ticks',1.5:0.9:numel(classNames),'TickLabels',classNames);
numberOfBins = max(fcls(:));
countsPercentage = 100 * hist(fcls(:), numberOfBins) / numel(fcls);
The above code is giving me incorrect values as they do not add upto 100. I values I am getting are :
countsPercentage =
0.1541 1.9319 0 0.0006 1.0463 0.0362 0.1464
I am unable to make the value of the background pixels zero as well (shown as blue in the image) which I think is the reason for not getting correct results for percentage.

Accepted Answer

Image Analyst
Image Analyst on 2 Jul 2021
If you don't want to consider index 0 (class 0), just make a histogram and don't consider that
% fcls = 0:10 % Test data
maxIndex = max(fcls(:))
% Define histogram edges.
edges = 0 : maxIndex + 1
% Get counts of all classes, including 0.
counts = histcounts(fcls, edges)
% Let's ignore class 0
counts = counts(2:end)
% Normalize
countsPercentage = 100 * counts / sum(counts)
  2 Comments
Anwesha Sharma
Anwesha Sharma on 4 Jul 2021
This is perfect. Thanks a lot.
If I may add another question here, is it possible to make the background pixel values zero in the image(I mean make the background either white or black)? If so, please suggest how should I do it? Or should I post it as another question?
Thanks a lot.
Image Analyst
Image Analyst on 4 Jul 2021
Yes, you need to set the first row of the colormap to 0 for black or 1 for white:
maxIndex = max(fcls(:))
cmap = jet(maxIndex); % Jet colormap
% Make 0 data value show up as black
cmap(1, :) = 0;
imshow(fcls, 'Colormap', cmap);
colorbar;

Sign in to comment.

More Answers (1)

Chunru
Chunru on 2 Jul 2021
Remove the nans before the line 'numberOfBins = max(fcls(:))'. This way the hist will not count on nans.
fcls = fcls(:); fcls = fcls(~isnan);

Categories

Find more on Images in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!