OpenCV4入门教程094:寻找最大内接圆

索引地址:系列索引

和上一篇一样,不过本篇的轮廓形状为圆.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//---------------------------------【头文件、命名空间包含部分】----------------------------
// 描述:包含程序所使用的头文件和命名空间
//------------------------------------------------------------------------------------------------
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;

//-----------------------------------【ShowHelpText( )函数】----------------------------------
// 描述:输出一些帮助信息
//----------------------------------------------------------------------------------------------
static void ShowHelpText() {

//输出欢迎信息和OpenCV版本
printf("\n\n\t\t\t非常感谢购买《OpenCV3编程入门》一书!\n");
printf("\n\n\t\t\t此为本书OpenCV3版的第13个配套示例程序\n");
printf("\n\n\t\t\t 当前使用的OpenCV版本为:" CV_VERSION);
printf("\n\n ----------------------------------------------------------------------------\n");

//输出一些帮助信息
printf("\n\n\t\t\t欢迎来到【寻找最小面积的包围圆】示例程序~\n");
printf("\n\n\t按键操作说明: \n\n"
"\t\t键盘按键【ESC】、【Q】、【q】- 退出程序\n\n"
"\t\t键盘按键任意键 - 重新生成随机点,并寻找最小面积的包围圆\n");
}

int main() {
//显示帮助文字
ShowHelpText();

//初始化变量和随机值
Mat image(600, 600, CV_8UC3);
RNG &rng = theRNG();

//循环,按下ESC,Q,q键程序退出,否则有键按下便一直更新
while (1) {
//参数初始化
int count = rng.uniform(3, 103); //随机生成点的数量
vector<Point> points; //点值

//随机生成点坐标
for (int i = 0; i < count; i++) {

Point point;
point.x = rng.uniform(image.cols / 4, image.cols * 3 / 4);
point.y = rng.uniform(image.rows / 4, image.rows * 3 / 4);

points.push_back(point);
}

//对给定的 2D 点集,寻找最小面积的包围圆
Point2f center;
float radius = 0;
minEnclosingCircle(Mat(points), center, radius);

//绘制出随机颜色的点
image = Scalar::all(0);
for (int i = 0; i < count; i++)
circle(image, points[ i ], 3,
Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), FILLED,
LINE_AA);

//绘制出最小面积的包围圆
circle(image, center, cvRound(radius),
Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), 2, LINE_AA);

//显示窗口
imshow("Result", image);

//按下ESC,Q,或者q,程序退出
char key = (char)waitKey();
if (key == 27 || key == 'q' || key == 'Q') // 'ESC'
break;
}

return 0;
}

效果为:


OpenCV4入门教程094:寻找最大内接圆
https://feater.top/opencv/opencv-find-max-area-circle/
作者
JackeyLea
发布于
2020年9月13日
许可协议