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

2024-04-20 00:28:36 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我有一张由多个小片组成的图像,希望得到它的外部轮廓,如下所示:

enter image description here

enter image description here

我以前使用过轮廓近似凸包函数来获得近似的外部轮廓,但它们只是由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

有什么办法让它更接近你想要的吗?在


Tags: 函数imgnpareacv2kernelmax轮廓
2条回答

正如@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

你可以应用形态学操作来闭合轮廓,也许这会奏效

  kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
  thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

然后应用扩张手术来闭合间隙较小的轮廓

^{pr2}$

请给我你的反馈。在

相关问题 更多 >