1. 程式人生 > >opencv3尋找最小包圍圓形在影象中的應用-滾動條

opencv3尋找最小包圍圓形在影象中的應用-滾動條

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

using namespace cv;
using namespace std;

int g_nMinThred = 128, g_nMaxThred = 255;
int g_nThick = 0;

int main()
{
	Mat srcImage = imread("group.jpg");

	namedWindow("【原圖】", 0);
	imshow("【原圖】", srcImage);

	createTrackbar("minthred", "【原圖】", &g_nMinThred, 255, 0);
	createTrackbar("maxthred", "【原圖】", &g_nMaxThred, 255, 0);
	createTrackbar("thick", "【原圖】", &g_nThick, 100, 0);

	//先對影象進行空間的轉換(為了之後要提取二值影象)
	Mat grayImage;
	cvtColor(srcImage, grayImage, CV_BGR2GRAY);
	//對影象進行濾波,達到較好的效果
	GaussianBlur(grayImage, grayImage, Size(3, 3), 0, 0);
	imshow("【濾波後的影象】", grayImage);

	char key;
	while (1)
	{
		//用邊緣檢測的方式獲取二值影象
		Mat cannyImage;
		Canny(grayImage, cannyImage, g_nMinThred, g_nMaxThred, 3);

		//在二值影象中提取輪廓
		vector<vector<Point>> contours;
		vector<Vec4i> hierarchy;
		findContours(cannyImage, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));

		//對每個輪廓的點集 找逼近多邊形
		vector<vector<Point>> approxPoint(contours.size());
		for (int i = 0; i < (int)contours.size(); i++)
		{
			//在生成的那些隨機點中尋找最小包圍圓形
			Point2f center;
			float radius;
			minEnclosingCircle(contours[i], center, radius);

			//根據得到的圓形和半徑  繪製圓形
			circle(cannyImage, static_cast<Point>(center), (int)radius
				, Scalar(255, 255, 255), g_nThick + 1);
		}

		imshow("【繪製後的影象】", cannyImage);

		key = waitKey(1);
		if (key == 27)
			break;
	}

	return 0;
}