opencv3.1 example解析1 求最小包圍圓和最小包圍矩形以及最小包圍三角形
阿新 • • 發佈:2019-02-12
最小包圍這類的我一直沒有注意,在換了團隊之後,新的團隊要求將目標如何如何標記出來。所以找了這個例子寫一下注釋,方便以後檢視
思路遠比實現更重要,下面是將要註釋的程式碼的程式碼思路
所解釋的例子結構是:
標頭檔案
help函式
main函式
定義mat
產生隨機點
產生最小包圍的矩形等
繪製出來
顯示圖片
以下是例子以及註釋,原始檔為opencv自帶例子的minarea.cpp檔案
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
static void help()
{
cout << "This program demonstrates finding the minimum enclosing box, triangle or circle of a set\n"
<< "of points using functions: minAreaRect() minEnclosingTriangle() minEnclosingCircle().\n"
<< "Random points are generated and then enclosed.\n\n"
<< "Press ESC, 'q' or 'Q' to exit and any other key to regenerate the set of points.\n\n";
}
int main( int /*argc*/, char** /*argv*/ )
{
help();
Mat img(500, 500, CV_8UC3);// 初始化一個Mat圖片
RNG& rng = theRNG();// 建立一個隨機數生成器。這個RNG類還有其他用法,視覺化的時候有些用處
for(;;)//for語句的語法規定,括號裡面一定要有兩個分號,分開三個句子。
//第一個句子是初始化用的,如果沒有初始化的必要,就視為空語句,加上分號;
//第二個句子作為判斷條件,如果沒有判斷條件,也視為空語句,後加一個分號。這種情況,會無限迴圈,相當於while(1)。如果for的執行部分,就是{}之間有break語句,可以退出;
//第三個句子是執行部分執行完畢再執行的語句;無則視為空語句;此時不用再加分號。
{
int i, count = rng.uniform(1, 101);
vector<Point> points;
// Generate a random set of points
for( i = 0; i < count; i++ )
{
Point pt;
pt.x = rng.uniform(img.cols/4, img.cols*3/4);// uniform返回指定範圍內的一個隨機數
pt.y = rng.uniform(img.rows/4, img.rows*3/4);
points.push_back(pt);//
}
// Find the minimum area enclosing bounding box// 找最小封閉的邊界框
Point2f vtx[4];
RotatedRect box = minAreaRect(points);
box.points(vtx);
// Find the minimum area enclosing triangle// 找最小封閉三角形
vector<Point2f> triangle;
minEnclosingTriangle(points, triangle);
// Find the minimum area enclosing circle// 找最小包圍圓
Point2f center;
float radius = 0;
minEnclosingCircle(points, center, radius);
img = Scalar::all(0);// 影象都置零
// Draw the points
for( i = 0; i < count; i++ )
circle( img, points[i], 3, Scalar(0, 0, 255), FILLED, LINE_AA );
// Draw the bounding box
for( i = 0; i < 4; i++ )
line(img, vtx[i], vtx[(i+1)%4], Scalar(0, 255, 0), 1, LINE_AA);
// Draw the triangle
for( i = 0; i < 3; i++ )
line(img, triangle[i], triangle[(i+1)%3], Scalar(255, 255, 0), 1, LINE_AA);
// Draw the circle
circle(img, center, cvRound(radius), Scalar(0, 255, 255), 1, LINE_AA);
imshow( "Rectangle, triangle & circle", img );
char key = (char)waitKey();// 這個無限迴圈中,這兩行用於判斷是否終止迴圈
if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
break;
}
return 0;
}
注意:
函式 cvRound, cvFloor, cvCeil 用一種舍入方法將輸入浮點數轉換成整數。
(1)cvRound 返回和引數最接近的整數值。
(2)cvFloor 返回不大於引數的最大整數值。
(3)cvCeil 返回不小於引數的最小整數值。
其實,這個例子網上早就有其他人寫過了,還挺詳細,所以我只註釋我需要注意的部分。限於版權要求,我不能直接用別人的,在這裡放一下連結:最小包圍形狀原始碼別人的解析
最小包圍圓的函式有時候會無法給出結果不能在那跑