简体   繁体   English

如何在OpenCV / C ++中为Mat对象创建圆形蒙版?

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

My goal is to create a circular mask on a Mat object, so eg for a Mat looking like this: 我的目标是在Mat对象上创建一个圆形蒙版,例如对于看起来像这样的Mat

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 1 s within it, so .eg ...修改它,使得我在其中获得1秒的“圆形” ,所以.eg

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? 问题是,在我调用circlecircleROI 中最多只有一个字段设置为1 ...根据我的理解,此代码应该有效,因为circle应该使用有关centerradius的信息修改circleROI ,使得圆圈区域内的所有点都应该设置为1 ...有没有人对我有什么解释我做错了什么? 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)? 我是否采取了正确的方法解决问题,但实际问题可能在其他地方(这也是非常可能的,因为我是C ++和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. 请注意,我还尝试将circle调用中的最后一个参数(即圆形轮廓粗细 )修改为1-1 ,没有任何影响。

It is because you're filling your circleROI with a coordinate of the circle in the big mat. 这是因为你正在用大垫子中的圆圈坐标填充你的circleROI。 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. circleROI中的圆坐标应相对于circleROI,在您的情况下: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);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM