0

I want to check if there is any part overlapping between two CvRect * variables . Are there inbuilt opencv functions to do this check . I am writing in the c version of opencv .

Bhushanam Bhargav
  • 301
  • 1
  • 4
  • 10
  • http://stackoverflow.com/questions/115426/algorithm-to-detect-intersection-of-two-rectangles look here for algorithm – Ann Orlova Jul 02 '13 at 05:56

1 Answers1

3

OpenCV does not have a C API for this. The C++ way is simply r1 & r2. The OpenCV source for &= is

template<typename _Tp> static inline Rect_<_Tp>& operator &= ( Rect_<_Tp>& a, const Rect_<_Tp>& b )
{
    _Tp x1 = std::max(a.x, b.x), y1 = std::max(a.y, b.y);
    a.width = std::min(a.x + a.width, b.x + b.width) - x1;
    a.height = std::min(a.y + a.height, b.y + b.height) - y1;
    a.x = x1; a.y = y1;
    if( a.width <= 0 || a.height <= 0 )
        a = Rect();
    return a;
}

So you just need to translate it to C:

CvRect rect_intersect(CvRect a, CvRect b) 
{ 
    CvRect r; 
    r.x = (a.x > b.x) ? a.x : b.x;
    r.y = (a.y > b.y) ? a.y : b.y;
    r.width = (a.x + a.width < b.x + b.width) ? 
        a.x + a.width - r.x : b.x + b.width - r.x; 
    r.height = (a.y + a.height < b.y + b.height) ? 
        a.y + a.height - r.y : b.y + b.height - r.y; 
    if(r.width <= 0 || r.height <= 0) 
        r = cvRect(0, 0, 0, 0); 

    return r; 
}
Bull
  • 11,771
  • 9
  • 42
  • 53