前一篇画出了最小外接矩形,但是有时候画出来的矩形由于中间像素干扰或者是其他原因矩形框并不是真正想要的
如图1是一个信号的雨图,被矩形框分割成了多个小框:
需要合并矩形框达到的效果:
主要思想:
扫描两次最小外接矩形,第一次扫描出的矩形是图一的小矩形,遍历vector指定一个合并最大距离(假设是80),达到指定距离使用画矩形函数将这两个矩形占据的组合区域染成实心矩形。
第二次扫描直接扫描之前画的实心矩形图确定最终边框
过程图 膨胀处理和像素翻转:
代码:
#include "core/core.hpp" #include "highgui/highgui.hpp" #include "imgproc/imgproc.hpp" #include "iostream" #include "cmath" using namespace std; using namespace cv;int Distance(Rect rect1,Rect rect2) { // 用于判断rect1在rect2的第三象限里 用于反转X轴用 bool isInversion; // 保存两个比较的点 Point point1; Point point2; // 判断 rect1 在rect2的上面还是下面 也就是说是在第一、二象限还是在三四象限 if(rect1.y<rect2.y) { // 判断rect1 在rect2的左边还是右边 也就是说是在 一象限还是二象限 isInversion= rect1.x<rect2.x; if(isInversion ) { // 取rect1的右上点 point1 = Point(rect1.x+rect1.width,rect1.y+rect1.height); // 取rect2的左下点 point2 = Point(rect2.x,rect2.y); }else { // 取rect1的左上点 point1 = Point(rect1.x,rect1.y+rect1.height); // 取rect2的右下点 point2 = Point(rect2.x+rect2.width,rect2.y); } }else { // 判断rect1 在rect2的左边还是右边 也就是说是在 三象限还是四象限 isInversion = rect1.x>rect2.x; if(isInversion) { // 取rect2的右上点 point1 = Point(rect2.x+rect2.width,rect2.y+rect2.height); // 取rect1的左下点 point2 = Point(rect1.x,rect1.y); }else { // 取rect2的左上点 point1 = Point(rect2.x,rect2.y+rect2.height); // 取rect1的右下点