zebra
zebra

Reputation: 6531

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

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

Upvotes: 6

Views: 18948

Answers (3)

mevatron
mevatron

Reputation: 14011

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);

Upvotes: 15

Kuroro
Kuroro

Reputation: 49

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);
}

Upvotes: 4

Bartis Áron
Bartis Áron

Reputation: 668

As mevatron said: the Sobel and the Laplace operators are powerful, but don't forget about the Scharr operator, which has greater accuracy at a 3×3 kernel than the Sobel has.

Upvotes: 1

Related Questions