opencv29-轮廓周围绘制矩形框和圆形框

#include<opencv2\opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
using namespace std;
Mat src, temp, dst, src_gray;
int threshold_v = 170;
int threshold_max = 255;
char *output = "output image";
RNG rng;
void Contours_Callback(int, void*);
int main()
{
	//加载图像
	src = imread("E:\\vs2015\\opencvstudy\\29police.jpg");
	if (!src.data)
	{
		cout << "could not load image!" << endl;
		return -1;
	}
	imshow("inputImage", src);
	cvtColor(src, src_gray, CV_BGR2GRAY);
	blur(src_gray, src_gray, Size(3, 3), Point(-1, -1), BORDER_DEFAULT);
	namedWindow(output, CV_WINDOW_AUTOSIZE);
	createTrackbar("Size", output, &threshold_v, threshold_max, Contours_Callback);
	Contours_Callback(0, 0);

	waitKey(0);
	return 0;
}

void Contours_Callback(int, void*)
{
	Mat bin_image;
	vector<vector<Point>> contours;
	vector<Vec4i> hierarhy;
	threshold(src_gray, bin_image, threshold_v, threshold_max, THRESH_BINARY);
	findContours(bin_image, contours, hierarhy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(-1, -1));

	vector<vector<Point>> contours_poly(contours.size());   //外接多边形
	vector<Rect> ploy_rects(contours.size());  //多边形的外接矩形
	vector<Point2f> ccs(contours.size());  //圆心
	vector<float> radius(contours.size());  //圆的半径

	vector<RotatedRect> minRects(contours.size());
	vector<RotatedRect> myellipse(contours.size());

	for (size_t i = 0; i < contours.size(); i++)
	{
		approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true);  //输出结果放在contours_poly里
		ploy_rects[i]=boundingRect(contours_poly[i]);   //第i个外接矩形
		minEnclosingCircle(contours_poly[i], ccs[i], radius[i]);
		if (contours_poly[i].size() > 5)
		{
			myellipse[i] = fitEllipse(contours_poly[i]);
			minRects[i] = minAreaRect(contours_poly[i]);
		}
	}
	//绘制
	src.copyTo(dst);
	Point2f pts[4];
	for (size_t t = 0; t < contours.size(); t++)
	{
		Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
		//rectangle(dst, ploy_rects[t], color, 2, 8);
		//circle(dst, ccs[t], radius[t], color, 2, 8);

		ellipse(dst, myellipse[t], color, 2, 8);
		minRects[t].points(pts);
		for (int r = 0; r < 4; r++)
		{
			line(dst, pts[r], pts[(r+1) % 4], color, 2, 8);
		}
	}
	imshow("result", dst);

}

 

运行结果:

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chde2Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值