目录
一.介绍
1.函数原型
2. 原理与步骤:
1). 消除噪声: gaussian
2). 计算梯度幅值和方向: sobel算子
3). 进行非极大值抑制
4). 滞后阈值,筛选边缘。
二. 代码测试
main.cpp
testFuntion.h
testFuntion.cpp
三. 运行结果
一.介绍 1.函数原型对应opencv中:cv:Canny imgproc.hpp
@param image 8-bit input image.
@param edges output edge map; single channels 8-bit image, which has the same size as image .
@param threshold1 first threshold for the hysteresis procedure.
@param threshold2 second threshold for the hysteresis procedure.
@param apertureSize aperture size for the Sobel operator.
@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm
\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude (L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough (L2gradient=false )
CV_EXPORTS_W void Canny( InputArray image, OutputArray edges,
double threshold1, double threshold2,
int apertureSize = 3, bool L2gradient = false );
2. 原理与步骤: 1). 消除噪声: gaussian
一般情况下,使用高斯平滑滤波器,卷积降噪。 如 size = 5 的高斯核
Ⅰ.运用一对卷积阵列 (分别作用于 x 和 y 方向): 按照Sobel算子进行计算梯度
Ⅱ.使用下列公式计算梯度幅值和方向: 二阶偏导平和开根号 角度是反正切
即求梯度方向的局部极大值,来排除非边缘像素, 仅仅保留了一些细线条(候选边缘)。
非极大值抑制原理: 在一个窗口内,如果有多个角点,则用值最大的那个角点,其他的角点都删除,比如可以通过图像的膨胀运算来达到检测极大值的目的,因为默认参数的膨胀运算就是用窗口内的最大值替代当前的灰度值。
4). 滞后阈值,筛选边缘。使用了两个阈值(高阈值和低阈值):
Ⅰ. 如果某一像素的梯度小于低阈值, 该像素被排除。 //小阈值用来控制边缘连接
Ⅱ. 如果某一像素的梯度超过高阈值, 该像素被保留为边缘像素。 //大的阈值用来控制强边缘的初始分割
Ⅲ. 如果某一像素的梯度在两个阈值之间,该像素仅仅在连接到一个高于高阈值的像素时,被保留。
推荐的高低阈值比: 在2:1到3:1之间。或者使用直方图中像素总数的70% 30%位置的值。
二. 代码测试 main.cpp
#include ".\mycode\include\testFuntion.h"
int main()
{
test_Canny();
return 0;
}
testFuntion.h
#include
#define PIC_LOGO "D://test_OpenCV//testpic//jologo.jpg"
#define PIC_MOUNTAIN_CITY "D:\\test_OpenCV\\testpic\\mountain_city.jpg"
#define SCALE 100 //缩放比例因子
using namespace cv;
测试Canny算子,检测图像边缘
void test_Canny();
testFuntion.cpp
void test_Canny()
{
Mat srcImg = imread(PIC_LOGO);
Mat grayImg, dstImg, edgeImg;
namedWindow("Pic src");
imshow("Pic src", srcImg);
int unitSize = (srcImg.size().height > srcImg.size().width ? srcImg.size().width : srcImg.size().height)*2/ SCALE;
cvtColor(srcImg, grayImg, COLOR_BGR2GRAY);
blur(grayImg, grayImg, Size(unitSize, unitSize));
Canny(grayImg, edgeImg, 3, 9);
namedWindow("Pic after canny");
imshow("Pic after canny", edgeImg);
waitKey();
}
三. 运行结果