c++ - 如何检测强度梯度方向

标签 c++ opencv

有一个 Mat 是灰度像素的正方形区域。如何创建一条直线,其方向被创建为垂直于大多数像素值改变方向(平均梯度,aerage 在整个 Mat 上,结果将只是一个方向(然后可以绘制为一条线))?

例如有

enter image description here

看起来像

enter image description here

如何在 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();

image direction

关于c++ - 如何检测强度梯度方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796108/

相关文章:

c++ - 为什么我的迭代器指向 null,但只是有时?

c++ - 如何通过编译错误找到 C++ 复制构造函数的使用位置?

c++ - 如何打破这种循环类型定义?

opencv - 解码 MB 时出现 ffmpeg RTSP 错误

c++ - 构造函数谁 spect void*

c++ - 从哪里开始计算机视觉

c++ - glsl 顶点着色器统一变量未激活

c++ - 堆栈/堆分配数组的销毁顺序

matlab - 快速图像扫描

python - Opencv cv2.BFMatcher 没有看到相似之处