偷偷拿来记录一下萌新的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;
}
运行结果:
学了更多知识还会回来更新的!有误之处请大佬指正,非常感谢!