【OpenCV】Canny 边缘检测

【OpenCV】Canny 边缘检测Canny边缘检测算法1986年,JOHNCANNY提出一个很好的边缘检测算法,被称为Canny编边缘检测器[1]。Canny边缘检测根据对信噪比与定位乘积进行测度,得到最优化逼近算子,也就是Canny算子。类似与LoG边缘检测方法,也属于先平滑后求导数的方法。使用Canny边缘检测器,图象边缘检测必须满足两个条件:能有效地抑制噪声;必须尽量精确确定边缘的位置。算

大家好,又见面了,我是你们的朋友全栈君。

Canny 边缘检测算法

1986年,JOHN CANNY 提出一个很好的边缘检测算法,被称为Canny编边缘检测器[1]。

Canny边缘检测根据对信噪比与定位乘积进行测度,得到最优化逼近算子,也就是Canny算子。类似与 LoG 边缘检测方法,也属于先平滑后求导数的方法。

使用Canny边缘检测器,图象边缘检测必须满足两个条件:

  • 能有效地抑制噪声;
  • 必须尽量精确确定边缘的位置。

算法大致流程:

1、求图像与高斯平滑滤波器卷积:

【OpenCV】Canny 边缘检测

2、使用一阶有限差分计算偏导数的两个阵列P与Q:

【OpenCV】Canny 边缘检测

3、幅值和方位角:

【OpenCV】Canny 边缘检测

4、非极大值抑制(NMS ) :细化幅值图像中的屋脊带,即只保留幅值局部变化最大的点。

将梯度角的变化范围减小到圆周的四个扇区之一,方向角和幅值分别为:

【OpenCV】Canny 边缘检测

非极大值抑制通过抑制梯度线上所有非屋脊峰值的幅值来细化M[i,j],中的梯度幅值屋脊.这一算法首先将梯度角θ[i,j]的变化范围减小到圆周的四个扇区之一,如下图所示:

【OpenCV】Canny 边缘检测

 

5、取阈值

  • 将低于阈值的所有值赋零,得到图像的边缘阵列 

  • 阈值τ取得太低->假边缘
  • 阈值τ取得太高->部分轮廊丢失
  • 选用两个阈值: 更有效的阈值方案.
     

相关代码

 Canny算法实现:

  1. 用高斯滤波器平滑图像(在调用Canny之前自己用blur平滑)
  2. 用一阶偏导的有限差分来计算梯度的幅值和方向.
  3.  对梯度幅值应用非极大值抑制 .
  4. 用双阈值算法检测和连接边缘.
