0

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?

knedlsepp
  • 6,065
  • 3
  • 20
  • 41
user1727119
  • 117
  • 2
  • 11
  • 2
    try to avoid loops if at all possible. Matlab is powerful when dealing with images. – Russell Uhl Jun 05 '14 at 13:55
  • thanks, i'm new to matlab and image processing. moving from a c background, it's hard to leave loops behind :P – user1727119 Jun 05 '14 at 14:04
  • i hear that. I was thrust upon matlab for a class and was totally lost. It's a completely new and different style of programming for people used to C-like languages. – Russell Uhl Jun 05 '14 at 14:44

1 Answers1

2

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.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371