c++ - 检查 cvRect 是否在 cvMat 内

标签 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);

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

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

最佳答案

如错误所述,您的 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()); 

关于c++ - 检查 cvRect 是否在 cvMat 内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23599169/

相关文章:

c++ - 计算力矩时 OpenCV 断言失败

ios - 查找 CGPath 与 CGRect 相交的区域

c++ - 输入操作

c++ - 关于CFile Seek的问题

c++ - 如何使用 QSqlQueryModel 在 QTableView 中显示多个选择的结果

java - Android 触摸边界矩形和纹理位置

wpf - 如何获取 PathFigureCollection 边界矩形

c++ - 声明一个具有四个键值的多重映射

c++ - 使用 CMake、CUDA 9.0 RC 和 Visual Studio 2017 安装带有 contrib 模块的 OpenCV 3.3.0

java - opencv Java构建中imshow的等效方法