單張圖根據座標提取多個mask

三個矩形區域,已經設置有座標,提取後背景黑色,mask區域白色,且三個mask都在最後的final.png內。

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <vector>

using namespace std;
using namespace cv;

int main()
{
  cv::Mat img = imread("filename.png");
  cv::Mat dst1;
  cv::Mat dst2;
  cv::Mat dst3;
  cv::Mat tmp;
  cv::Mat final;

  cv::Mat roi1 = Mat::zeros(img.size(), CV_8U);
  cv::Mat roi2 = Mat::zeros(img.size(), CV_8U);
  cv::Mat roi3 = Mat::zeros(img.size(), CV_8U);

  vector<vector<cv::Point>> contour;
  vector<cv::Point> pts;
  
  pts.push_back(Point(193, 277));
  pts.push_back(Point(283, 246));
  pts.push_back(Point(189, 445));
  pts.push_back(Point(126, 423));  
  
  contour.push_back(pts);
  cv::drawContours(roi1, contour, 0, Scalar::all(255), -1);

  img.copyTo(dst1, roi1);

  cv::imwrite("roi1.png", roi1);
  cv::imwrite("dst1.png", dst1);
  
  pts.clear();
  contour.clear();
  pts.push_back(Point(450, 201));
  pts.push_back(Point(651, 204));
  pts.push_back(Point(642, 474));
  pts.push_back(Point(342, 463));
  contour.push_back(pts);
  cv::drawContours(roi2, contour, 0, Scalar::all(255), -1);

  img.copyTo(dst2, roi2);

  cv::add(roi1, roi2, tmp);

  cv::imwrite("roi2.png", roi2);
  cv::imwrite("dst2.png", dst2);
  cv::imwrite("final.png", tmp);
  pts.clear();
  contour.clear();
  pts.push_back(Point(898, 222));
  pts.push_back(Point(1047, 270));
  pts.push_back(Point(1119, 447));
  pts.push_back(Point(1000, 466));
  contour.push_back(pts);
  cv::drawContours(roi3, contour, 0, Scalar::all(255), -1);

  img.copyTo(dst3, roi3);

  cv::add(tmp, roi3, final);
  cv::imwrite("roi3.png", roi3);
  cv::imwrite("dst3.png", dst3);
  cv::imwrite("final.png", final);

  //waitKey();
  return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章