![cfa76b9998af09c8857e91ddeb3a531e.png](https://i-blog.csdnimg.cn/blog_migrate/e190b0ffd1cfdc107325fcdc6604622d.jpeg)
1. 用 Canny 算子检测图像轮廓
介绍: 使用 Canny 算子,需要指定两个阈值,基于两个阈值获得二值分布图的策略(滞后阈值化)。在低阈值边缘分布图上值保留具有连续路径的边缘点,同时把那些边缘点连接到属于高阈值边缘分布图的边缘上,高阈值的边缘点被保留下来,低阈值分布图上的孤立点全部被移除。
例子代码
#include<opencv2/opencv.hpp>
#include<iostream>
#include<string>
using namespace cv;
using namespace std;
void test()
{
Mat srcImg = imread("road.jpg");
if (srcImg.empty())
{
cout << "could not load image...n" << endl;
return;
}
namedWindow("input image", CV_WINDOW_AUTOSIZE);
imshow("input image", srcImg);
Mat grayImg,contoursImg;
cvtColor(srcImg, grayImg, CV_BGR2GRAY);
Canny(grayImg, contoursImg, 125, 350);
namedWindow("output image", CV_WINDOW_AUTOSIZE);
imshow("output image", contoursImg);
}
int main()
{
test();
waitKey(0);
return 0;
}
效果图
![cc0b5162ba1dbcbdb97d3ad17c530b43.png](https://i-blog.csdnimg.cn/blog_migrate/bb4a3059cd5e7b431caacc6401385369.jpeg)
2. 发现轮廓
介绍:是基于图像边缘提取基础寻找对象轮廓的方法,边缘提取的阈值选定会影响最终轮廓发现结果。
步骤: - 输入图像转为灰度图像 - 使用 Canny 进行边缘提取,得到二值图像 - 使用 findContours 寻找轮廓 - 使用 drawContours 绘制轮廓
例子代码
#include<opencv2/opencv.hpp>
#include<iostream>
#include<string>
using namespace cv;
using namespace std;
Mat srcImg, dstImg;
int thresholdValue = 100;
int thresholdMax = 255;
void DemoContours(int ,void *)
{
Mat cannyOutput;
vector<vector<Point>>contours;
vector<Vec4i> hierachy; //层次
Canny(srcImg, cannyOutput, thresholdValue, thresholdValue * 2, 3, false);
//找轮廓
findContours(cannyOutput, //输入图像,非0的像素被看成1,0的像素值保持不变,8-bit
contours, //全部发现的轮廓对象
hierachy, //该图的拓扑结构,可选,该轮廓发现算法正是基于图像拓扑结构实现
RETR_TREE, //轮廓返回模式
CHAIN_APPROX_SIMPLE, //发现方法
Point(0, 0)); //轮廓像素的位移 默认(0, 0)没有