void cv::Canny( InputArray _src, OutputArray _dst,
                double low_thresh, double high_thresh,
                int aperture_size, bool L2gradient )
{
    Mat src = _src.getMat();
    CV_Assert( src.depth() == CV_8U );
    
    _dst.create(src.size(), CV_8U);
    Mat dst = _dst.getMat();

    if (!L2gradient && (aperture_size & CV_CANNY_L2_GRADIENT) == CV_CANNY_L2_GRADIENT)
    {
        //backward compatibility
        aperture_size &= ~CV_CANNY_L2_GRADIENT;
        L2gradient = true;
    }

    if ((aperture_size & 1) == 0 || (aperture_size != -1 && (aperture_size < 3 || aperture_size > 7)))
        CV_Error(CV_StsBadFlag, "");

#ifdef HAVE_TEGRA_OPTIMIZATION
    if (tegra::canny(src, dst, low_thresh, high_thresh, aperture_size, L2gradient))
        return;
#endif

    const int cn = src.channels();
    cv::Mat dx(src.rows, src.cols, CV_16SC(cn));
    cv::Mat dy(src.rows, src.cols, CV_16SC(cn));

    cv::Sobel(src, dx, CV_16S, 1, 0, aperture_size, 1, 0, cv::BORDER_REPLICATE);
    cv::Sobel(src, dy, CV_16S, 0, 1, aperture_size, 1, 0, cv::BORDER_REPLICATE);

    if (low_thresh > high_thresh)
        std::swap(low_thresh, high_thresh);

    if (L2gradient)
    {
        low_thresh = std::min(32767.0, low_thresh);
        high_thresh = std::min(32767.0, high_thresh);
		
        if (low_thresh > 0) low_thresh *= low_thresh;
        if (high_thresh > 0) high_thresh *= high_thresh;
    }
    int low = cvFloor(low_thresh);
    int high = cvFloor(high_thresh);

    ptrdiff_t mapstep = src.cols + 2;
    cv::AutoBuffer<uchar> buffer((src.cols+2)*(src.rows+2) + cn * mapstep * 3 * sizeof(int));
    
    int* mag_buf[3];
    mag_buf[0] = (int*)(uchar*)buffer;
    mag_buf[1] = mag_buf[0] + mapstep*cn;
    mag_buf[2] = mag_buf[1] + mapstep*cn;
    memset(mag_buf[0], 0, /* cn* */mapstep*sizeof(int));

    uchar* map = (uchar*)(mag_buf[2] + mapstep*cn);
    memset(map, 1, mapstep);
    memset(map + mapstep*(src.rows + 1), 1, mapstep);

    int maxsize = std::max(1 << 10, src.cols * src.rows / 10);
    std::vector<uchar*> stack(maxsize);
    uchar **stack_top = &stack[0];
    uchar **stack_bottom = &stack[0];

    /* sector numbers
       (Top-Left Origin)

        1   2   3
         *  *  *
          * * *
        0*******0
          * * *
         *  *  *
        3   2   1
    */

    #define CANNY_PUSH(d)    *(d) = uchar(2), *stack_top++ = (d)
    #define CANNY_POP(d)     (d) = *--stack_top

    // calculate magnitude and angle of gradient, perform non-maxima supression.
    // fill the map with one of the following values:
    //   0 - the pixel might belong to an edge
    //   1 - the pixel can not belong to an edge
    //   2 - the pixel does belong to an edge
    for (int i = 0; i <= src.rows; i++)
    {
        int* _norm = mag_buf[(i > 0) + 1] + 1;
        if (i < src.rows)
        {
            short* _dx = dx.ptr<short>(i);
            short* _dy = dy.ptr<short>(i);

            if (!L2gradient)
            {
                for (int j = 0; j < src.cols*cn; j++)
                    _norm[j] = std::abs(int(_dx[j])) + std::abs(int(_dy[j]));
            }
            else
            {
                for (int j = 0; j < src.cols*cn; j++)
                    _norm[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j];
            }
			
            if (cn > 1)
            {
                for(int j = 0, jn = 0; j < src.cols; ++j, jn += cn)
                {
                    int maxIdx = jn;
                    for(int k = 1; k < cn; ++k)
                        if(_norm[jn + k] > _norm[maxIdx]) maxIdx = jn + k;
                    _norm[j] = _norm[maxIdx];
                    _dx[j] = _dx[maxIdx];
                    _dy[j] = _dy[maxIdx];
                }
            }
            _norm[-1] = _norm[src.cols] = 0;
        }
        else
            memset(_norm-1, 0, /* cn* */mapstep*sizeof(int));
		
        // at the very beginning we do not have a complete ring
        // buffer of 3 magnitude rows for non-maxima suppression
        if (i == 0)
            continue;

        uchar* _map = map + mapstep*i + 1;
        _map[-1] = _map[src.cols] = 1;

        int* _mag = mag_buf[1] + 1; // take the central row
        ptrdiff_t magstep1 = mag_buf[2] - mag_buf[1];
        ptrdiff_t magstep2 = mag_buf[0] - mag_buf[1];

        const short* _x = dx.ptr<short>(i-1);
        const short* _y = dy.ptr<short>(i-1);

        if ((stack_top - stack_bottom) + src.cols > maxsize)
        {
            int sz = (int)(stack_top - stack_bottom);
            maxsize = maxsize * 3/2;
            stack.resize(maxsize);
            stack_bottom = &stack[0];
            stack_top = stack_bottom + sz;
        }

        int prev_flag = 0;
        for (int j = 0; j < src.cols; j++)
        {
            #define CANNY_SHIFT 15
            const int TG22 = (int)(0.4142135623730950488016887242097*(1<<CANNY_SHIFT) + 0.5);

            int m = _mag[j];

            if (m > low)
            {
                int xs = _x[j];
                int ys = _y[j];
                int x = std::abs(xs);
                int y = std::abs(ys) << CANNY_SHIFT;

                int tg22x = x * TG22;

                if (y < tg22x)
                {
                    if (m > _mag[j-1] && m >= _mag[j+1]) goto __ocv_canny_push;
                }
                else
                {
                    int tg67x = tg22x + (x << (CANNY_SHIFT+1));
                    if (y > tg67x)
                    {
                        if (m > _mag[j+magstep2] && m >= _mag[j+magstep1]) goto __ocv_canny_push;
                    }
                    else
                    {
                        int s = (xs ^ ys) < 0 ? -1 : 1;
                        if (m > _mag[j+magstep2-s] && m > _mag[j+magstep1+s]) goto __ocv_canny_push;
                    }
                }
            }
            prev_flag = 0;
            _map[j] = uchar(1);
            continue;
__ocv_canny_push:
            if (!prev_flag && m > high && _map[j-mapstep] != 2)
            {
                CANNY_PUSH(_map + j);
                prev_flag = 1;
            }
            else
                _map[j] = 0;
        }

        // scroll the ring buffer
        _mag = mag_buf[0];
        mag_buf[0] = mag_buf[1];
        mag_buf[1] = mag_buf[2];
        mag_buf[2] = _mag;
    }

    // now track the edges (hysteresis thresholding)
    while (stack_top > stack_bottom)
    {
        uchar* m;
        if ((stack_top - stack_bottom) + 8 > maxsize)
        {
            int sz = (int)(stack_top - stack_bottom);
            maxsize = maxsize * 3/2;
            stack.resize(maxsize);
            stack_bottom = &stack[0];
            stack_top = stack_bottom + sz;
        }

        CANNY_POP(m);

        if (!m[-1])         CANNY_PUSH(m - 1);
        if (!m[1])          CANNY_PUSH(m + 1);
        if (!m[-mapstep-1]) CANNY_PUSH(m - mapstep - 1);
        if (!m[-mapstep])   CANNY_PUSH(m - mapstep);
        if (!m[-mapstep+1]) CANNY_PUSH(m - mapstep + 1);
        if (!m[mapstep-1])  CANNY_PUSH(m + mapstep - 1);
        if (!m[mapstep])    CANNY_PUSH(m + mapstep);
        if (!m[mapstep+1])  CANNY_PUSH(m + mapstep + 1);
    }

    // the final pass, form the final image
    const uchar* pmap = map + mapstep + 1;
    uchar* pdst = dst.ptr();
    for (int i = 0; i < src.rows; i++, pmap += mapstep, pdst += dst.step)
    {
        for (int j = 0; j < src.cols; j++)
            pdst[j] = (uchar)-(pmap[j] >> 1);
    }
}

