#include<opencv2/opencv.hpp>
#include<iostream>
#include<vector>
using namespace cv;
using namespace std;
int g_nMinThred = 125;
int g_nMaxThred = 255;
int g_nColor = 255;
int g_CheckWay = 0;
int g_nThick = 0;
int main()
{
RNG &rng = theRNG();
Mat srcImage = imread("group.jpg");
imshow("【原图】", srcImage);
//因为后期需要在二值图像中寻找轮廓,所以需要进行阀值操作或是使用canny边缘检测操作,无论是哪种方式,都需要输入一张灰度图像
//所以这里先进行图像格式的转换
Mat grayImage;
cvtColor(srcImage, grayImage, CV_BGR2GRAY);
//处理图像之前先对图像进行滤波操作
Mat blurImage;
GaussianBlur(grayImage, blurImage, Size(3, 3), 0, 0);
imshow("【高斯滤波后的灰度图】", blurImage);
namedWindow("【滚动条窗口】", 0);
createTrackbar("MinThred", "【滚动条窗口】", &g_nMinThred, 255, 0);
createTrackbar("MaxThred", "【滚动条窗口】", &g_nMaxThred, 255, 0);
createTrackbar("Color", "【滚动条窗口】", &g_nColor, 255, 0);
createTrackbar("CheckWay", "【滚动条窗口】", &g_CheckWay, 2, 0);
createTrackbar("thick", "【滚动条窗口】", &g_nThick, 100, 0);
char key;
while (1)
{
//这里采用边缘检测的方式来生成二值图像
Mat cannyImage;
Canny(blurImage, cannyImage, g_nMinThred + 1, g_nMaxThred + 1);
//在得到的二值图像中寻找轮廓
//g_vcontours用来存储 所有轮廓 的 点向量
vector<vector<Point>> g_vcontours;
vector<Vec4i> g_vHierarchy;
findContours(cannyImage, g_vcontours, g_vHierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
//在被找到的所有轮廓的点向量中,寻找凸包
//g_vHull用来存储 所有凸包检测的凸包 的点集 ,注意:这里的g_vHull变量需要确定大小,保证输入和输出的大小相同
vector<vector<Point>> g_vHull(g_vcontours.size());
for (int i = 0; i < (int)g_vcontours.size(); i++)
{
convexHull(g_vcontours[i], g_vHull[i], true);
}
//首先建立一个黑色背景
Mat dstImage = Mat::zeros(srcImage.size(), CV_8UC1);
for (int i = 0; i < (int)g_vcontours.size(); i++)
{
//如果g_CheckWay变量是0,表示轮廓和凸包都显示,如果是1 仅仅显示轮廓, 如果是2 仅仅显示凸包
if (g_CheckWay == 0)
{
//用drawContours函数先绘制所有轮廓
drawContours(dstImage, g_vcontours, i, Scalar(g_nColor), g_nThick + 1, 8);
//用drawContours函数绘制所有的凸包
drawContours(dstImage, g_vHull, i, Scalar(g_nColor), g_nThick + 1, 8);
}
if (g_CheckWay == 1)
{
//用drawContours函数先绘制所有轮廓
drawContours(dstImage, g_vcontours, i, Scalar(g_nColor), g_nThick + 1, 8);
}
if (g_CheckWay == 2)
{
//用drawContours函数绘制所有的凸包
drawContours(dstImage, g_vHull, i, Scalar(g_nColor), g_nThick + 1, 8);
}
}
imshow("【处理后的图像】", dstImage);
key = waitKey(1);
if (key == 27)
break;
}
return 0;
}
来源:CSDN
作者:轩落_翼
链接:https://blog.csdn.net/qq_23880193/article/details/49257193