简体   繁体   English

使用 opencv python 合并多个轮廓

[英]Merge multiple contour using opencv python

When I applied OpenCV findContours() function on this image , I found that it created two separate contours.当我在这张图片上应用 OpenCV findContours() function 时,我发现它创建了两个单独的轮廓。 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.最重要的部分是获得轮廓的连续形状。

最终目标

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:使用 findContours() function 我得到了如下所示的轮廓:

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

查找轮廓

Step two (merge contours):第二步(合并轮廓):

Then I tried to merge the two contours using np.vstack() function and draw it on the image.然后我尝试使用 np.vstack() function 合并两个轮廓并将其绘制在图像上。 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:使用此代码,我得到了如图所示的轮廓:

轮廓组合

Step three (Us of OpenCV convexHull):第三步(OpenCV 凸包的使用):

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:我得到了下面的图片:

凸包

I have used cv2.morphologyEx() but unfortunately, that also did not help me to achieve my goal (check the image below).我使用了 cv2.morphologyEx() 但不幸的是,这也没有帮助我实现我的目标(查看下图)。

形态学

How do I get a single contour shown in the first image?如何获得第一张图片中显示的单个轮廓?

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.现在,当您确定船体和轮廓中的四个端点时,只需连接相关部分。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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