Canny() 调用接口(C++):

void Canny(InputArray image, OutputArray edges, double threshold1, double threshold2, 
                   int apertureSize=3, bool L2gradient=false )

实践示例

 

Mat src, src_gray;
Mat dst, detected_edges;
int edgeThresh = 1;
int lowThreshold;
int const max_lowThreshold = 100;
int ratio = 3;
int kernel_size = 3;
char* window_name = "Edge Map";

void CannyThreshold(int, void*)
{
    /// Reduce noise with a kernel 3x3
    blur( src_gray, detected_edges, Size(3,3) );
    /// Canny detector
    Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );
    dst = Scalar::all(0);
    src.copyTo( dst, detected_edges);
    imshow( window_name, dst );
}

int main( )
{
  src = imread( "images\\happycat.png" );
  if( !src.data )
    { return -1; }
  dst.create( src.size(), src.type() );
  cvtColor( src, src_gray, CV_BGR2GRAY );
  namedWindow( window_name, CV_WINDOW_AUTOSIZE );
  createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );
  CannyThreshold(0, 0);
  waitKey(0);
  return 0;
}

 原图:

【OpenCV】Canny 边缘检测

边缘检测效果图:

(从左到右lowThread分别为0、50、100)

【OpenCV】Canny 边缘检测 【OpenCV】Canny 边缘检测 【OpenCV】Canny 边缘检测

 

 参考文献:

