我正在使用边界框来查找图像中的文本,但有时边界框会稍微太小,并且会切断顶部和底部的部分文本。
所以我想我会稍微扩展每个边界框以补偿不准确。
double Z = 10;
cv::Rect extended( appRect.x-Z, appRect.y-Z, appRect.width+2*Z, appRect.height+2*Z);
appRect
是一个 cv::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
如何在扩展边界框的同时检查矩形是否在图像边界内并避免此错误?
最佳答案
如错误所述,您的 x
、y
、w
和 h
不允许为负数.
尝试添加一个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());
关于c++ - 检查 cvRect 是否在 cvMat 内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23599169/