gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:31:33 51 4
gpt4 key购买 nike

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

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/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com