图像轮廓与图像分隔修复(2):4
四,综合示例程序:查找并绘制轮廓
===================
此程序利用了图像平滑技术(blur()函数)和边缘检测技术(canny()函数),根据滑动条的调节,可以动态地检测出图形的轮廓。
代码如下:
//-------------【头文件、命名空间部分】--------------
// 描述:包含程序所依赖的头文件和命名空间
//---------------------------------------------------
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/utils/logger.hpp>
#include <iostream>
using namespace std;
using namespace cv;
//-------------------【宏定义部分】----------------------
// 描述:定义一些辅助宏(窗口标题)
//-------------------------------------------------------
#define WINDOW_NAME1 "【原始图】"
#define WINDOW_NAME2 "【轮廓图】"
//-------------【全局变量声明部分】--------------
// 描述:全局变量声明
//-----------------------------------------------
Mat g_srcImage;
Mat g_grayImage;
int g_nThresh = 80;
int g_nThresh_max = 255;
RNG g_rng(12345);
Mat g_cannyMat_output;
vector<vector<Point>> g_vContours;
vector<Vec4i> g_vHierarchy;
//-------------【全局函数声明部分】--------------
// 描述:全局函数声明
//-----------------------------------------------
void on_ThreshChange(int, void*);
int main()
{
cv::utils::logging::setLogLevel(utils::logging::LOG_LEVEL_SILENT);//控制台不在输出日志文件
//加载图像
g_srcImage = imread("E:/pictures/2.jpg", 1);
if (!g_srcImage.data)
{
printf("图片不存在
");
return false;
}
//转成灰度图并模糊化降噪
cvtColor(g_srcImage, g_grayImage, COLOR_BGR2GRAY);
blur(g_grayImage, g_grayImage, Size(3, 3));
//创建窗口
namedWindow(WINDOW_NAME1, WINDOW_AUTOSIZE);
imshow(WINDOW_NAME1, g_srcImage);
//创建滚动条并初始化
createTrackbar("canny阈值", WINDOW_NAME1, &g_nThresh, g_nThresh_max, on_ThreshChange);
on_ThreshChange(0, 0);
waitKey(0);
return 0;
}
//----------------【on_ThreshChange()函数】---------------
// 描述:回调函数
//---------------------------------------------------
void on_ThreshChange(int, void*)
{
//用Canny算子检测边缘
Canny(g_grayImage, g_cannyMat_output, g_nThresh, g_nThresh * 2, 3);
//寻找轮廓
findContours(g_cannyMat_output, g_vContours, g_vHierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
//绘制轮廓
Mat drawing = Mat::zeros(g_cannyMat_output.size(), CV_8UC3);
for (int i = 0; i < g_vContours.size(); i++)
{
Scalar color = Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255)); //任意值
drawContours(drawing, g_vContours, i, color, 2, 8, g_vHierarchy, 0, Point());
}
imshow(WINDOW_NAME2, drawing);
}
运行结果:
canny值为80:
canny值为187: