最近在用opencv寫一個文本定位的程序,獲取到字符輪廓之後需要進行合並,涉及到判斷矩形是否相交的問題,記得去年去三星通信研究院面試同樣問到了這個問題,如何判斷兩條線段是否相交,如何判斷兩個矩形是否相交。以前寫過一篇如何判斷線段相交的問題,上網查了一些方法,在這裡做一下後一個問題的總結:
方法一:假定矩形是用一對點表達的(minx,miny)(maxx, maxy) ,那麼兩個矩形rect1{(minx1,miny1)(maxx1, maxy1)}, rect2{(minx2,miny2)(maxx2, maxy2)} 相交的結果一定是個矩形,構成這個相交矩形rect{(minx,miny)(maxx, maxy)}的點對坐標是:
- <pre name="code" class="cpp">bool CPreprocess::crossAlgorithm1(CvRect r1,CvRect r2)
- {
- int nMaxLeft = 0;
- int nMaxTop = 0;
- int nMinRight = 0;
- int nMinBottom = 0;
- //計算兩矩形可能的相交矩形的邊界
- nMaxLeft = r1.x >= r2.x ? r1.x : r2.x;
- nMaxTop = r1.y >= r2.y ? r1.y : r2.y;
- nMinRight = (r1.x + r1.width) <= (r2.x + r2.width) ? (r1.x + r1.width) : (r2.x + r2.width);
- nMinBottom = (r1.y + r1.height) <= (r2.y + r2.height) ? (r1.y + r1.height) : (r2.y + r2.height);
- // 判斷是否相交
- if (nMaxLeft > nMinRight || nMaxTop > nMinBottom)
- {
- return false;
- }
- else
- {
- return true;
- }
- }</pre>
- <pre></pre>
- //判斷兩個矩形是否相交
- bool CPreprocess::crossAlgorithm2(CvRect r1,CvRect r2)
- {
- //判斷兩個矩形是否相交,
- //從一個矩形中取出一條橫線,與另一矩形中的一條豎線判斷是否交叉
- return crossLine(r1.x, r1.x + r1.width, r1.y, r2.y, r2.y + r2.height, r2.x)
- || crossLine(r1.x, r1.x + r1.width, r1.y, r2.y, r2.y + r2.height, r2.x + r2.width)
- || crossLine(r1.x, r1.x + r1.width, r1.y + r1.height, r2.y, r2.y + r2.height, r2.x)
- || crossLine(r1.x, r1.x + r1.width, r1.y + r1.height, r2.y, r2.y + r2.height, r2.x r2.width)
- || crossLine(r2.x, r2.x + r2.width, r2.y, r1.y, r1.y + r1.height, r1.x)
- || crossLine(r2.x, r2.x + r2.width, r2.y, r1.y, r1.y + r1.height, r1.x + r1.width)
- || crossLine(r2.x, r2.x + r2.width, r2.y + r2.height, r1.y, r1.y + r1.height, r1.x)
- || crossLine(r2.x, r2.x + r2.width, r2.y r2.height, r1.y + r1.height, r1.y + r1.height, r1.x r1.width);
- }
- //判斷直線是否相交
- bool CPreprocess::crossLine(int left,int right,int x,int top,int bottom,int y)
- {
- return (top < y) && (bottom > y) && (left < x) && (right > x);
- }
方法三:
朋友面试的时候碰到这样的问题.
方法四:
第二种方法
两个矩形相交的条件:两个矩形的重心距离在X和Y轴上都小于两个矩形长或宽的一半之和.这样,分两次判断一下就行了.
bool CrossLine(Rect r1,RECT r2)
{
if(abs((r1.x1+r1.x2)/2-(r2.x1+r2.x2)/2)<((r1.x2+r2.x2-r1.x1-r2.x1)/2) && abs((r1.y1+r1.y2)/2-(r2.y1+r2.y2)/2)<((r1.y2+r2.y2-r1.y1-r2.y1)/2))
return true;
return false;
}