findContours function in C++ not giving same number as Python

asked 2019-07-25 21:00:23 -0500

I am trying to get contours for an image using OpenCV4 and C++. I have defined the contours as vector of vector of points. When I use the function it is only giving me one set of contours.

vector<vector<cv::Point> > contours;
vector<cv::Vec4i> hierarchy;

findContours(border_image, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);

cout<<"Size of contours -->"<< contours.size()<<endl;

border_image --> cv::Mat and has each pixel as CV_8UC1

Above code is returning size(length of vector of vector of points) as 1.

If I do the same in Python, I am getting the required number of contours. What am I doing wrong?

Python Version:

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

Above returns contours of length 112 thresh above is same image as border_image above in C++.

Expected contours(Vector of Vector of Points) of length 112. I only got contours of length 1 which is nothing but first element(Vector of Points) in result obtained by Python.

What am I doing wrong? Someone help me out.

edit retag flag offensive close merge delete



what is value of contours[0].size() ?

LBerger gravatar imageLBerger ( 2019-07-26 03:21:26 -0500 )edit

The size it returns is 4 and when I print it out it is the same as contours[0] returned by Python. Thanks for responding.

rkandury gravatar imagerkandury ( 2019-07-26 05:11:13 -0500 )edit

Also, I realized that my image is a binary image is a with white background. Is there any requirement that the background is black.

The contour I received from C++ is basically 4 points all of them being the 4 coordinates of the corners of input image.

rkandury gravatar imagerkandury ( 2019-07-26 05:28:08 -0500 )edit

@rkandury. It iis not contour problem. You had something on threshold or canny or blur, etc

supra56 gravatar imagesupra56 ( 2019-07-26 06:35:12 -0500 )edit