OpenCV/C++ Canny Edge Detector

偷偷拿来记录一下萌新的cs路——day 44 用于暑假作业的边缘检测

Canny 的原理:

1. 图像灰度化

由于后续需要检测边缘,故图像需要为黑白两色。

2. 图像去噪

噪音过多会导致边缘的误检测,故图像需要进行去噪处理,可以使用中值滤波、高斯滤波等。卷积核越大,对噪音敏感度越低,一般使用3x3 or 5x5 。

4. 对梯度幅度进行非极大值抑制

这部分暂时没有理解,后续再更。

3. 检测边缘

主要运用双阈值算法:给定上下两个阈值,低阈值TL 和高阈值TH,梯度值高于TH 的赋值255/1,低于TL 的赋值0,TH 邻域内像素全部视作TH,TL邻域内像素视作TL,起到边缘细化、对比度增加的作用。

#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2\imgproc\types_c.h>
#include <opencv2/highgui/highgui_c.h>

using namespace std;
using namespace cv;

int main()
{
    cv::Mat imgOriginal;        // input image
    cv::Mat imgGrayscale;       // grayscale of input image
    cv::Mat imgBlurred;         // intermediate blured image
    cv::Mat imgCanny;           // Canny edge image

    std::cout << "Please enter an image filename : ";
    std::string img_addr;
    std::cin >> img_addr;
    std::cout << "Searching for " + img_addr << std::endl;

    imgOriginal = cv::imread(img_addr);     // open image

    if (imgOriginal.empty()) {                                   
        std::cout << "error: image not read from file\n\n";      // show error message
        return(0);                                           
    }

    cv::cvtColor(imgOriginal, imgGrayscale, CV_BGR2GRAY);        // convert to grayscale

    cv::GaussianBlur(imgGrayscale,          // input image
        imgBlurred,                         // output image
        cv::Size(5, 5),                     // smoothing window width and height in pixels
        1.5);                               // sigma value, determines how much the image will be blurred

    cv::Canny(imgBlurred,                   // input image
        imgCanny,                           // output image
        100,                                // low threshold
        200);                               // high threshold


    // Declare windows
    // Note: you can use CV_WINDOW_NORMAL which allows resizing the window
    // or CV_WINDOW_AUTOSIZE for a fixed size window matching the resolution of the image
    // CV_WINDOW_AUTOSIZE is the default
    cv::namedWindow("imgOriginal", CV_WINDOW_AUTOSIZE);
    cv::namedWindow("imgCanny", CV_WINDOW_AUTOSIZE);

    //Show windows
    cv::imshow("imgOriginal", imgOriginal);
    cv::imshow("imgCanny", imgCanny);

    cv::waitKey(0);                    // hold windows open until user presses a key
    return 0;
}

运行结果:

学了更多知识还会回来更新的!有误之处请大佬指正,非常感谢!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值