# How to Calculate White/Black Ratio within a border of an image

2 views (last 30 days)
DannyP99 on 7 Jul 2020
Commented: Mahesh Taparia on 15 Jul 2020
I am trying to calculate the ratio of black to white in this image without including the large black background above and below the sliver. This is the original image:
This is the image after I binarize it:
In this binarized image, I need to calculate the black to white ratio without incorporating the background. How do I do that?

Mahesh Taparia on 15 Jul 2020
Edited: Mahesh Taparia on 15 Jul 2020
Hi
You can find the ratio of black to white part by removing the top and bottom black pixels into calculation. After removing those pixels, find the number of black pixels in the middle part (the organ) and take the ratio. For example, consider the sample code below:
gray=rgb2gray(a);
w=gray<multithresh(gray); %%%%%%%%%%%%% Set the threshold as per your calculation
figure;imshow(w)
conComp=bwconncomp(w);
nComp=[];
for i=1:size(conComp.PixelIdxList,2)
nComp=[nComp size(conComp.PixelIdxList{1,i},1)];
end
topBlackPortion=sum(maxk(nComp,2)); %%%%%Eliminating the 2 areas with maximum values which is top and bottom
remainingPortion=size(gray,1)*size(gray,2)-topBlackPortion;
remainingBlackPotion=sum(nComp)-topBlackPortion;
fractionOfPortion=remainingBlackPotion/remainingPortion; %%% this is the ratio of black portion in the central part
Hope it will help!

madhan ravi on 15 Jul 2020
Preallocation is really significant instead of appending an array.
Mahesh Taparia on 15 Jul 2020
Yeah, but it is a small array, does not take much time.