OpenCV截取ROI区域——多种形状 1 /* cut off each piece */2 Rect piece_ROI(Point(center.x-piece_roi_size/2,

语言:C++(

Opencv版本:Opencv3.4.1

1、截取矩形的ROI:

/* cut off each piece */
Rect piece_ROI(Point(center.x-piece_roi_size/2,center.y-piece_roi_size/2),Point(center.x+piece_roi_size/2,center.y+piece_roi_size/2));
Mat piece_cutoff = piece_image(piece_ROI);

2、截取圆形的ROI:

这里涉及到截取一个不是矩形的区域,不管是截取一个圆形、椭圆,或者是截取一个不规则多边形,其方法都是使用contour(轮廓)来指定ROI。

  比如,要截取一个多边形的ROI区域:

    Mat dst;
    Mat roi = Mat::zeros(img.size(),CV_8U);

    vector> contour;
    vector pts;
    pts.push_back(Point(30,45));
    pts.push_back(Point(100,15));
    pts.push_back(Point(300,145));
    pts.push_back(Point(330,240));
    pts.push_back(Point(50,250));
    contour.push_back(pts);

    drawContours(roi,contour,0,Scalar::all(255),-1);
    img.copyTo(dst,roi);

    imshow("roi",roi);
    imshow("img",img);
    imshow("dst",dst);

如果要截取一个圆形区域,方法相似:

    Mat dst = Mat::zeros(image.size(), image.type());
    Mat mask = Mat::zeros(image.size(),CV_8U);

    Point circleCenter(mask.cols / 2, mask.rows / 2);
    int radius = min(mask.cols, mask.rows)/2;
    // 画圆
    circle(mask, circleCenter, radius, Scalar(255),-1);

    image.copyTo(dst, mask);

如果要截取一个椭圆呢?也是一样的方法:

 ellipse(mask,circleCenter,Size(240,146),10,-180,180,Scalar(255),-1);

你可能感兴趣的:(OpenCV截取ROI区域——多种形状 1 /* cut off each piece */2 Rect piece_ROI(Point(center.x-piece_roi_size/2,)