[英]How to verify if rect is inside cv::Mat in OpenCV?
Is there anything like cv::Mat::contains(cv::Rect)
in Opencv? cv::Mat::contains(cv::Rect)
是否有类似cv::Mat::contains(cv::Rect)
的东西?
Background: After detecting objects as contours and trying to access ROIs by using cv::boundingRect my application crashed. 背景:在将对象检测为轮廓并尝试使用cv :: boundingRect访问ROI之后,我的应用程序崩溃了。 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. 其中cellRect是对象的边界矩形, m是图像。 I hope there is a dedicated opencv function for this. 我希望有一个专用的opencv函数。
Simple way is to use the AND (ie &
) operator. 简单的方法是使用AND (即&
)运算符。
Assume you want to check if cv::Rect rect
is inside cv::Mat mat
: 假设您要检查cv::Rect rect
是否在cv::Mat mat
:
bool is_inside = (rect & cv::Rect(0, 0, mat.cols, mat.rows)) == rect;
You can create rect "representing"(x,y = 0, width and height equal to image width and height) your image and check whether it contains bounding rects of your contours. 您可以创建图像的“代表”矩形(x,y = 0,宽度和高度等于图像的宽度和高度),并检查其是否包含轮廓的边界矩形。 To achieve that you need to use rect intersection - in OpenCV it's very simple, just use rect1 & rect2
. 要实现您需要使用rect相交-在OpenCV中非常简单,只需使用rect1 & rect2
。 Hope that code makes it clear: 希望代码能清楚说明:
cv::Rect imgRect = cv::Rect(cv::Point(0,0), img.size());
cv::Rect objectBoundingRect = ....;
cv::Rect rectsIntersecion = imgRect & objectBoundingRect;
if (rectsIntersecion.area() == 0)
//object is completely outside image
else if (rectsIntersecion.area() == objectBoundingRect.area())
//whole object is inside image
else
//((double)rectsIntersecion.area())/((double)objectBoundingRect.area()) * 100.0 % of object is inside image
Here is a method to judge whether a rectangle contains an other rectangle. 这是一种判断一个矩形是否包含另一个矩形的方法。 you can get the size info from cv::Mat first
, and then use method below: 您可以先从cv::Mat first
获取大小信息,然后使用以下方法:
public bool rectContainsRect(Rectangle containerRect, Rectangle subRect)
{
if( containerRect.Contains(new Point(subRect.Left, subRect.Top))
&& containerRect.Contains(new Point(subRect.Right, subRect.Top))
&& containerRect.Contains(new Point(subRect.Left, subRect.Bottom))
&& containerRect.Contains(new Point(subRect.Right, subRect.Bottom)))
{
return true;
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.