I am trying to make a program that will identify a pattern by sliding a ROI over an image and comparing the ROI with a template, it will compare pixel values of the ROI and
It means you're trying to get the ROI region out of the image plane. You should make sure the ROI area to be within the image plane in order to avoid the crash.
For your case, you can do like this:
// check the box within the image plane
if (0 <= box.x
&& 0 <= box.width
&& box.x + box.width <= iOrig.cols
&& 0 <= box.y
&& 0 <= box.height
&& box.y + box.height <= iOrig.rows){
// box within the image plane
Mat region(iOrig, box);
}
else{
// box out of image plane, do something...
}