opencv 轮廓包围,剔除中间重叠的轮廓

#include <iostream>    
#include <opencv2\opencv.hpp>    
#include <opencv2\highgui\highgui.hpp>      
#include <fstream> 
#include <stdio.h> 
#include <string.h> 

using namespace cv;
using namespace std;

// 轮廓包围
void SetRect(vector<vector<Point> > contours, vector<Rect>& boundRect)
{
	// 多边形逼近轮廓 + 获取矩形和圆形边界框
	vector<vector<Point> > contours_poly(contours.size());
	//一个循环,遍历所有部分,进行本程序最核心的操作
	for (unsigned int i = 0; i < contours.size(); i++)
	{
		approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true);//用指定精度逼近多边形曲线 
		boundRect[i] = boundingRect(Mat(contours_poly[i]));//计算点集的最外面(up-right)矩形边界
	}
}

// 去重叠
vector<Rect> DeleteOverlap(vector<Rect> inRect)
{
	vector<Rect> rec1 = inRect;
	for (size_t i = 0; i < rec1.size();i++)
	{
		vector<Rect> rec2 = rec1;
		for (size_t j = i + 1; j < rec2.size(); j++)
		{
		    // 2在1里面
			if ((rec2[j].x >= rec1[i].x)&& (rec2[j].x + rec2[j].width <= rec1[i].x + rec1[i].width)) {
				if ((rec2[j].y >= rec1[i].y) && (rec2[j].y + rec2[j].height <= rec1[i].y + rec1[i].height)) {
					rec1.erase(rec1.begin() + j); // 删除j
					i--;
					break;
				}
			}

			// 1在2里面
			if ((rec1[i].x >= rec2[j].x) && (rec1[i].x + rec1[i].width <= rec2[j].x + rec2[j].width)) {
				if ((rec1[i].y >= rec2[j].y) && (rec1[i].y + rec1[i].height <= rec2[j].y + rec2[j].height)) {
					rec1.erase(rec1.begin() + i); // 删除i
					i--;
					break;
				}
			}
		}
	}
	return rec1;
}

int main()
{
	Mat srcImage = imread("./avi/2.jpg");
	Mat desImage;
	cvtColor(srcImage, desImage, CV_RGB2GRAY);
	threshold(desImage, desImage, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

	vector<Vec4i> hierarchy;
	vector<vector<Point> > contours;
	findContours(desImage, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
	if (hierarchy.size())
	{
		vector<Rect> boundRect(hierarchy.size());
		SetRect(contours, boundRect);
		vector<Rect> Rects = DeleteOverlap(boundRect);

		Mat a = srcImage.clone();
		for (size_t i = 0; i < boundRect.size(); i++) {
			rectangle(a, boundRect[i], Scalar(0, 255, 0), 2);
		}
		imshow("剔除前", a);

		Mat b = srcImage.clone();
		for (size_t i = 0; i < Rects.size(); i++) {
			rectangle(b, Rects[i], Scalar(0, 0, 255), 2);
		}
		imshow("剔除后", b);
	}
	
	waitKey(0);
	return 0;
}

 

测试效果如下:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值