如何使用opencv 绘制轮廓边框最小包裹 多边形 圆形 矩形?
函数说明:
Rect boundingRect(InputArray points)
points:输入信息,可以为包含点的容器(vector)或是Mat。
返回包覆输入信息的最小正矩形。
RotatedRect minAreaRect(InputArray points)
points:输入信息,可以为包含点的容器(vector)或是Mat。
返回包覆输入信息的最小斜矩形。
void minEnclosingCircle(InputArray points, Point2f& center, float& radius)
points:输入信息,可以为包含点的容器(vector)或是Mat。
center:包覆圆形的圆心。
radius:包覆圆形的半径。
void approxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool closed)
InputArray curve:一般是由图像的轮廓点组成的点集
OutputArray approxCurve:表示输出的多边形点集
double epsilon:主要表示输出的精度,就是另个轮廓点之间最大距离数,5,6,7,,8,,,,
bool closed:表示输出的多边形是否封闭
代码实现:
JNIEXPORT void JNICALL
Java_org_opencv_samples_tutorial2_Tutorial2Activity_FindFeatures(JNIEnv *, jobject, jlong addrGray,
jlong addrRgba) {
Mat &mGr = *(Mat *) addrGray;
Mat &mRgb = *(Mat *) addrRgba;
vector<KeyPoint> v;
looperAddNum++;
if (looperAddNum > 60) {
looperAddNum = 0;
if (looperIndexNum < 100)
looperIndexNum += 1;
}
blur(mGr, mGr, Size(3,3));
Mat threshold_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
threshold( mGr, threshold_output, 100, 255, THRESH_BINARY );
findContours( threshold_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );
vector<vector<Point> > contours_poly( contours.size() );
vector<Rect> boundRect( contours.size() );
vector<Point2f>center( contours.size() );
vector<float>radius( contours.size() );
for( size_t i = 0; i < contours.size(); i++ )
{
approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );// 多边形转换
boundRect[i] = boundingRect( Mat(contours_poly[i]) );
minEnclosingCircle( contours_poly[i], center[i], radius[i] );
}
Mat drawing = mRgb;
for( size_t i = 0; i< contours.size(); i++ )
{
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
drawContours( drawing, contours_poly, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );
rectangle( drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0 );
circle( drawing, center[i], (int)radius[i], color, 2, 8, 0 );
}
LOGI("index %d", looperIndexNum);
}