python - 在OpenCV中获取多个小轮廓的外部轮廓

标签 python opencv

所以我有以下由多个小块组成的图像,并希望获得其外部轮廓,如下所示:

enter image description here

enter image description here

之前,我同时使用了Contour逼近和Convex Hull函数来获取近似的外部轮廓,但是它们只是由1个单一轮廓组成,而在这种情况下,较小的部分确实很重要。

我以前使用的功能与此类似:

canvas = np.zeros(img.shape, np.uint8)

img2gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
kernel = np.ones((5,5),np.float32)/25
img2gray = cv2.filter2D(img2gray,-1,kernel)

ret,thresh = cv2.threshold(img2gray,120,255,cv2.THRESH_BINARY_INV)
im2,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

cnt = contours[0]
max_area = cv2.contourArea(cnt)

for cont in contours:
    if cv2.contourArea(cont) > max_area:
        cnt = cont
        max_area = cv2.contourArea(cont)

hull = cv2.convexHull(cnt)

cv2.drawContours(canvas, hull, -1, (0, 255, 0), 3)

如您所料,输出与所需的输出相差甚远:

enter image description here

关于如何使其更接近所需的任何想法?

最佳答案

正如@Amine所说,形态学运算将是必经之路,尤其是扩张。可以找到更多信息here。举了一个小例子,您可以微调,但我认为它非常接近所需的输出。

import cv2
import numpy as np

cv_img = cv2.imread('spot.jpg', 0)
im_copy = cv_img.copy()

kernel_dilation = np.ones((5,5), np.uint8)
dilation = cv2.dilate(cv_img, kernel_dilation, iterations=12)
ret, thresh = cv2.threshold(dilation, 127, 255, 0)

im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

cnt = contours[0]
max_area = cv2.contourArea(cnt)

for cont in contours:
    if cv2.contourArea(cont) > max_area:
        cnt = cont
        max_area = cv2.contourArea(cont)

cv2.drawContours(im_copy, [cnt], 0, (255, 255, 0), 3)
cv2.imshow('Contour', im_copy)
cv2.waitKey(0)

输出:
enter image description here

关于python - 在OpenCV中获取多个小轮廓的外部轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55385233/

相关文章:

Python 3 : Programmatically converting list of hex numbers to binary

python - Matplotlib - 添加与轴底部对齐的标签

Python看门狗应用程序

python - 为什么在这个简单的基准测试中 SQLite 比 Redis 快?

javascript - Bokeh 无法从 CDN 加载 Bokeh

c++ - cvSet2D 的有效替代方案?

python - 使用 Python 查找线外的点

python - 如何使用 opencv python 从矩阵创建图像?

c++ - 未定义对 cv::Tracker::update 的引用

python - 在python-opencv中打印读取图像的像素值时出现错误,TypeError: 'NoneType'对象没有属性 '__getitem__'