Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to work with ROI in OpenCV

📅 2014-May-09 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ opencv, roi ⬩ 📚 Archive

Many common image operations are performed using Region of Interest in OpenCV. A ROI allows us to operate on a rectangular subset of the image.

The typical series of steps to use ROI is: create a ROI on the image, perform the operation you want on this subregion of the image, reset back the ROI.

Remember that in OpenCV, the origin is the top-left corner of the image. And a ROI is specified using a CvRect structure.

To copy a cropped region of an image to another image:

IplImage* img; // Source image
IplImage* cropImg; // Destination cropped image
CvRect cropRect = cvRect(10, 12, 100, 300); // ROI in source image

cvSetImageROI(img, cropRect);
cvCopy(img, cropImg, NULL); // Copies only crop region
cvResetImageROI(img);

To set only a region of an image to a certain value:

IplImage* img;
CvRect setRect = cvRect(10, 12, 100, 300); // ROI in image

cvSetImageROI(img, setRect);
cvSet(img, cvScalar(255)); // Set region of image to 255
cvResetImageROI(img);

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