Image Gradient for Edge Detection in PyTorch

ANUMOL C S
2 min readJun 4, 2020

To extract the feature representations more precisely we can compute the image gradient to the edge constructions of a given image. The most recognized utilization of image gradient is edge detection that based on convolving the image with a filter. In the given direction of filter, the gradient image defines its intensity from each pixel of the original image and the pixels with large gradient values become possible edge pixels.

At each image point, the gradient of image intensity function results a 2D vector which have the components of derivatives in the vertical as well as in the horizontal directions. To approximate the derivatives, it convolve the image with a kernel and the most common convolving filter here we using is sobel operator, which is a small, separable and integer valued filter that outputs a gradient vector or a norm.

Let S is the source image and there are two 3 x 3 sobel kernels Sx and Sy to compute the approximations of gradient in the direction of vertical and horizontal directions respectively.

sobel kernels Sx and Sy

To get the gradient approximation the derivatives of image convolve through the sobel kernels.

Gx is the gradient approximation for vertical changes and Gy is the horizontal gradient approximation. Both are computed as

Gx = Sx * ΔS and Gy = Sy * ∆S,

Where * represents the 2D convolution operation

To get the vertical and horizontal edge representation, combines the resulting gradient approximations, by taking the root of squared sum of these approximations, Gx and Gy.

The image gradient can be computed on tensors and the edges are constructed on PyTorch platform and you can refer the code as follows.

My Name is Anumol, an engineering post graduate. Check out my LinkedIn profile.

If you enjoyed this article, please recommend it and share it! Thanks for your time.

--

--