(29)Air Band OpenCV2.4.13

    xiaoxiao2021-03-25  124

    本文是对OpenCV2.4.13文档的部分翻译,作个人学习之用,并不完整。

    Canny边缘检测方法是最佳的检测方法,Canny算法旨在满足下面三个关键点:更低的错误率、良好的定位、最小反应时间。

    步骤:

    1.使用高斯滤波器过滤噪声,例如用大小为5的高斯核;

    2.找到图像的灰度梯度,类似于Sobel:

    在x和y两个维度上应用一对掩码矩阵:

    找到梯度的强度和方向(方向值在四个可能方向之一:0、45、90、135):

    3.应用非极大值抑制,去除不是边缘的像素,因此只有线条存在

    4.滞后:最终步骤,使用两个阈值(上界和下界):

    如果像素梯度比上界阈值高,该像素被接受为一个边缘;

    如果像素梯度比下界阈值低,就拒绝;

    如果像素梯度在两个阈值之间,只有当它和一个比上界阈值高的像素相连时才被接收。

    #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <stdlib.h> #include <stdio.h> using namespace cv; /// Global variables Mat src, src_gray; Mat dst, detected_edges; int edgeThresh = 1; int lowThreshold; int const max_lowThreshold = 100;//低阈值的最大值为100 int ratio = 3;//lower:upper=3:1 int kernel_size = 3;//核大小为3 const char* window_name = "Edge Map"; /** * @function CannyThreshold * @brief Trackbar callback - Canny thresholds input with a ratio 1:3 */ static void CannyThreshold(int, void*) { /// 用3x3的核来消噪 blur( src_gray, detected_edges, Size(3,3) ); /// Canny边缘检测(原灰度图、检测的输出(可能与输入相同)、低阈值(用户用滑动条给定的)、高阈值(这里设定为低阈值的3倍)、核大小(本质上使用了Sobel核大小3)) Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size ); /// 将Canny输出作为掩码矩阵,输出图像用黑丝填充 dst = Scalar::all(0); // 复制图像使得只有我们定义为边缘的才映射到黑色的背景上 src.copyTo( dst, detected_edges); imshow( window_name, dst ); } /** * @function main */ int main() { /// 加载图像 src = imread("lena.jpg"); if( !src.data ) { return -1; } /// 创建相同类型和大小的矩阵用作目标图像 dst.create( src.size(), src.type() ); /// 将图像转换为灰度图 cvtColor( src, src_gray, COLOR_BGR2GRAY ); /// 创建窗口 namedWindow( window_name, WINDOW_AUTOSIZE ); /// 创建滑动条来选择阈值 // 滑动条控制的变量是低阈值,最大为max_lowThreshold(100) // 每次滑动条事件触发CannyThreshold函数调用 createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold ); /// 显示图像 CannyThreshold(0, 0); /// 等待用户按键 waitKey(0); return 0; } 结果:

    转载请注明原文地址: https://ju.6miu.com/read-10015.html

    最新回复(0)