有一个 Mat 是灰度像素的正方形区域。如何创建一条直线,其方向被创建为垂直于大多数像素值改变方向(平均梯度,aerage 在整个 Mat 上,结果将只是一个方向(然后可以绘制为一条线))?
例如有
看起来像
如何在 OpenCV 中(在 Python 或 C++ 中)做这样的事情?
最佳答案
OpenCV 实现如下所示。它以与 Mark Setchell 的回答中解释的类似方式解决了问题,只是对图像进行归一化对结果方向没有任何影响。
Mat img = imread("img.png", IMREAD_GRAYSCALE);
// compute the image derivatives for both the x and y direction
Mat dx, dy;
Sobel(img, dx, CV_32F, 1, 0);
Sobel(img, dy, CV_32F, 0, 1);
Scalar average_dx = mean(dx);
Scalar average_dy = mean(dy);
double average_gradient = atan2(-average_dy[0], average_dx[0]);
cout << "average_gradient = " << average_gradient << endl;
并显示结果方向
Point center = Point(img.cols/2, img.rows/2);
Point direction = Point(cos(average_gradient) * 100, -sin(average_gradient) * 100);
Mat img_rgb = imread("img.png"); // read the image in colour
line(img_rgb, center, center + direction, Scalar(0,0,255));
imshow("image", img_rgb);
waitKey();
关于c++ - 如何检测强度梯度方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796108/