How to find the percentage/number of pixels in each class of an indexed image?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Anwesha Sharma
le 1 Juil 2021
Commenté : Image Analyst
le 4 Juil 2021
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/671798/image.jpeg)
0 commentaires
Réponse acceptée
Image Analyst
le 2 Juil 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 commentaires
Image Analyst
le 4 Juil 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;
Plus de réponses (1)
Chunru
le 2 Juil 2021
Remove the nans before the line 'numberOfBins = max(fcls(:))'. This way the hist will not count on nans.
fcls = fcls(:); fcls = fcls(~isnan);
Voir également
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!