MATLAB: ¿How to sum determinated values from an image

matlab images rows columns avoid values how to sum bigger 255

Hi! I want to create a "median filtering" without medfilt2(). I created a random matrix just to visualize how the program works, but I'm suposed to apply this to any gray image (uint8).
I have this code right now
if true
% code
>> f=uint8(round(255*rand(10,9)));
>> [M,N]=size(f);
>> g=uint8(zeros(M+2,N+2));
>> g(2:end-1,2:end-1)=f
g =
0 0 0 0 0 0 0 0 0 0 0
0 252 35 241 105 90 200 57 28 80 0
0 17 56 173 154 248 177 69 46 46 0
0 240 46 252 191 88 2 172 25 86 0
0 5 11 196 149 226 215 122 125 54 0
0 174 27 86 141 116 235 159 49 130 0
0 200 157 169 149 105 197 60 228 231 0
0 136 240 62 131 56 11 45 25 160 0
0 226 90 75 21 32 96 212 11 26 0
0 229 105 173 183 79 180 196 142 100 0
0 160 251 135 254 185 186 238 197 14 0
0 0 0 0 0 0 0 0 0 0 0
>> for m=1:M
for n=1:N
h(m,n)=(g(m,n)+g(m,n+1)+g(m,n+2)+g(m+1,n)+g(m+1,n+2)+g(m+2,n)+g(m+2,n+1)+g(m+2,n+2))/8;
end
end
>> h
h =
14 32 32 32 32 32 32 32 15
32 32 32 32 32 32 32 32 32
17 32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32 32
>>
end
So I was wondering why the values of h were almost always 32, And I found that if I sum for example 14+18, it is 22, but if I sum 127+128 it gives me (in matlab, in the upper code) 255, if doesn't matter if the number is really bigger than 255. That's why when I do the median (/8) it gives me almost always 32 (255/8=31.87)
So, how can I avoid this? how can I sum the values of the images and how can matlab gives me the real result?
Thanks (And sorry if my english is so bad) 🙂

Best Answer

When you add two uint8 values the result will be a uint8 value and so will be at most 255. You need to convert the values to a type that can hold the maximum sum. Or use mean()
Related Question