Valentin Heinitz Valentin Heinitz - 1 month ago 23
C++ Question

How to verify if rect is inside cv::Mat in OpenCV?

Is there anything like

cv::Mat::contains(cv::Rect)
in Opencv?

Background:
After detecting objects as contours and trying to access ROIs by using cv::boundingRect my application crashed. OK, that's because the bounding rects of the object close to image border may be not entirely within the image.

Now I skip the objects not entirely in image by this check:

if(
cellRect.x>0 &&
cellRect.y>0 &&
cellRect.x + cellRect.width < m.cols &&
cellRect.x + cellRect.width < m.rows) ...


where cellRect is the bounding rect of the object and m is the image.
I hope there is a dedicated opencv function for this.

Answer

Simple way is to use the AND (i.e. &) operator.

Assume you want to check if cv::Rect rect is inside cv::Mat mat:

bool is_inside = (rect & cv::Rect(0, 0, mat.cols, mat.rows)) == rect;