检查cvRect是否在cvMat中

时间:2014-05-11 23:50:28

标签: c++ opencv bounding-box

我正在使用边界框来查找图像中的文本,有时框太小而且切掉了顶部和底部的文本部分。

enter image description here

所以我想我会扩展每个边界框以弥补不准确性。

double Z = 10;
cv::Rect extended( appRect.x-Z, appRect.y-Z, appRect.width+2*Z, appRect.height+2*Z);

appRectcv::Rect

这就是我正在寻找的东西,但似乎有时它会使边界框超出范围。

给我这个错误:

OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in Mat

如何检查矩形是否在图像的边界内,并在扩展边界框时避免此错误?

1 个答案:

答案 0 :(得分:4)

如错误所示,您的xywh不允许为否定。

尝试添加std::max()std::min()

#include <algorithm> // std::max && std::min

int Z = 10;
int x = std::max<int>(0, appRect.x-Z);
int y = std::max<int>(0, appRect.y-Z);
int w = std::min<int>(mat.cols - x, appRect.width+2*Z);
int h = std::min<int>(mat.rows - y, appRect.height+2*Z);
cv::Rect extended(x, y, w, h);

Iwillnotexist聪明地建议:

// expand
double Z = 10;
cv::Rect extended( appRect.x-Z, appRect.y-Z, appRect.width+2*Z, appRect.height+2*Z);

// intersect
extended &= Rect(Point(0, 0), mat.size()); 
相关问题