gpt4 book ai didi

opencv - 从 canny 计算非定向边

转载 作者:太空宇宙 更新时间:2023-11-03 21:01:17 24 4
gpt4 key购买 nike

任何人都可以帮助我如何使用 opencv cannyedge 检测来计算非定向边缘的数量吗?我有一个来自 opencv 的 cannyEdge 图像,我想要一个基于边缘方向的直方图,这样我就可以计算出定向和非定向边缘的数量。

最佳答案

我认为您混淆了边缘检测和梯度检测。 Canny 提供基于梯度幅度的边缘图(通常使用 Sobel 算子,但也可以使用其他算子),因为 Canny 仅返回阈值梯度幅度信息,无法为您提供方向信息。

编辑: 我应该澄清一下,Canny 算法确实在非最大抑制步骤中使用了梯度方向。但是,Canny 的 OpenCV 实现向您隐藏了此方向信息,并且仅返回边缘幅度图。

获取梯度大小和方向的基本算法如下:

  1. 计算 X 方向的 Sobel (Sx)。
  2. 计算 Y 方向的 Sobel (Sy)。
  3. 计算梯度大小sqrt(Sx*Sx + Sy*Sy)
  4. 使用 arctan(Sy/Sx) 计算梯度方向。

可以使用以下 OpenCV 函数实现此算法:Sobel , magnitude , 和 phase .

下面是一个计算梯度幅度和相位的示例,并显示了梯度方向的粗略颜色映射:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <iostream>
#include <vector>

using namespace cv;
using namespace std;

Mat mat2gray(const cv::Mat& src)
{
Mat dst;
normalize(src, dst, 0.0, 255.0, cv::NORM_MINMAX, CV_8U);

return dst;
}

Mat orientationMap(const cv::Mat& mag, const cv::Mat& ori, double thresh = 1.0)
{
Mat oriMap = Mat::zeros(ori.size(), CV_8UC3);
Vec3b red(0, 0, 255);
Vec3b cyan(255, 255, 0);
Vec3b green(0, 255, 0);
Vec3b yellow(0, 255, 255);
for(int i = 0; i < mag.rows*mag.cols; i++)
{
float* magPixel = reinterpret_cast<float*>(mag.data + i*sizeof(float));
if(*magPixel > thresh)
{
float* oriPixel = reinterpret_cast<float*>(ori.data + i*sizeof(float));
Vec3b* mapPixel = reinterpret_cast<Vec3b*>(oriMap.data + i*3*sizeof(char));
if(*oriPixel < 90.0)
*mapPixel = red;
else if(*oriPixel >= 90.0 && *oriPixel < 180.0)
*mapPixel = cyan;
else if(*oriPixel >= 180.0 && *oriPixel < 270.0)
*mapPixel = green;
else if(*oriPixel >= 270.0 && *oriPixel < 360.0)
*mapPixel = yellow;
}
}

return oriMap;
}

int main(int argc, char* argv[])
{
Mat image = Mat::zeros(Size(320, 240), CV_8UC1);
circle(image, Point(160, 120), 80, Scalar(255, 255, 255), -1, CV_AA);

imshow("original", image);

Mat Sx;
Sobel(image, Sx, CV_32F, 1, 0, 3);

Mat Sy;
Sobel(image, Sy, CV_32F, 0, 1, 3);

Mat mag, ori;
magnitude(Sx, Sy, mag);
phase(Sx, Sy, ori, true);

Mat oriMap = orientationMap(mag, ori, 1.0);

imshow("magnitude", mat2gray(mag));
imshow("orientation", mat2gray(ori));
imshow("orientation map", oriMap);
waitKey();

return 0;
}

使用圆形图片:
enter image description here

这会产生以下幅度和方向图像:
magnitude orientation

最后,这里是渐变方向图:
map

更新:阿比德实际上​​在评论中提出了一个很好的问题“这里的方向是什么意思?”,我认为需要进一步讨论。我假设 phase 函数不会从正 y 轴向下和正 x 轴正确的正常图像处理角度切换坐标系。鉴于此假设导致以下图像显示围绕圆的梯度方向向量:

enter image description here

这可能很难习惯,因为坐标轴与我们通常在数学课上使用的坐标轴翻转了...因此,梯度方向是法向量与梯度表面在增加方向上形成的角度改变。

希望对您有所帮助!

关于opencv - 从 canny 计算非定向边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11145852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com