如何通过绘制边界框(或多边形)从图像中裁剪多个对象?

时间:2016-04-21 13:36:16

标签: image opencv mouseevent image-segmentation

如何使用OpenCV使用鼠标绘制绑定框,从图像中裁剪多个对象。请参阅下图:

enter image description here

我想用鼠标点击选择焦炭罐边界并裁剪它们。

需要解决方案来绘制多个多边形来选择对象:

我能够绘制单个多边形而不是多个。这是代码:

void mouseHandler(int event,int x,int y,int,void *) {

 int[] imageId = {
        R.drawable.image1,
        R.drawable.image2,
        R.drawable.image3,
        R.drawable.image4,
        R.drawable.image5,
        R.drawable.image6,
        R.drawable.image7

}

int main() {

if (event == EVENT_LBUTTONDOWN && !drag)
{
    if (flag1 == 0)
    {
        if (var == 0)
            img1 = img0.clone();
        point = Point(x, y);
        circle(img1, point, 2, Scalar(0, 0, 255), -1, 8, 0);
        pts[var] = point;
        var++;
        drag = 1;
        if (var>1)
            line(img1, pts[var - 2], point, Scalar(0, 0, 255), 2, 8, 0);

        imshow("Source", img1);
    }
}

if (event == EVENT_LBUTTONUP && drag)
{
    imshow("Source", img1);

    drag = 0;
}
if (event == EVENT_RBUTTONDOWN)
{
    flag1 = 1;
    img1 = img0.clone();
    for (int i = var; i < numpts; i++)
        pts[i] = point;

    if (var != 0)
    {
        const Point* pts3[1] = { &pts[0] };
        polylines(img1, pts3, &numpts, 1, 1, Scalar(0, 0, 0), 2, 8, 0);
    }

    for (int i = 0; i<var; i++)
    {
        minx = min(minx, pts[i].x);
        maxx = max(maxx, pts[i].x);
        miny = min(miny, pts[i].y);
        maxy = max(maxy, pts[i].y);
    }
    lenx = maxx - minx;
    leny = maxy - miny;

    imshow("Source", img1);
}

if (event == EVENT_RBUTTONUP)
{
    flag = var;

    final = Mat::zeros(img0.size(), CV_8UC3);
    res1 = Mat::zeros(img0.size(), CV_8UC1);
    const Point* pts4[1] = { &pts[0] };

    fillPoly(res1, pts4, &numpts, 1, Scalar(255, 255, 255), 8, 0);
    bitwise_and(img0, img0, final, res1);
    imshow("mask", res1);
    imwrite("mask.png", res1);

    imshow("Source", img1);



}
if (event == EVENT_MBUTTONDOWN)
{
    for (int i = 0; i < numpts; i++)
    {
        pts[i].x = 0;
        pts[i].y = 0;
    }
    var = 0;
    flag1 = 0;
    minx = INT_MAX; miny = INT_MAX; maxx = INT_MIN; maxy = INT_MIN;
    imshow("Source", img0);
    drag = 0;
}

}

1 个答案:

答案 0 :(得分:1)

如果您只想绘制矩形,可以参考this answer中的代码。

如果您需要绘制多边形,请查看下面的代码。您可以使用鼠标左键单击绘制多边形顶点。左键双击将关闭多边形,然后开始一个新的多边形。

请注意,添加删除顶点的选项可能会有所帮助,例如删除最靠近鼠标右键的顶点。

底部将向您展示如何保存裁剪的图像。

代码:

$(document).on('click','input.chk',function(){
    // getting the tds with in the rows in which check exists 
    $tds=$(this).parent().siblings();

    if($(this).is(':checked'))
    {
      $data=$($tds[$tds.length-1]).text();
      alert($data);
    }

  })