Why is my Laplacian of Gaussian function different from fspecial even though my Gaussian function is correct?

8 ビュー (過去 30 日間)
I'm trying to create a Gaussian as well as a Laplacian of Gaussian filter. I'm following the algorithms on the fspecial page. For the Gaussian function I have
lin = round(linspace(-floor(kernelSize/2),floor(kernelSize/2),kernelSize));
[X,Y] = meshgrid(lin,lin);
kernel = exp(-(X.^2 + Y.^2)/(2*sigma^2));
kernel = kernel/sum(kernel(:));
fspecial('gaussian',kernelSize,sigma) returns the same output as my code above.
But for my LoG code, the answers are different. The code I wrote is
lin = round(linspace(-floor(kernelSize/2),floor(kernelSize/2),kernelSize));
[X,Y] = meshgrid(lin,lin);
hg = exp(-(X.^2 + Y.^2)/(2*(sigma^2)));
kernel = ((X.^2 + Y.^2-(2*(sigma^2))).*hg)/(2*pi*(sigma^6)*sum(hg(:)));
Running fspecial('log',kernelSize,sigma) gives a different output. I'm running both these filters for edge detection and because of the difference in outputs, fspecial is doing a better job of detecting edges (for log).
Please help me out!

回答 (1 件)

Dimitris Iliou
Dimitris Iliou 2017 年 5 月 19 日
If I understand correctly, you wrote your own implementation of LoG but when you compare it with the built-in fspecial the results are different.
I ran the code you provided to try to find where the discrepancy occurs. If you modify your code to the following:
lin = round(linspace(-floor(kernelSize/2),floor(kernelSize/2),kernelSize));
[X,Y] = meshgrid(lin,lin);
hg = exp(-(X.^2 + Y.^2)/(2*(sigma^2)));
kernel_t = hg.*(X.^2 + Y.^2-2*sigma^2)/(sigma^4*sum(hg(:)));
% make the filter sum to zero
kernel = kernel_t - sum(kernel_t(:))/kernelSize^2;
You should get identical results.
The main reason you were seeing the difference is because fspecial makes the filter sum to zero in the end.
In general, because an edge detection filter is a high pass filter, it is looking for quick changes. Because of that you need to have a 0 response at DC, which in this case means that your filter terms need to sum to zero.
  1 件のコメント
GiftOfWhen
GiftOfWhen 2018 年 3 月 28 日
This does not match the 'fspecial' ouput when 'kernelSize' is even. CAn you point me to some documentation on how the fspecial filter handles even kernelSize?

サインインしてコメントする。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by