4

I have a question about how to define a ROI with OpenCV. I know what the definition of the function cvSetImageROI but I want to know if is possible to define a ROI with OpenCV with a different shape than rectangle. For example, define a ROI in a circle or in different form.

It is possible to do this?

cvSetImageROI(img1, cvRect(a, b, c, d));

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
edsonlp1
  • 453
  • 2
  • 9
  • 22

2 Answers2

3

The following code, which you could have found here or even here sets a circular ROI using a bit mask on your image.

#include "cv.h"
#include "highgui.h"

int main(int argc, char** argv)
{
    IplImage* src, * res, * roi;

    /* usage: <prog_name> <image> */
    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s <image>\n", argv[0]);
        return 1;
    }

    src = cvLoadImage(argv[1], 1);
    res = cvCreateImage(cvGetSize(src), 8, 3);
    roi = cvCreateImage(cvGetSize(src), 8, 1);

    /* prepare the 'ROI' image */
    cvZero(roi);

    /* Note that you can use any shape for the ROI */
    cvCircle(
        roi,
        cvPoint(130, 100),
        50,
        CV_RGB(255, 255, 255),
        -1, 8, 0
    );

    /* extract subimage */
    cvAnd(src, src, res, roi);

    /*
     * do the main processing with subimage here.
     * in this example, we simply invert the subimage
     */
    cvNot(res, res);

    /* 'restore' subimage */
    IplImage* roi_C3 = cvCreateImage(cvGetSize(src), 8, 3);
    cvMerge(roi, roi, roi, NULL, roi_C3);
    cvAnd(res, roi_C3, res, NULL);

    /* merge subimage with original image */
    cvNot(roi, roi);
    cvAdd(src, res, res, roi);

    /* show result */
    cvNamedWindow(argv[1], 1);
    cvNamedWindow("res", 1);
    cvShowImage(argv[1], src);
    cvShowImage("res", res);

    cvWaitKey(0);

    /* be tidy */
    cvDestroyAllWindows();
    cvReleaseImage(&src);
    cvReleaseImage(&res);
    cvReleaseImage(&roi);

    return 0;
}

For a pentagon or hexagon just adapt it so to change the geometric shape of the mask. Check this SO Question: Using ROI in OpenCV?.

Community
  • 1
  • 1
Matteo
  • 7,924
  • 24
  • 84
  • 129
1

You are supposed to use masks to simulate non-rectangular ROI.

Andrey Kamaev
  • 29,582
  • 6
  • 94
  • 88
  • Exactly. I want to define a different shape, like a pentagon or an hexagon. – edsonlp1 May 17 '12 at 08:33
  • Is there any possibility to use something similar to slicing but for irregular shapes? I'm asking this because the ROI created using masks and bitwise operations are more time consuming. For example, using `timeit` I got the following output `CROP TIMING: 11560.400000007576 us`, and `ROI TIMING: 780580.8000000524 us` using `10000` iterations for testing – Cătălina Sîrbu May 17 '20 at 11:21