MATLAB: How to analyze black and white pixels inside a ROI

Image Processing Toolboxmaskmaskingpixelroi

I am working with an image and I would like to select a ROI and analyse the pixels inside. Inside that ROI, I have black and white pixels. I would like to know the number of black pixels inside the ROI and the percentage of black pixels in that area. I was using binaryImage but then, I have all pixels white inside. Can anyone help me? This is my code:
[file, pathname] = uigetfile('*.jpg','Load Image');
a=imread(file);%color image
% Get the number of rows and columns, and, most importantly, the number of color channels.
[rows, columns, numberOfColorChannels] = size(a);
if numberOfColorChannels > 1
% It's a true color RGB image. We need to convert to gray scale.
Igray = rgb2gray(a);
end
% Show picture converted into gray.
imshow(Igray, []);
fontSize = 16;
% Draw the region with pixels you're interested in
hFH = imfreehand();
% Create a binary image ("mask") from the ROI object.
binaryImage = hFH.createMask();

Best Answer

You said that Igray has only black and white pixels - no "gray" pixels in between. Like 0 and 1 or 0 and 255. You can use this code to count the number of black and white pixels within the mask ("binaryImage") only
% Get a vector -- a 1-D list -- of pixel values in the mask.
pixelsInsideMask = Igray(binaryImage);
numTotalPixels = length(pixelsInsideMask);
numWhitePixels = nnz(pixelsInsideMask); % Count of number of non-zero pixels
numBlackPixels = numTotalPixels - numWhitePixels;