Plotting a Gradient Vector Field in OpenCV

后端 未结 2 1800
温柔的废话
温柔的废话 2021-02-09 23:19

I want to compute the gradient of a gray-scale image (smoothed_plane in the code) and plot it as a vector field in OpenCV, superposed to an existing image.

I tr

相关标签:
2条回答
  • 2021-02-10 00:20

    The following worked for me, after trying to use your code directly

    Scharr(smoothed_plane,grad_x,ddepth,1,0,scale);
    Scharr(smoothed_plane,grad_y,ddepth,0,1,scale);
    
    for (int i = 0 ; i < image_height ; i ++){
        for (int j = 0 ; j < image_width ; j ++){
            Scalar xval = grad_x.at<uchar>(i,j); // Notice <uchar> not float
            Scalar yval = grad_y.at<uchar>(i,j);
            gradient_field.at<Point2f>(i,j) = Point2f(xval.val[0],yval.val[0]);
        }
    }
    

    The < float > suggestion gave me high and unusable values.

    0 讨论(0)
  • 2021-02-10 00:23

    I solved my problem. The main mistake lied in the access method of the partial derivatives matrices, grad_x and grad_y. As described here, the method at.<>() returns a Scalar object, so to get access to the pixel intensity value one should use the .val[] field. This is how the code has to be changed:

    Scharr(smoothed_plane,grad_x,ddepth,1,0,scale);
    Scharr(smoothed_plane,grad_y,ddepth,0,1,scale);
    
    for (int i = 0 ; i < image_height ; i ++){
        for (int j = 0 ; j < image_width ; j ++){
            Scalar xval = grad_x.at<float>(i,j);
            Scalar yval = grad_y.at<float>(i,j);
            gradient_field.at<Point2f>(i,j) = Point2f(xval.val[0],yval.val[0]);
        }
    }
    

    and this is the expected result:

    0 讨论(0)
提交回复
热议问题