I'm using OpenCV to get a small rectangular ROI from a large image and save the ROI to a file. Sometimes, the ROI goes out of bounds of the image. I need a way to make the resulting Mat show the portion of the large image that is within bounds, and show black for the rest.
To help explain, image that you have an image that is a map of an area. I know where a person is on the map, and want to take a 500x500 pixel section of the map with their location in the center. But when the user gets to the edge of the map, part of this 500x500 section will need to be "off the map". So I would like it to fill it in with black.
Preferably, OpenCV would be able to gracefully handle out-of-bounds ROIs (e.g. negative top left corner values) by filling in with black (like it does when you rotate an image with warpAffine
) but that doesn't seem to be the case. Any suggestions for how to accomplish this goal?
All other answers seem a little bit too complicated to me. Simply:
// Create rects representing the image and the ROI
auto image_rect = cv::Rect({}, image.size());
auto roi = cv::Rect(-50, 50, 200, 100)
// Find intersection, i.e. valid crop region
auto intersection = image_rect & roi;
// Move intersection to the result coordinate space
auto inter_roi = intersection - roi.tl();
// Create black image and copy intersection
cv::Mat crop = cv::Mat::zeros(roi.size(), image.type());
image(intersection).copyTo(crop(inter_roi));
Image for reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With