# How do I calculate number of white pixels inside ROI?

4 views (last 30 days)
Alexander Hsu on 9 Jul 2020
I'm trying to calculate the number of white pixels in my roi of the last image which has already been segmented and converted to binary. I need the number of white pixels within the roi and not the entire image. I've copied my code below. The area im having issues with is commented ROI. My image is in the answers section.
clc;
close all;
clear;
% Get dimensions of image
[rows, columns, numberOfColorChannels] = size(grayImage);
if numberOfColorChannels > 1
grayImage = rgb2gray(grayImage);
end
subplot(2, 3, 1);
imshow(grayImage,[]);
title('grayscale');
% Binarize image by thresholding
subplot(2, 3, 2);
title('binary')
% Get rid of small blobs
% Find areas and perimeters
stats = regionprops(labeledImage,'Area', 'Perimeter');
allAreas = [stats.Area];
sortedAreas = sort(allAreas,'descend');
allPerimeters = [stats.Perimeter];
% Compute circularities
circularities = allPerimeters .^ 2 ./ (4 * pi * allAreas)
sortedC = sort(circularities, 'descend');
% Keep only blobs that are nowhere close to circular or compact.
minAllowableCircularity = .5;
keeperIndexes = find(circularities >= minAllowableCircularity);
subplot(2, 3, 3);
title('removeWhite')
% Get rid of black islands
subplot(2, 3, 4);
title('removeBlack')
% Plaque count
Rmin = 7;
Rmax = 11;
subplot(2, 3, 5)
title('plaqueCount');
length(centers)
% ROI
Rmin2 = 150;
Rmax2 = 300;
subplot (2, 3, 6);
title('roi');
KSSV on 9 Jul 2020

Madhav Thakker on 21 Aug 2020
Hi
You can use the inpolygon function to check whether a query point lies inside the polygon. You can make a polygon from your ROI and count the number of white pixels that lie inside the polygon.
I am attaching the code for better understanding.
xc = roi.Center(1);
yc = roi.Center(2);
n = 200;
theta = (0:n-1)*(2*pi/n);
x = xc + r*cos(theta);
y = yc + r*sin(theta);
P = polyshape(x,y);
xpoly = P.Vertices(:,1);
ypoly = P.Vertices(:,2);
inpolygon(xquery, yquery, xpoly, ypoly);
inpolygon(xquery, yquery, xpoly, ypoly);
disp(nnz(inpolygon(xquery, yquery, xpoly, ypoly)))
Hope this helps.
inpolygon documentation for better understanding –