nburk
nburk

Reputation: 22731

How to create circular mask for Mat object in OpenCV / C++?

My goal is to create a circular mask on a Mat object, so e.g. for a Mat looking like this:

0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

...modify it such that I obtain a "circular shape" of 1s within it, so .e.g.

0 0 0 0 0 
0 0 1 0 0 
0 1 1 1 0
0 0 1 0 0
0 0 0 0 0

I am currently using the following code:

typedef struct {
    double radius;
    Point center;
} Circle;

...

for (Circle c : circles) {

    // get the circle's bounding rect
    Rect boundingRect(c.center.x-c.radius, c.center.y-c.radius, c.radius*2,c.radius*2);

    // obtain the image ROI:
    Mat circleROI(stainMask_, boundingRect);
    int radius = floor(radius);
    circle(circleROI, c.center, radius, Scalar::all(1), 0);
}

The problem is that after my call to circle, there is at most only one field in the circleROI set to 1... According to my understanding, this code should work because circle is supposed to use the information about the center and the radius to modify circleROI such that all points that are within the area of the circle should be set to 1... does anyone have an explanation for me what I am doing wrong? Am I taking the right approach to the problem but the actual issue might be somewhere else (this is very much possible too, since I am a novice to C++ and OpenCv)?

Note that I also tried to modify the last parameter in the circle call (which is the thickness of the circle outline) to 1 and -1, without any effect.

Upvotes: 3

Views: 6530

Answers (2)

Ha Dang
Ha Dang

Reputation: 1238

It is because you're filling your circleROI with a coordinate of the circle in the big mat. Your circle coordinate inside the circleROI should be relative to the circleROI, which is, in your case: new_center = (c.radius, c.radius), new_radius = c.radius.

Here is a snipcode for the loop:

for (Circle c : circles) {

    // get the circle's bounding rect
    Rect boundingRect(c.center.x-c.radius, c.center.y-c.radius, c.radius*2+1,c.radius*2+1);

    // obtain the image ROI:
    Mat circleROI(stainMask_, boundingRect);

    //draw the circle
    circle(circleROI, Point(c.radius, c.radius), c.radius, Scalar::all(1), -1);

}

Upvotes: 5

Photon
Photon

Reputation: 3222

Take a look at: getStructuringElement

http://docs.opencv.org/modules/imgproc/doc/filtering.html

Upvotes: 2

Related Questions