Question

I have a segmented image 'a' of a signature made with a colored pen. The background is pure white. I need to compute the sum of r g b components of the foreground pixels, and the total pixels that constitute the foreground. Here is my code-

r=a(:,:,1);
g=a(:,:,2);
b=a(:,:,3);
rsum=0;
gsum=0;
bsum=0;
count=0;
for i=1:h
    for j=1:w
        if r(i,j)~=255 || g(i,j)~=255 || b(i,j)~=255
            rsum=rsum + r(i,j);   
            gsum=gsum + g(i,j);
            bsum=bsum + b(i,j);
            count=count+1; 
        end
    end
end

It computes the value of count correctly but rsum,gsum,bsum are all set to 255 which is clearly wrong. The matrix r,g,b is correct(shows pixels other than 255). Why does is not work?

Was it helpful?

Solution

It seems like the type of rsum, gsum and bsum is uint8 and it is saturated at 255. Try explicitly cast the sum to a different type.

msk = r < 255 | g < 255 | b < 255;
rsum = sum( double( r(msk) ) );
gsum = sum( double( g(msk) ) );
bsum = sum( double( b(msk) ) );
count = sum(msk(:));

PS,
It is best not to use i and j as variable names in Matlab.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top