Ask Your Question

how do I draw a gradient image with internal data structure(step) of opencv

asked 2013-09-02 04:26:01 -0500

benzwt gravatar image

I was trying to draw a gradient image with opencv's step But the result was wrong. Could someone give me some hints ? thanks!

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main( int argc, char** argv )
    Mat img;
    Scalar a = 0;
    img = Mat(32, 32, CV_8UC1, a);
    unsigned char *p;
    for(int i=0; i<img.rows; i++)
        p = + i*img.step[0];
        for(int j=0; j<img.cols; j++, p++)
                *p = j;
    imwrite("gradient.png", img);
    return 0;
edit retag flag offensive close merge delete


thanks for the reply. But there is some mis-understanding, the gradient image I mentioned is some kind of gimp style gradient image. Please kindly check the code above. thanks!

benzwt gravatar imagebenzwt ( 2013-09-02 20:07:02 -0500 )edit

What do you mean by wrong result? I've run your code and have image with horizontal gradient. BTW, instead of " + i*img.step[0]" you can use "img.row(i) .data".

Daniil Osokin gravatar imageDaniil Osokin ( 2013-09-07 13:55:29 -0500 )edit

2 answers

Sort by » oldest newest most voted

answered 2013-09-02 04:28:39 -0500

edit flag offensive delete link more

answered 2013-09-02 06:06:49 -0500

To illustrate @Spas Hristov his asnwer, here is some sample code on how to calculate gradient images.

void calculateGradientImage(Mat inputImage, Mat outputImage, Size kernelSize, int sigma){
   Mat grayImage, smoothedImage;
   // Some basic smoothing on the image to remove pixelation
   GaussianBlur( inputImage, smoothedImage, kernelSize, sigma);
   // Convert RBG towards grayscale image
   cvtColor( smoothedImage, grayImage, CV_RGB2GRAY );

   // Calculate gradient image
   Mat grad_X = Mat(inputImage.rows, inputImage.cols, CV_32F);
   Mat grad_Y = Mat(inputImage.rows, inputImage.cols, CV_32F);

   // Gradient for the X direction
   Sobel( grayImage, grad_X, CV_32F, 1, 0, 3, 1, 0, BORDER_DEFAULT );
   // Gradient for the Y direction
   Sobel( grayImage, grad_Y, CV_32F, 0, 1, 3, 1, 0, BORDER_DEFAULT );

   // Combine both gradient functions together
   // total = sqrt(dx² + dy²) <-- more correct than just adding both values weighted together
   Mat gradient = Mat(grayImage.rows, grayImage.cols, CV_64F);
   sum = grad_X.mul(grad_X)+ grad_Y.mul(grad_Y;
   sqrt(sum, gradient);

   // Push back the gradient image
   imageOutput = gradient;
edit flag offensive delete link more
Login/Signup to Answer

Question Tools


Asked: 2013-09-02 04:26:01 -0500

Seen: 754 times

Last updated: Sep 02 '13