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
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.
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: