opencv - 从canny计算非方向性边缘

use*_*743 3 opencv edge-detection

任何人都可以帮助我如何使用opencv cannyedge检测计算非定向边缘的数量?我有一个来自opencv的cannyEdge图像,我希望有一个基于边缘方向的直方图,我可以计算它的方向和非方向边数.

mev*_*ron 38

我认为你将边缘检测与梯度检测混淆.Canny提供了一个基于梯度幅度的边缘图(通常使用Sobel算子,但它可以使用其他算子),因为Canny只返回它无法为您提供方向信息的阈值梯度幅度信息.

编辑:我应该澄清,Canny算法确实使用梯度方向进行非最大抑制步骤.但是,OpenCV实现会Canny隐藏此方向信息,并仅返回边缘幅度图.

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

  1. 在X方向计算Sobel(Sx).
  2. 在Y方向计算索贝尔(Sy).
  3. 计算梯度幅度sqrt(Sx*Sx + Sy*Sy).
  4. 使用计算渐变方向arctan(Sy / Sx).

该算法可以使用以下OpenCV函数实现:Sobel,幅度相位.

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

使用圆形图像:
在此输入图像描述

这会产生以下幅度和方向图像:
大小 取向

最后,这是渐变方向图:
地图

更新:阿比德实际上​​在评论中提出了一个很好的问题:"这里的方向是什么意思?",我认为需要进一步讨论.我假设该phase功能不会从正常y轴向下的正常图像处理角度切换坐标框架,正x轴向右.鉴于此假设导致后续图像显示圆周围的渐变方向向量:

在此输入图像描述

这可能很难习惯,因为轴是从我们通常使用的数学类中翻转出来的......因此,渐变方向是法线向量在渐变方向上向渐变表面所做的角度.

希望你发现有帮助!

  • +1 - 很好..有一个疑问.这里的方向是什么意思? (2认同)