You can not do the histogram on the original gray image since you are counting the areas after bwlabel
. One dirty method might work without calling hist
function, but you need to roughly estimate your maximum area of the connected components. Note that sometimes with one threshold you set, the area of some connected components are very large, but such a large value only occurs very few times (most times it is 1). You may consider ignore such a large area in your final image. Based on the image you showed, I used 200 as the permitted maximum connected component area.
MAP=zeros(101,200);
for k=0:0.01:1
bw_normal = im2bw(img, k);
bw = imcomplement(bw_normal);
[label,n] = bwlabel(bw);
stats = regionprops(label, 'Area');
for j=1:length(stats)
if stats(j).Area<=200
MAP(fix(k/0.01+1),stats(j).Area)=MAP(fix(k/0.01+1),stats(j).Area)+1;
end
end
end
imagesc(MAP)