findContours边界的多种画法(一)

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
 
using namespace cv;
using namespace std;
 

RNG rng(12345);
 
 
int main( int argc, char** argv )
{
  Mat src = imread("D:\\1\\2.png");
  Mat result;
  cvtColor( src, result, COLOR_BGR2GRAY );
  blur(result, result, Size(3,3) );
 

  vector<vector<Point> > contours;
  vector<Vec4i> hierarchy;

 

  //阈值检测边界
  threshold(result, result, 100, 255, THRESH_BINARY);
  //查找轮廓
  findContours(result, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);

  //近似轮廓多边形,方形和圆圈
  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);
	  boundRect[i] = boundingRect(Mat(contours_poly[i]));
	  minEnclosingCircle(contours_poly[i], center[i], radius[i]);
  }


  //用方形和圆圈画多边形边界
  Mat drawing = Mat::zeros(result.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);
  }

 
  
  imwrite("D:\\1\\2a.png", drawing);

  return(0);
}

原图
结果图
说明:本程序是64位系统的,如果想用32位系统调试,直接修改里面的几句话即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

翱翔的小鸟2001

您的鼓励是我最大的动力!!!

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

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

打赏作者

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

抵扣说明:

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

余额充值