您的位置:首页 > 运维架构

OpenCV截取图像ROI,任意形状

2015-12-16 11:37 513 查看
//1.First create mask image as described above

//2.Copy the source image to new Mat dst1 using the mask

//3.Invert your mask and copy destination image to a new Mat dst2

//4.For final result just add up dest1 and dest2 to new Mat

Mat src = imread("src.jpg",1);

Mat dst = imread("dest.bmp",1);

int new_w = 0;

int new_h = 0;

if(src.cols >dst.cols)

new_w = dst.cols;

else

new_w = src.cols;

if(src.rows>dst.rows)

new_h=dst.rows;

else

new_h=src.rows;

Rect rectROI(0,0,new_w,new_h);

Mat mask(new_h, new_w, CV_8UC1, cv::Scalar(0));

Point P1(107,41);

Point P2(300,61);

Point P3(250,280);

Point P4(110,253);

vector< vector<Point> > co_ordinates;

co_ordinates.push_back(vector<Point>());

co_ordinates[0].push_back(P1);

co_ordinates[0].push_back(P2);

co_ordinates[0].push_back(P3);

co_ordinates[0].push_back(P4);

drawContours( mask,co_ordinates,0, Scalar(255),CV_FILLED, 8 );

Mat srcROI=src(rectROI);

Mat dstROI=dst(rectROI);

Mat dst1;

Mat dst2;

srcROI.copyTo(dst1,mask);

imwrite("dst1.jpg",dst1);

bitwise_not(mask,mask);

dstROI.copyTo(dst2,mask);

dstROI.setTo(0);

dstROI=dst1+dst2;

imshow("final result",dst);

result:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: