1 #include<opencv2/opencv.hpp>
2 #include<iostream>
3 #include<vector>
4
5 using namespace cv;
6 using namespace std;
7
8 int g_nMinThred = 128, g_nMaxThred = 255;
9 int g_nThick = 0;
10
11 int main()
12 {
13 Mat srcImage = imread("group.jpg");
14
15 namedWindow("【原图】", 0);
16 imshow("【原图】", srcImage);
17
18 createTrackbar("minthred", "【原图】", &g_nMinThred, 255, 0);
19 createTrackbar("maxthred", "【原图】", &g_nMaxThred, 255, 0);
20 createTrackbar("thick", "【原图】", &g_nThick, 100, 0);
21
22 //先对图像进行空间的转换(为了之后要提取二值图像)
23 Mat grayImage;
24 cvtColor(srcImage, grayImage, CV_BGR2GRAY);
25 //对图像进行滤波,达到较好的效果
26 GaussianBlur(grayImage, grayImage, Size(3, 3), 0, 0);
27 imshow("【滤波后的图像】", grayImage);
28
29 char key;
30 while (1)
31 {
32 //用边缘检测的方式获取二值图像
33 Mat cannyImage;
34 Canny(grayImage, cannyImage, g_nMinThred, g_nMaxThred, 3);
35
36 //在二值图像中提取轮廓
37 vector<vector<Point>> contours;
38 vector<Vec4i> hierarchy;
39 findContours(cannyImage, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
40
41 //对每个轮廓的点集 找逼近多边形
42 vector<vector<Point>> approxPoint(contours.size());
43 for (int i = 0; i < (int)contours.size(); i++)
44 {
45 //rectPoint变量中得到了矩形的四个顶点坐标
46 RotatedRect rectPoint = minAreaRect(contours[i]);
47 //定义一个存储以上四个点的坐标的变量
48 Point2f fourPoint2f[4];
49 //将rectPoint变量中存储的坐标值放到 fourPoint的数组中
50 rectPoint.points(fourPoint2f);
51
52 //根据得到的四个点的坐标 绘制矩形
53 for (int i = 0; i < 3; i++)
54 {
55 line(cannyImage, fourPoint2f[i], fourPoint2f[i + 1]
56 , Scalar(255, 255, 255), g_nThick);
57 }
58 line(cannyImage, fourPoint2f[0], fourPoint2f[3]
59 , Scalar(255, 255, 255), g_nThick);
60 }
61
62 imshow("【绘制后的图像】", cannyImage);
63
64 key = waitKey(1);
65 if (key == 27)
66 break;
67 }
68
69 return 0;
70 }