Ask Your Question

Revision history [back]

In opencv you can use sobel functions, or write your own functions: For horizontal gradient compare picell wit coordinates (x-1,y) and (x+1,y) i.e. abs(image.at<uchar>(y,x-1)-image.at<uchar>(y,x+1)); Analogously for the Y gradient.

p.p. Here, that are my functions for calculating gradient on gray scale image. They are working with a pointer to the data stored in the matrix. The output matrices are 64bit, but 16 will do the job too, just change the cast and the constructor.

void gradx (Mat input, Mat &output)
{
    output=Mat::zeros(input.size(),CV_64FC1);
    for(int y=0;y<input.rows;y++)
    {
        for(int x=1;x<input.cols-1;x++)
        {
            *((double*)output.data+y*output.cols+x)=(double)(*(input.data+y*input.cols+x+1)-*(input.data+y*input.cols+x-1))/2;
        }
    }
}

void grady (Mat input, Mat &output)
{
    output=Mat::zeros(input.size(),CV_64FC1);
    for(int y=1;y<input.rows-1;y++)
    {
        for(int x=0;x<input.cols;x++)
        {
            *((double*)output.data+y*output.cols+x)=(double)(*(input.data+(y+1)*input.cols+x)-*(input.data+(y-1)*input.cols+x))/2;
        }
    }
}

In opencv you can use sobel functions, or write your own functions: For horizontal gradient compare picell wit pixelwit coordinates (x-1,y) and (x+1,y) i.e. abs(image.at<uchar>(y,x-1)-image.at<uchar>(y,x+1)); gard(x,y)=abs(image(x-1,y)-image.(x+1,y)); Analogously for the Y gradient.

p.p. Here, that are my functions for calculating gradient on gray scale image. They are working with a pointer to the data stored in the matrix. The output matrices are 64bit, but 16 will do the job too, just change the cast and the constructor.

void gradx (Mat input, Mat &output)
{
    output=Mat::zeros(input.size(),CV_64FC1);
    for(int y=0;y<input.rows;y++)
    {
        for(int x=1;x<input.cols-1;x++)
        {
            *((double*)output.data+y*output.cols+x)=(double)(*(input.data+y*input.cols+x+1)-*(input.data+y*input.cols+x-1))/2;
        }
    }
}

void grady (Mat input, Mat &output)
{
    output=Mat::zeros(input.size(),CV_64FC1);
    for(int y=1;y<input.rows-1;y++)
    {
        for(int x=0;x<input.cols;x++)
        {
            *((double*)output.data+y*output.cols+x)=(double)(*(input.data+(y+1)*input.cols+x)-*(input.data+(y-1)*input.cols+x))/2;
        }
    }
}