在利用OpenCV对图像进行处理时,通常会遇到一个情况,就是只需要对部分感兴趣区域进行处理。
因此,如何选取感兴趣区域(其实就是“抠图”)。
下面给出一个例子:
Mat img = imread(IMG_PATH);
Mat cat = imread(CAT_PATH);
if (img.empty()|| cat.empty())
cerr << "can not read image."<<endl;
// 指定感兴趣区域,两种方法
Mat ROI = img(Rect(40,40,cat.cols,cat.rows));
Mat ROI2(img,Rect(40,40,cat.cols,cat.rows));
// 展示 roi 区域
imshow("roi",ROI);
cout<<endl
<<"将猫放到感兴趣区域,两种方法"<<endl;
//cat.copyTo(ROI);
cat.copyTo(ROI,cat);
imshow("lotus with cat",img);
// 在图像中画出 矩形
rectangle(img,Rect(240,240,cat.cols,cat.rows),Scalar(0,0,255));
imshow("with rectangle box",img);
// 另一种方法
cout <<endl
<< "利用 Rect 保存方框,然后使用"<<endl;
Rect r1 = Rect(100,0,200,200);
rectangle(img,r1,Scalar(255,0,0));
imshow("with rectangle box 2",img);
下面是程序最终的结果: