I am trying to filter an image with out using imfilter
. I should get the same results as imfilter
but I keep getting diffrent results. Can someone
This is modifies code and gives the exact same result as imfilter....
%# Let's first create a small test image from the built-in peppers image
original = im2double(imread('peppers.png'));
original = original(1:5,1:8,1);
filter = 1/9 * [-1 -1 -1 ; -1 17 -1 ; -1 -1 -1];
s = size(original);
r = zeros(s);
original=padarray(original,[1,1]);
for i = 2:s(1)
for j = 2:s(2)
temp = original(i-1:i+1,j-1:j+1) .* filter;
r(i-1,j-1) = sum(temp(:));
end
end
This gives the result matrix which is exactly same as with the function...
The size of r
should be the same as the original I think. And I don't understand why you convert to single precision using single
. Anyway, I think you want to do the following:
%# Let's first create a small test image from the built-in peppers image
original = im2double(imread('peppers.png'));
original = original(1:5,1:8,1);
filter = 1/9 * [-1 -1 -1 ; -1 17 -1 ; -1 -1 -1];
s = size(original);
r = zeros(s);
for i = 2:s(1)-1
for j = 2:s(2)-1
temp = original(i-1:i+1,j-1:j+1) .* filter;
r(i,j) = sum(temp(:));
end
end
The result is as follows:
r =
0 0 0 0 0 0 0 0
0 0.2336 0.2157 0.2514 0.2436 0.2257 0.2344 0
0 0.2453 0.2444 0.2671 0.2693 0.2418 0.2240 0
0 0.2741 0.2728 0.2397 0.2505 0.2375 0.2436 0
0 0 0 0 0 0 0 0
And with imfilter
, it is:
r2 = imfilter(original, filter)
r2 =
0.3778 0.3325 0.3307 0.3442 0.3516 0.3312 0.3163 0.3856
0.3298 0.2336 0.2157 0.2514 0.2436 0.2257 0.2344 0.3386
0.3434 0.2453 0.2444 0.2671 0.2693 0.2418 0.2240 0.3512
0.3272 0.2741 0.2728 0.2397 0.2505 0.2375 0.2436 0.3643
0.3830 0.3181 0.3329 0.3403 0.3508 0.3272 0.3412 0.4035
As you see, the results are the same except the ones on the borders. There are a few strategies to compute the ones on the borders as mirroring the image to the out of the borders, keeping them the same, etc. Please read the documentation of imfilter and choose one strategy.
Note that I didn't flipped filter
here since the filter is symmetric in both directions. And I recommend you to avoid loops! There are nested loops of depth four in your code!
Lastly, you can use 2-D convolution to do the same as imfilter
:
r3 = conv2(original, filter, 'same');
r3 =
0.3778 0.3325 0.3307 0.3442 0.3516 0.3312 0.3163 0.3856
0.3298 0.2336 0.2157 0.2514 0.2436 0.2257 0.2344 0.3386
0.3434 0.2453 0.2444 0.2671 0.2693 0.2418 0.2240 0.3512
0.3272 0.2741 0.2728 0.2397 0.2505 0.2375 0.2436 0.3643
0.3830 0.3181 0.3329 0.3403 0.3508 0.3272 0.3412 0.4035