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());