Is there a quick and easy way to calculate image gradient in OpenCV?

Using the latest OpenCV, is there an easy way to calculate the gradient image of a particular cv :: Mat?

+5
source share
3 answers

Assuming you mean a typical image gradient ; you can easily compute them using the Sobel operator , as mentioned by Chris. Take a look at the Sobel Derivatives tutorial here . You may also be interested in the Laplace and tutorial operator .

The following is a short snippet of calculating 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);
+14
source

: http://en.wikipedia.org/wiki/Image_gradient :

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

As the megatron said: Sobel and Laplace operators are powerful, but do not forget about the Scharr operator, which has greater accuracy in the 3 Γ— 3 kernel than Sobel.

0
source

All Articles