avinash k
avinash k

Reputation: 25

What does `filter2` do in this code?

function G=costfunction(im) 
   G=zeros(size(im,1),size(im,2));
   for ii=1:size(im,3) 
      G=G+(filter2([.5 1 .5; 1 -6 1; .5 1 .5],im(:,:,ii))).^2; 
   end
end

Here, im is an input image (rgb image). What will this cost function return?

Upvotes: 1

Views: 873

Answers (2)

Cris Luengo
Cris Luengo

Reputation: 60680

This bit:

filter2([.5 1 .5; 1 -6 1; .5 1 .5],im(:,:,ii))

applies a Laplace filter to one 2D slice of im. Usually, the Laplace filter is implemented as [0 1 0; 1 -4 1; 0 1 0] or [1 1 1; 1 -8 1; 1 1 1]. I guess whoever wrote this code couldn't decide between those two and took the average.

The loop runs through each of the 2D slices in the 3D image im, and adds the square of each of the results together. If im is an RGB image, it will apply the filter to each of the color channels, and add the square of the results.

The Laplace operator gives a strong negative response on thin lines in the image, as well as responses (positive and negative) around the edges in an image. By taking the square, all responses are positive. Note that the cost function will be close to zero on edges, but high just inside and outside the edges.

Upvotes: 3

Diogo
Diogo

Reputation: 171

Assuming that filter2 is the same used for image processing(as tagged in the question) it should do a 2d linear filtering, im will get its data filtered in the matrix [.5 1 .5; 1 -6 1; .5 1 .5] with the 2d FIR filter. For the return, G should be that zeros(size(im,1),size(im,2)) plus all the processed images there.

Upvotes: 0

Related Questions