[1] Canny. A Computational Approach to Edge Detection, IEEE Trans. on Pattern Analysis and Machine Intelligence, 8(6), pp. 679-698 (1986).

 

转载请注明出处:http://blog.csdn.net/xiaowei_cqu/article/details/7839140

资源下载:http://download.csdn.net/detail/xiaowei_cqu/4483966

 

 

 

[1] Canny. A Computational Approach to Edge Detection, IEEE Trans. on Pattern Analysis and Machine Intelligence, 8(6), pp. 679-698 (1986).

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/139401.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Java链表删除节点操作

    Java链表删除节点操作1、创建节点类Node/***程序目的:建立一组学生成绩的单向链表程序,包含学号、姓名、和成绩3种数据。只要输入要删除学生的成绩,就可以遍历该链表,并清除学生的节点,*要结束输入时,输入“-1”,则此时会列出该链表未删除的所有学生数据。**@author86176**///构建节点类publicclassNode{ intdata; int…

    2022年5月18日
    39
  • eclipse安装教程(win10)

    eclipse安装教程(win10)1.官网下载下载链接:http://www.eclipse.org/downloads/2.运行运行后有很多版本可供选择EclipseIDEforJavaDevelopers是为java开发的EclipseIDEforJavaEEDevelopers是为J2EE开发的EclipseforRCP/Plug-inDevelopers是…

    2022年6月8日
    37
  • JAVA的一般输入输出 和 快速输入输出 (BufferedReader&BufferedWrite)

    JAVA的一般输入输出 和 快速输入输出 (BufferedReader&BufferedWrite)JAVA基础知识和常用算法合集:https://blog.csdn.net/GD_ONE/article/details/104061907目录1.主类的命名必须是Main2.输入输出:2.1输入:(1)使用Scanner类进行输入(2)hasNext()方法2.2输出3快速输入输出3.1使用StreamTokenizer和PrintW…

    2022年5月26日
    38
  • 基于python的情感分析案例_约翰肯尼格的悲伤词典

    基于python的情感分析案例_约翰肯尼格的悲伤词典情感分析是大数据时代常见的一种分析方法,多用于对产品评论的情感挖掘,以探究顾客的满意度程度。在做情感分析时,有两种途径:一种是基于情感词典的分析方法,一种是基于机器学习的方法,两者各有利弊。在此,笔者主要想跟大家分享基于python平台利用情感词典做情感分析的方法。本文主要参考https://blog.csdn.net/lom9357bye/article/details/79058946这篇文章,在此文章中,博主用一句简单的语句“我今天很高兴也非常开心”向我们清楚的展示的利用情感词典做情感分析的方法,这

    2022年8月23日
    3
  • Mathtype公式编辑器常用快捷键

    Mathtype公式编辑器常用快捷键文章目录Mathtype公式编辑器常用快捷键1.放大或缩小尺寸2.在数学公式中插入一些符号3.微移间隔4.元素间的跳转用键盘选取菜单或工具条贴加常用公式Mathtype公式编辑器常用快捷键1.放大或缩小尺寸Ctrl+1(100%);Ctrl+2(200%);Ctrl+4(400%);Ctrl+8(800%)。2.在数学公式中插入一些符号Ctrl+9或Ctrl+0(小括号);Ctrl+[或Ctrl+](中括号);Ctrl+{或Ctrl+}(大括号);Ctrl+F(分式);Ctrl+/(斜杠

    2025年6月18日
    2
  • CentOS7配置LLDP服务

    CentOS7配置LLDP服务作者:BK运维团队成员官方链接:https://vincentbernat.github.io/lldpd/usage.html官方图片:什么是lldpdLLDP可以让你准确的知道服务器所连接的交换机端口号。LLDP是一种工业标准协议,用于取代EDP或CDP等专用链路层协议。LLDP的目标是提供一个inter-vendor兼容机制,向相邻网络设备发送链路层通知。lldpd是一个L…

    2022年5月28日
    109

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号