Search code examples
matlabimage-processingcomputer-visiongaussianderivative

Calculating the first derivative of Gaussian (dx, dy) without using gradient() in Matlab


I initiated my gaussian as fspecial('gaussian', 4, 1), and I know gradient() is a very convenient way to get the first derivative. Is there anyways that I can calculate the first derivatives without using gradient()? I am using it for creating the Harris Corner detector, as illustrated as the first step in the textbook:

  • Compute the horizontal and vertical derivatives of the image Ix and Iy by convolving the original image with derivatives of Gaussians

Solution

  • If it is your intent to implement the Harris Corner Detector, then you should not use gradient at all. What is traditionally done is you use a derivative kernel and you filter the image with this kernel. You can use various kernels, but what I've seen done in practice is to use a centered difference such that the horizontal kernel dx is [-1 0 1] and the vertical kernel dy is the transpose of this or [-1;0;1]. You thus filter the image with these kernels to get the responses Ix and Iy where these are the horizontal and vertical gradients of your image, then you perform Gaussian smoothing on the squared version of these images: Ix.^2, Iy.^2, as well as their product Ix.*Iy. You then form the correlation matrix, find the determinants and traces and determine the corner response. Any values surpassing this threshold are potential corners. Performing Gaussian smoothing on the derivative images effectively filters the original image with a derivative of Gaussians as originally stated in your question.

    Therefore assuming your image is stored in im, you simply do:

    im = double(im); % Cast to double precision to ensure accuracy
    dx = [-1 0 1];
    dy = dx.';
    Ix = conv2(im, dx, 'same');
    Iy = conv2(im, dy, 'same');
    

    You would use Ix and Iy to finally compute the Harris Corner Response. If you have the image processing toolbox, I would recommend you use imfilter instead. It's faster and it uses the Intel Integrated Performance Primitives (IIPP). If you'd like more information on how to compute it properly, check out my previous post here: Trying to find/understand correct implementation of Harris Corners