繁体   English   中英

检查cvRect是否在cvMat中

[英]Check if cvRect is within cvMat

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

在此处输入图片说明

因此,我认为我将对每个边界框进行一些扩展以弥补这种不准确性。

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

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

就像错误所言,您的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()); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM