opencv 提取多边形mask区域

最近在项目中需要提取多边形区域,并传入到算子中计算,故记录一下对多边形mask区域的提取方法。

 

#include <opencv2\opencv.hpp>

using namespace cv;

int main()
{
    Mat src = imread(R"(E:\picture\picture_for_test\8.jpg)", 1);  // replace image path

    vector<vector<Point>> mask_area;
    vector<Point> mask_points;
    mask_points.push_back(Point(100, 200));
    mask_points.push_back(Point(500, 300));
    mask_points.push_back(Point(520, 460));
    mask_points.push_back(Point(300, 420));
    mask_points.push_back(Point(200, 330));
    mask_points.push_back(Point(100, 250));
    mask_area.push_back(mask_points);

    polylines(src, mask_area, 1, Scalar(0, 0, 0));
    imshow("resource", src);
    cv::Mat mask, dst;

    src.copyTo(mask);
    mask.setTo(cv::Scalar::all(0));
    fillPoly(mask, mask_area, Scalar(255, 255, 255));
    imshow("mask", mask);
    src.copyTo(dst, mask);
    imshow("dst", dst);

    waitKey();

    return 0;
}

 关键函数为:fillPoly,该函数提供两种调用接口,分别如下:

void fillPoly(Mat& img, const Point** pts,
                         const int* npts, int ncontours,
                         const Scalar& color, int lineType=8, int shift=0,
                         Point offset=Point() );

void fillPoly(InputOutputArray img, InputArrayOfArrays pts,
                           const Scalar& color, int lineType=8, int shift=0,
                           Point offset=Point() );

这里使用到第二种调用接口,其具体实现代码如下:

void cv::fillPoly(InputOutputArray img, InputArrayOfArrays pts,
                  const Scalar& color, int lineType, int shift, Point offset)
{
    CV_INSTRUMENT_REGION();

    int i, ncontours = (int)pts.total();
    if( ncontours == 0 )
        return;
    AutoBuffer<Point*> _ptsptr(ncontours);
    AutoBuffer<int> _npts(ncontours);
    Point** ptsptr = _ptsptr.data();
    int* npts = _npts.data();

    for( i = 0; i < ncontours; i++ )
    {
        Mat p = pts.getMat(i);
        CV_Assert(p.checkVector(2, CV_32S) >= 0);
        ptsptr[i] = p.ptr<Point>();
        npts[i] = p.rows*p.cols*p.channels()/2;
    }
    fillPoly(img, (const Point**)ptsptr, npts, (int)ncontours, color, lineType, shift, offset);
}

可见,最终还是调用第一个接口实现。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值