Question

I am using bounding boxes to find text in an image and sometimes the boxes are just slightly too small and cut off parts of text on the top and bottom.

enter image description here

So I thought I'd extend every bounding box just a little to compensate for the inaccuracy.

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

appRect being a cv::Rect

This does what I am looking for however it seems that sometimes it takes the bounding box out of bounds.

Giving me this error:

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

How can I check that the rect is within the boundaries of the image and avoid this error while still expanding the bounding boxes?

Was it helpful?

Solution

Like the error says, your x, y, w and h are not allowed to be negative.

Try to add a std::max() and 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);

Or as Iwillnotexist smartly suggested:

// 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()); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top