#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;
}
测试效果如下: