Amit
Amit

Reputation: 51

Merge multiple contour using opencv python

When I applied OpenCV findContours() function on this image, I found that it created two separate contours. I am trying to merge these two contours to form a single contour. My final goal is as follows:

Please ignore the dots. I have created it with annotation tools. The final contour might be slightly different from the given image but somewhat similar to this image. The most important part is to get a continuous shape of the contour.

Final goal

I am summarizing my work below with some code and images.

Step one (Finding contours):

Using the findContours() function I got the contours as shown below:

contour = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, [contour], -1, (0,0,255), 2)

findContours

Step two (merge contours):

Then I tried to merge the two contours using np.vstack() function and draw it on the image. Basically, I have stacked the two contour coordinates into one.

contours_combined = np.vstack(contour)
cv2.drawContours(img, [contours_combined], -1, (0,0,255), 2)

Using this code I got the contour as shown in the image:

contours combined

Step three (Us of OpenCV convexHull):

Then I created convex hull using the stacked contours.

hull = cv2.convexHull(contours_combined)
cv2.polylines(img, [hull], True, (0,0,255), 2)

I got the image below:

convexHull

I have used cv2.morphologyEx() but unfortunately, that also did not help me to achieve my goal (check the image below).

morphology

How do I get a single contour shown in the first image?

Upvotes: 0

Views: 1961

Answers (1)

user1196549
user1196549

Reputation:

There is a way to achieve that in your particular case: if you compare the individual outlines and the global convex hull, there are exactly two segments that link a vertex from one outline to a vertex of the other.

So the trick is to follow the convex hull, and for every vertex check which outline it belongs to (the convex hull is defined by a subset of the union of the set of vertices). This can be done efficiently.

Now when you have identified the four endpoints in the hull and in the outlines, just concatenate the relevant pieces.

enter image description here

Upvotes: 0

Related Questions