Implement IMFILTER in Matlab

I am trying to filter an image without using imfilter . I should get the same results as imfilter , but I keep getting different results. Can someone tell me where I was wrong?

 orignal=imread('obj6__17.png'); filter=1/9*[-1 -1 -1 ; -1 17 -1 ; -1 -1 -1]; s=size(orignal); r=zeros(s(1)); temp = zeros(3); for i= 2: s(1)-1 for j = 2: s(2)-1 for n= 1: 3 for m= 1:3 temp(n,m)=orignal(i+2-n,j+2-m)*filter(n,m); end end r(i,j)=sum(single(sum(temp))); end end 
+7
source share
2 answers

The size r should match the original I think. And I don’t understand why you are converting to single precision with single . In any case, I think you want to do the following:

 %# Let 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 , this 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 can see, the results are the same as those indicated at the borders. There are several strategies for calculating borders at borders, such as reflecting an image at borders, keeping them the same, etc. Please read the imfilter documentation and choose one strategy.

Note that I did not flip the filter here, as the filter is symmetrical in both directions. And I recommend that you avoid cycles! Your code has nested depth of field loops!

Finally, you can use two-dimensional 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 
+7
source

This modifies the code and gives the same result as imfilter ....

 %# Let 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 a matrix of results that is exactly the same as with the function ...

0
source

All Articles