将一个图片的各个轮廓用凸包包围。

#include <iostream>
#include <opencv2/opencv.hpp>


using namespace cv;
using namespace std;



#define window "【原始图】"
#define windowx "【结果图1】"
#define windowy "[结果图2]"
//

RNG rng = theRNG();
int thresh = 40;
Mat edge;
Mat src_gray;
Mat result;

void on_thresh(int,void*);
int main()
{
	//1.读取图片并对图片进行灰度化处理
	Mat src = imread("21.jpg");
	
	cvtColor(src,src_gray,CV_BGR2GRAY);
	imshow(window,src_gray);
	//2.对图片过滤,并且进行阈值化处理
	blur(src_gray,src_gray,Size(3,3));

	namedWindow(windowx);
	createTrackbar("thresh",windowx,&thresh,255,on_thresh);
	imshow(windowx,src);

	
	
		

	

	waitKey(0);
	return 0;

}


void on_thresh(int,void*)
{
	threshold(src_gray,edge,thresh,255,THRESH_BINARY);
	
	//3.找图片的轮廓。findcouter
	vector<vector<Point>> contours;
	vector<Vec4i> index;
	findContours(edge, contours, index, CV_RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
	//4.找出各个轮廓的点集的凸包。
	vector<vector<Point>> hull(contours.size());//.........................多少个这样的hull,有多少轮廓数,就有多少个凸包。hull有两种方式,一种是返回下标,一种是直接返回点。
	for (int i = 0; i < contours.size(); ++i)
	{

		convexHull(contours[i], hull[i], false);

	}
	//5.将这些凸包画在与原图一样大的图像上。
	result = Mat::zeros(src_gray.size(), CV_8UC3);
	for (int i = 0; i < hull.size(); ++i)
	{
		//line(result,hull[i][0],hull[i][hull[i].size()-1],Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255)));
		Point pre = hull[i][hull[i].size() - 1];
		int color = rng.uniform(0, 255);
		for (int j = 0; j < hull[i].size(); ++j)
		{

			line(result, pre, hull[i][j], Scalar(color, color, color));
			pre = hull[i][j];

		}


	}
	//6.显示结果。
	imshow(windowx, result);
	//
}

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章