Web Analytics Made
Easy - StatCounter

OpenCV's Rect as a ROI: returns a pointer.

result image from the code aboveI have been using OpenCV’s Rect class a lot this week and needed to really know what was going on with it. I suspected that in the absence of explicitly forcing a clone, that using the Rect to get an image’s region of interest (ROI for the rest of this post), you would only get a pointer to that image data. And, yep – it is only a pointer. Which is really cool, and allows me to do some neat things. I’m working in C++. The internals of OpenCV are implemented differently in C++ than Python, FYI.

In the MWE below, I created an image that is solid blue, extracted some ROIs, set them to different colors, then added them together, and then wrote the ROIs and the result image. The result image is this blue image with the red, green, yellow, and white bars to the right.

So beyond this little toy example, you can do processing on patches, and then you don’t need to copy them back into a larger image. You’re working with a pointer to that data anyway if you’ve extracted it using a Rect.


A MWE illustrating how to use a Rect and ROIs, and what the output is.

    // includes and using namespace cv;

    // src image is blue
    Mat srcImage(Size(480, 640), CV_8UC3, Scalar(255, 0, 0));

    string filename = "srcImageInitial.png";

    imwrite(filename.c_str(), srcImage);

    // x, y, width, height
    Rect R0(100,100, 50, 200);

    Mat roi0 = srcImage(R0);

    // change the roi's color;
    roi0.setTo(Scalar(0, 0, 255));

    // x, y, width, height
    Rect R1(300, 100, 50, 200);

    Mat roi1 = srcImage(R1);

    // change the roi's color;
    roi1.setTo(Scalar(0, 255, 0));

    // x, y, width, height
    Rect R2(200, 300, 50, 200);

    Mat roi2 = srcImage(R2);

    // x, y, width, height
    Rect R3(400, 300, 50, 200);

    Mat roi3 = srcImage(R3);

    // add the rois

    // roi0 + roi1 + roi2 = roi2;
    add(roi0, roi2, roi2);

    add(roi1, roi2, roi2);

    // roi0 + roi1 = roi3
    add(roi0, roi1, roi3);

    // write everything.
    filename = "srcImageFinal.png";

    imwrite(filename.c_str(), srcImage);

    filename = "roi0.png";

    imwrite(filename.c_str(), roi0);

    filename = "roi1.png";

    imwrite(filename.c_str(), roi1);

    filename = "roi2.png";

    imwrite(filename.c_str(), roi2);

    filename = "roi3.png";

    imwrite(filename.c_str(), roi3);

© Amy Tabb 2018 - 2021. All rights reserved. The contents of this site reflect my personal perspectives and not those of any other entity.