MATLAB: I exactly want to do same thing explained in “what should I do so that only gray image converts into binary , not the black backgroung while moving the threshold.” question. But when I count white and black pixels in ROI I am getting 0.

image processingImage Processing Toolbox

I exactly want to do same thing explained in "what should I do so that only gray image converts into binary , not the black background while moving the threshold." question. But when I count white and black pixels in ROI I am getting 0.
Following is my code.
if true
close all;
clear all;
%Read image in Matlab
ReadImg = imread('Sanjivjadhv25rckd.jpg');
figure(1); imshow(ReadImg);title('Original Image');
%Convert image into Gray Image
GrayImg = rgb2gray(ReadImg);
figure(2); imshow(GrayImg);title('Gray Image');
%ROI selection manually
height = 254 %189;
width = 254 %229;
[col1, row1] = ginput(1);
row2 = row1 + height;
col2 = col1 + width;
CropedImg = ReadImg(row1:row2, col1:col2);
figure(3); imshow(CropedImg); title('Region of Intrest');
%Removal of spekel noise using Median filter
medianFilteredIm2 = medfilt2(CropedImg,[4,4]);%using [4,4] window size getting better results
%figure(3); imshow(medianFilteredIm1);title('output of median filter');
figure(4); imshow(medianFilteredIm2);title('output of median filter');
%Segmentation of Kidney part using imfreehand
h = imfreehand();
mask = createMask(h);
medianFilteredIm2(~mask) = 0;
figure(5); imshow(medianFilteredIm2);
GrayThresh = 0.4; %graythresh(medianFilteredIm2);
BinaryImg = im2bw(medianFilteredIm2,GrayThresh);
figure(10); imshow(BinaryImg);title('Binary Image');
filledBinaryImage = imfill(BinaryImg, 'holes');
pixelsInROI = medianFilteredIm2(filledBinaryImage);
numBlackPixels = sum(pixelsInROI == 0);
numWhitePixels = sum(pixelsInROI == 255);
end
Following are images.

Best Answer

I don't understand the question you quoted (due to bad grammar), and don't understand yours either. But I think you want this:
numWhitePixels = sum(filledBinaryImage(:));
numBlackPixels = numel(filledBinaryImage) - numWhitePixels ;