Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a quick and easy way in OpenCV to compute the gradient of an image?

Tags:

c++

opencv

Using the newest OpenCV, is there an easy way to compute the gradient image of a specific cv::Mat?

like image 775
zebra Avatar asked Dec 14 '11 16:12

zebra


People also ask

How do you find the gradient of an image?

The most common way to approximate the image gradient is to convolve an image with a kernel, such as the Sobel operator or Prewitt operator. Image gradients are often utilized in maps and other visual representations of data in order to convey additional information.

How do you find the gradient of an image in Python?

We can find the gradient of an image by the help of Sobel and Laplacian derivatives of the image. Sobel is used for either X or Y direction or even in combined form while Laplacian help in both directions. Don't worry about the mathematical calculation of the image.

What is image gradient in Opencv?

Image gradient is used to extract information from an image. It is one of the fundamental building blocks in image processing and edge detection. The main application of image gradient is in. Many algorithms, such as Canny Edge Detection, use image gradients for detecting edges.

What is image gradient operator?

In digital images, a gradient operator is similar to an averaging operator (for noise removal), which is a weighted convolution operator utilizing the neighboring pixels for the operation. However, unlike the averaging operator, the weightings of a gradient operator are not exclusively positive integers.


2 Answers

Assuming you are referring to the typical image gradient; you can compute these quite easily with the Sobel operator as mentioned by Chris. Have a look at the Sobel Derivatives tutorial here. You may also be interested in the Laplace operator, and its tutorial.

Here is a short snippet of computing the X and Y gradients using Sobel:

cv::Mat src = ...; // Fill the input somehow.

cv::Mat Dx;
cv::Sobel(src, Dx, CV_64F, 1, 0, 3);

cv::Mat Dy;
cv::Sobel(src, Dy, CV_64F, 0, 1, 3);
like image 137
mevatron Avatar answered Oct 18 '22 18:10

mevatron


From: http://en.wikipedia.org/wiki/Image_gradient, you can do:

IplImage * diffsizekernel(IplImage *img, int f, int c) {
    float dkernel[] =  {-1, 0, 1};

    CvMat kernel = cvMat(f, c, CV_32FC1, dkernel);

    IplImage *imgDiff = cvCreateImage(cvSize(img->width, img->height), IPL_DEPTH_16S, 1);

    cvFilter2D( img, imgDiff, &kernel, cvPoint(-1,-1) );

    return imgDiff;
}

IplImage * diffx(IplImage *img) {
    return diffsizekernel(img, 3, 1);
}

IplImage * diffy(IplImage *img) {
    return diffsizekernel(img, 1, 3);
}
like image 27
Kuroro Avatar answered Oct 18 '22 19:10

Kuroro