# How to Calculate the Local Gradient of an Image in MATLAB

I know that the gradient function is supported by MATLAB, but the local gradient is not, so how do you calculate it?

Local gradient is another texture descriptor, which is defined as:

$$I_g=\sum_{z=-r}^{r} | \nabla I(x+\tau) |^2$$

• What do you mean by Local Gradient? Have you read it in an article you could link? It usually the classic gradient within a block. – Royi Apr 20 '14 at 16:07
• Assume that given image is divided into blocks. Local gradient is gradient of these block. You can see some definition at ac.els-cdn.com/S1874102913600038/… – John Apr 20 '14 at 16:38
• So, treat each block as it was an image and calculate the Gradient. Ot are you asking about the gradient of an image? – Royi Apr 20 '14 at 18:33
• I ask about gradient of an image. I think that first we divide image into bocks. For each block, we calculate gradient of them. So, local gradient of given image is gradient of each block combination. We can implement it by Gradient(K*I), where K is one kernel to divide image into block, * is convolution. How about my scheme? Thank – John Apr 21 '14 at 1:43
• I don't understand you. The gradient of an image or a block (Be more general a matrix) is well defined. For real life image the gradient is usually approximated by a filter, do you mean you want to show you that? – Royi Apr 21 '14 at 23:02

Ok,
First of all, pay attention it is a calculation per pixel using a sata from a blog. Basically summing the Gradient norm over a block / windows.

To calculate what you submitted above do the following:

1.Define the Finite Differences filters to approximate the gradient. Moreover build the "Win Summation" kernel which sums all elements within a window.

mLocalSumFilter = ones(filterWinSize, filterWinSize);


mInputImageGradX = imfilter(mInputImage, vGradXFilter, 'replicate', 'same', 'corr');


3.Calculate the norm of the gradient vector. Afterwards sum the norm of the gradient within the window.

mInputImageGradNorm = sqrt((mInputImageGradX .^ 2) + (mInputImageGradY .^ 2));


This is it.
Enjoy.

Presuming you have the Image processing toolbox the imgradient function should do what you want. It calculates the gradient magnitude (and direction) of each pixel using standard Sobel gradient.

From the discussion it sounds like you may want to calculate the gradient some other way. If so I recommend either nlfilter for sliding window methods (i.e pixel by pixel) or blockproc for block processing. For these functions you will have to work out a suitable equation for the gradient yourself but this isn't hard.

There is an error : correct your source by converting int8 to double

mLocalSumFilter = ones(filterWinSize, filterWinSize);