- 連通域反選
在使用Opencv的findcontours函數尋找連通域輪廓時,可能需要使用到類似PS中的選區反選功能。
以下對這一部分進行說明:
在findcontours函數中的mode參數中選擇CV_RETR_CCOMP兩級輪廓查找,
構建反選的選區范圍為讀入圖像大小:
vector<cv::Point> boundcontours(4); boundcontours[0] = cv::Point(0, 0); boundcontours[1] = cv::Point(0, src.rows-1); boundcontours[2] = cv::Point(src.cols-1, src.rows-1); boundcontours[3] = cv::Point(src.cols-1, 0);
int main() { cv::Mat src = imread("原圖.png", 0); vector<vector<cv::Point>>linecontours; vector<cv::Vec4i>hierarchy; findContours(src, linecontours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
//范圍限定 linecontours[0].clear(); vector<cv::Point> boundcontours(4); boundcontours[0] = cv::Point(0, 0); boundcontours[1] = cv::Point(0, src.rows-1); boundcontours[2] = cv::Point(src.cols-1, src.rows-1); boundcontours[3] = cv::Point(src.cols-1, 0); linecontours[0] = boundcontours;
//重繪選區 cv::Mat temptImg(scr.size(),CV_8UC1,Scalar(0)); drawContours(temptImg, linecontours, -1, Scalar(196), -1);//填充反向選區 }
原圖:
結果如下:
這種選取方式可以用來排除感興趣連通域外部的干擾。