I want to calculate the gradient of a gray image (smoothed_plane in code) and build it as a vector field in OpenCV superimposed on an existing image.
I tried using a couple of Sobel statements (I also tried Scharr) to compute two derivatives with respect to x and y, as described in the OpenCV documentation, but when I try to build, the vector field seems completely wrong. I would like to understand what my mistake is.
I put the code here to be more clear. Thanks in advance for your help.
Mat abs_grad_x, abs_grad_y, grad;
Mat g_img;
int ddepth = CV_16S;
int scale = 1;
int delta = 0;
cvtColor(img,g_img,CV_GRAY2BGR);
smoothed_plane = Mat::zeros(image_height,image_width,CV_8UC1);
gradient_field = Mat::zeros(image_height,image_width,CV_32FC2);
GaussianBlur(dominant_plane,smoothed_plane,Size(51,51),image_height*image_width*0.5);
erode(smoothed_plane, smoothed_plane, getStructuringElement(MORPH_ELLIPSE, Size(40+1,40+1)));
dilate(smoothed_plane, smoothed_plane, getStructuringElement(MORPH_ELLIPSE, Size(40, 40)));
dilate(smoothed_plane, smoothed_plane, getStructuringElement(MORPH_ELLIPSE, Size(40, 40)));
erode(smoothed_plane, smoothed_plane, getStructuringElement(MORPH_ELLIPSE, Size(40, 40)));
imshow("Eroded plane",smoothed_plane);
Scharr( smoothed_plane, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT );
convertScaleAbs( grad_x, abs_grad_x );
Scharr( smoothed_plane, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
convertScaleAbs( grad_y, abs_grad_y );
for (int i = 0 ; i < image_height ; i ++){
for (int j = 0 ; j < image_width ; j ++){
gradient_field.at<Point2f>(Point2f(j,i)) = Point2f(abs_grad_x.at<float>(Point2f(j,i)),abs_grad_y.at<float>(Point2f(j,i)));
}
}
for (int i = 0 ; i < image_height ; i += flowResolution){
for (int j = 0 ; j < image_width ; j+= flowResolution){
Point2f p(j,i);
Point2f p2(gradient_field.at<Point2f>(p)+p);
arrowedLine(g_img,p,p2,Scalar(0,0,255),1.5,8,0,0.1);
}
}
imshow("Gradient Vector Field", g_img);
EDIT:
This is a couple frames of my I / O results, if required

I tried to print some values, and at some points I got very high or very low values. Thanks again