OpenCV Tutorials —— Creating Bounding boxes and circles for contours

同样是提取出轮廓之后的处理 ~~

 

void approxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool closed)

Parameters:

  • curve

    Input vector of a 2D point stored in:

    • std::vector or Mat (C++ interface)
    • Nx2 numpy array (Python interface)
    • CvSeq or CvMat (C interface)
  • approxCurve – Result of the approximation. The type should match the type of the input curve. In case of C interface the approximated curve is stored in the memory storage and pointer to it is returned.
  • epsilon – Parameter specifying the approximation accuracy. This is the maximum distance between the original curve and its approximation.
  • closed – If true, the approximated curve is closed (its first and last vertices are connected). Otherwise, it is not closed.
  • header_size – Header size of the approximated curve. Normally, sizeof(CvContour) is used.
  • storage – Memory storage where the approximated curve is stored.
  • method – Contour approximation algorithm. Only CV_POLY_APPROX_DP is supported.
  • recursive – Recursion flag. If it is non-zero and curve is CvSeq*, the function cvApproxPolyapproximates all the contours accessible from curve by h_next and v_next links.

Rect boundingRect(InputArray points)

Calculates the up-right bounding rectangle of a point set.

void minEnclosingCircle(InputArray points, Point2f& center, float& radius)

Parameters:

  • points

    Input vector of 2D points, stored in:

    • std::vector<> or Mat (C++ interface)
    • CvSeq* or CvMat* (C interface)
    • Nx2 numpy array (Python interface)
  • center – Output center of the circle.
  • radius – Output radius of the circle.

 

 

 

Code

#include "stdafx.h"

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace cv;
using namespace std;

Mat src; Mat src_gray;
int thresh = 100;
int max_thresh = 255;
RNG rng(12345);

/// Function header
void thresh_callback(int, void* );

/** @function main */
int main( int argc, char** argv )
{
	/// Load source image and convert it to gray
	src = imread( "img2.jpg", 1 );

	/// Convert image to gray and blur it
	cvtColor( src, src_gray, CV_BGR2GRAY );
	blur( src_gray, src_gray, Size(3,3) );	// 均值滤波 —— 去除小的噪声

	/// Create Window
	char* source_window = "Source";
	namedWindow( source_window, CV_WINDOW_AUTOSIZE );
	imshow( source_window, src );

	createTrackbar( " Threshold:", "Source", &thresh, max_thresh, thresh_callback );
	thresh_callback( 0, 0 );

	waitKey(0);
	return(0);
}

/** @function thresh_callback */
void thresh_callback(int, void* )
{
	Mat threshold_output;
	vector<vector<Point> > contours;
	vector<Vec4i> hierarchy;

	/// Detect edges using Threshold
	threshold( src_gray, threshold_output, thresh, 255, THRESH_BINARY );
	/// Find contours
	findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

	/// Approximate contours to polygons + get bounding rects and circles
	vector<vector<Point> > contours_poly( contours.size() );
	vector<Rect> boundRect( contours.size() );
	vector<Point2f>center( contours.size() );
	vector<float>radius( contours.size() );

	for( int i = 0; i < contours.size(); i++ )
	{
		approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );	// 原始曲线和近似曲线的精度为3, 近似曲线封闭
		boundRect[i] = boundingRect( Mat(contours_poly[i]) );
		minEnclosingCircle( (Mat)contours_poly[i], center[i], radius[i] );
	}

	/// Draw polygonal contour + bonding rects + circles
	Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
	for( int 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, 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 );
	}

	/// Show in a window
	namedWindow( "Contours", CV_WINDOW_AUTOSIZE );
	imshow( "Contours", drawing );
}
时间: 2025-01-16 00:29:11

OpenCV Tutorials —— Creating Bounding boxes and circles for contours的相关文章

OpenCV Tutorials &mdash;&mdash; Creating Bounding rotated boxes and ellipses for contours

外接旋转矩形 ,或外接椭圆   RotatedRect minAreaRect(InputArray points) 返回面积最小的外接矩形 RotatedRect fitEllipse(InputArray points) The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of all. It returns the rotated rectangle

OpenCV Tutorials &mdash;&mdash; Creating a video with OpenCV

写video 需要用到 VideoWriter  视频文件可看作一个容器 视频的类型由视频文件的后缀名来指定   Due to this OpenCV for video containers supports only the avi extension, its first version. A direct limitation of this is that you cannot save a video file larger than 2 GB. Furthermore you ca

OpenCV Tutorials &mdash;&mdash; Creating yor own corner detector

Use the OpenCV function cornerEigenValsAndVecs to find the eigenvalues and eigenvectors to determine if a pixel is a corner. Use the OpenCV function cornerMinEigenVal to find the minimum eigenvalues for corner detection.   最小特征值对应的角点监测 ~~ 对自相关矩阵 M 进行

OpenCV Tutorials —— Creating Widgets

Explanation Extend Widget3D class to create a new 3D widget. Assign a VTK actor to the widget. Set color of the widget. Construct a triangle widget and display it in the window. Code #include <opencv2/viz/vizcore.hpp> #include <opencv2/viz/widget

学习opencv tutorials

1.opencv里头动态库和静态库的区别 lib是动态库,staticlib是静态库. 这是opencv tutorials中对动态库和静态库的说明.动态库是在runtime时候才load的库文件.而静态库文件会在你build的时候build-in inside your exe file.优点是可以避免误删,缺点是应用程序变大,加载时间也会变长. 2.  Visual Studio中solution和project的关系 在VS中,一个solution中可以包含多个project. 3.  两

OpenCV Tutorials &mdash;&mdash; Basic Drawing

Point It represents a 2D point, specified by its image coordinates and . We can define it as: Point pt;pt.x = 10;pt.y = 8; or Point pt = Point(10, 8); Scalar Represents a 4-element vector. The type Scalar is widely used in OpenCV for passing pixel va

OpenCV Tutorials &mdash;&mdash; Random generator and text with OpenCV

creating a Random Number Generator object (RNG): RNG rng( 0xFFFFFFFF ); 创建并初始化随机数生成子 create a matrix initialized to zeros (which means that it will appear as black), specifying its height, width and its type: /// Initialize a matrix filled with zeros

OpenCV Tutorials &mdash;&mdash; Hough Circle Transform

Hough 圆变换 和 Hough 直线变换原理相同,只是参数空间不同 : In the line detection case, a line was defined by two parameters . In the circle case, we need three parameters to define a circle: where define the center position (gree point) and is the radius, which allows us

OpenCV Tutorials &mdash;&mdash; Mat

if you pass on an already existing Mat object, which has already allocated the required space for the matrix, this will be reused. The idea is that each Mat object has its own header, however the matrix may be shared between two instance of them by h