MATLAB: Histogram-based segmentation error

histogram-based segmentationimage processing

Hey guys, So I'm working on histogram-based segmentation program using MatLab and I am able to successfully assign ranges to the histogram and obtain the corresponding binary images (as seen below),
but when I implemented the following code:
MATLAB code:
m1 = sum(sum(B1.*A))/sum(sum(B1));
m2 = sum(sum(B2.*A))/sum(sum(B2));
m3 = sum(sum(B3.*A))/sum(sum(B3));
m4 = sum(sum(B4.*A))/sum(sum(B4));
m5 = sum(sum(B5.*A))/sum(sum(B5));
m6 = sum(sum(B6.*A))/sum(sum(B6));
C = (m1 * B1) + (m2 * B2) + (m3 * B3) + (m4 * B4) + (m5 * B5) + (m6 * B6);
figure, subplot(2,1,1), imshow(A), title('Original Image');
subplot(2,1,2), imshow(C), title('Histogram-based segmentation');
And I got the following error, "Error using . Integers can only be combined with integers of the same class, or scalar doubles." % Error in A3_Prob2 (line 46) m1 = sum(sum(B1.*A))/sum(sum(B1));*
so I tweaked my code, which is as follows,
MATLAB code:
m1 = sum(sum(B1.*(double(A))))/sum(sum(B1));
m2 = sum(sum(B2.*(double(A))))/sum(sum(B2));
m3 = sum(sum(B3.*(double(A))))/sum(sum(B3));
m4 = sum(sum(B4.*(double(A))))/sum(sum(B4));
m5 = sum(sum(B5.*(double(A))))/sum(sum(B5));
m6 = sum(sum(B6.*(double(A))))/sum(sum(B6));
C = (m1 * B1) + (m2 * B2) + (m3 * B3) + (m4 * B4) + (m5 * B5) + (m6 * B6);
subplot(2,1,1), imshow(A), title('Original Image');
subplot(2,1,2), imshow(C), title('Histogram-based segmentation');
And I got the output image as seen below.I know the histogram-based segmented image won't be just "white", So where am I going wrong?? Could someone highlight the error in my coding/guide me please?
Thanks

Best Answer

Use
imshow(C, [])
Because you scaled B with 255, the m values are within the range [0 255], so your C is in the range [0,256^2].
You can improve your code by computing the B without the 255 scaling
B1= A >= 0 & A <= 30;
and adding
A = im2double(A);
before computing the m-values. And the m-values can be computed as
m1 = sum2(B1.*A)/nnz(B1);
Then C is in the range [0,1], and can be viewed with
imshow(C)
And of course if would be better if you vectorize your code.