OpenCV裁剪图像任意区域

  • Post author:
  • Post category:其他




1、获取选定图中的矩形ROI

利用矩形 Rect 框定,指定其左上角坐标(构造函数前两个参数)和矩形的 长宽(后两个参数)

//定义一个 Mat 类型并设定 ROI 区域
Mat imageROI;
imageROI = srcImage(Rect(200,250,logoImage.cols,logoImage.rows));



2、裁剪任意多边形


给出区域轮廓点集,通过drawContours函数填充区域,生成mask图像,与原图相与


代码如下:

#include<iostream>
#include<opencv2\opencv.hpp>
using namespace std;
using namespace cv;

int main()
{
    Mat src = imread("F:/testdata/input.png");
    Mat mask = Mat::zeros(src.size(), CV_8UC1);
    Mat dst;
    vector<vector<Point2i>> contours;
    vector<Point2i> points;
    points.push_back(Point2i(100, 100));
    points.push_back(Point2i(50, 150));
    points.push_back(Point2i(100, 200));
    points.push_back(Point2i(200, 200));
    points.push_back(Point2i(220, 150));
    points.push_back(Point2i(200, 100));
    contours.push_back(points);
    drawContours(mask, contours, 0, Scalar::all(255), -1);
    imshow("src", src);
    //作用是把mask和src重叠以后把mask中像素值为0(black)的点对应的src中的点变为透明,而保留其他点。
    src.copyTo(dst, mask);
    imshow("dst", dst);
    waitKey(0);
    return 0;
}

在这里插入图片描述
在这里插入图片描述

参考:

OpenCV裁剪图像任意区域

.