简体   繁体   中英

OpenCV findContours of points vector

I've got a vector of 2D points and I need to find all the contours formed by these points. Unfortunately, cv::findContours can't handle an array of points, it requires a binary image.

So the question is there any workaround to get contours of points? Maybe it is possible to form a binary image using the points and then use this image in cv::findContours function? Please advise here.

If you know the size of image, you can create a binary image of zeros and fill all the 2D points with value 255. Then use cv::findContours to find all the contours in binary image.

Following code snippet may help you:

// If pts is your array of float points and r,c are number of rows and columns of image
//calculate total number of points in array
int n = sizeof(pts) / sizeof(*pts);
//if points are stored in vector, then use n = pts.size()
//create binary image
cv::Mat image = cv::Mat::zeros(Size(c, r), CV_8UC1);
//fill all the points with value 255
for (int i = 0; i < n; i++) {
    image.at<uchar>(p[i]) = 255;
}
//find all contours in binary image and save in contours variale
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(image, contours, hierarchy, RETR_LIST, CHAIN_APPROX_NONE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM