这一节的综合示例程序,依然是结合滑动条,通过滑动条控制阈值,来得到不同的凸包检测效果图。程序详细注释的源代码如下。
//-------------【头文件、命名空间部分】--------------
// 描述:包含程序所依赖的头文件和命名空间
//---------------------------------------------------
#include
#include
#include
#include
using namespace std;
using namespace cv;
//-------------------【宏定义部分】----------------------
// 描述:定义一些辅助宏(窗口标题)
//-------------------------------------------------------
#define WINDOW_NAME1 "【原始图】"
#define WINDOW_NAME2 "【效果图】"
//-------------【全局变量声明部分】--------------
// 描述:全局变量声明
//-----------------------------------------------
Mat g_srcImage;
Mat g_grayImage;
int g_nThresh = 50;
int g_maxThresh = 255;
RNG g_rng(12345);
Mat srcImage_copy = g_srcImage.clone();
Mat g_thresholdImage_output;
vector> g_vContours;
vector 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("图片不存在\n");
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("阈值:", WINDOW_NAME1, &g_nThresh, g_maxThresh, on_ThreshChange);
on_ThreshChange(0, 0); //调用一次进行初始化
waitKey(0);
return 0;
}
//----------------【on_ThreshChange()函数】---------------
// 描述:回调函数
//---------------------------------------------------
void on_ThreshChange(int, void*)
{
//对图像进行二值化,控制阈值
threshold(g_grayImage, g_thresholdImage_output, g_nThresh, 255, THRESH_BINARY);
//寻找轮廓
findContours(g_thresholdImage_output, g_vContours, g_vHierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
//遍历每个轮廓,寻找其凸包
vector> hull(g_vContours.size());
for (unsigned int i = 0; i < g_vContours.size(); i++)
{
convexHull(Mat(g_vContours[i]), hull[i], false);
}
//绘制轮廓及其凸包
Mat drawing = Mat::zeros(g_thresholdImage_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, 1, 8, vector(), 0, Point());
drawContours(drawing, hull, i, color, 1, 8, vector(), 0, Point());
}
//显示效果图
imshow(WINDOW_NAME2, drawing);
}
运行结果: