Abdullah Shahriar
Abdullah Shahriar

Reputation: 375

Problem with adding two elements in MATLAB

I'm trying to write a function for blurring images. (I'm aware of imfilter command. Just trying to implement it in my own way). I've the following function which takes a uint8 matrix as argument img.

function output=bl(img,w)
row=size(img,1);
col=size(img,2);
g_size=(2*w+1)^2;
output=uint8(zeros(row,col));
for ii=1:row
    for jj=1:col
        s=0;
        corner=[ii jj]-w;
        for r=corner(1):(corner(1)+(2*w))
            for c=corner(2):(corner(2)+(2*w))
                if((r>0 && r<=row) && (c>0 && c<=col))
                    s=s+img(r,c); %PROBLEMATIC LINE
                    fprintf('The value of s is %d\n',s);
                end
            end
        end     
        m=s/g_size;
        output(ii,jj)=fix(m);
        s=0;
    end
end
end

I'm having trouble with the line marked as "PROBLEMATIC LINE". The line of code was supposed to add previous value of s with img(c,r). But surprisingly each time the line runs, the previous value of s becomes 0. What am I doing wrong here? How can I solve this?

Upvotes: 1

Views: 63

Answers (1)

Max
Max

Reputation: 4045

The problem is that your problematic line casts the result to a uint8. If you add more and more integers, you will eventually exceed the limit value of 255 (more cannot be represented with 8 bit). See:

s = 0 % s = 0; class double
s = s + uint8(200) % s = 200; class uint8
s = s + uint8(200) % s = 255; class uint8

The reason for this is that MATLAB cannot add different types, so it implicitly cast its default type double to a unit8. You will see that this fails if you would initialize s as a certain type other than double

s = uint16(0);
s = s + uint8(200) % this will produce an error

Error using +
Integers can only be combined with integers of the same class, or scalar doubles.

You will get around this by casting the image manually:

s = uint16(0) % s = 0; class uint16
img = uint8(200); % img = 200; class uint8
s = s + uint16( img ) % s = 200; class uint16
s = s + uint16( img ) % s = 400; class uint16

uint16 should suite your needs as you can represent numbers up to 2^16-1 = 65535 with it.

Upvotes: 1

Related Questions