gpt4 book ai didi

python - 如何绘制遮挡/重叠物体的轮廓?

转载 作者:行者123 更新时间:2023-11-30 21:51:12 25 4
gpt4 key购买 nike

我试图让 OpenCV 识别出红色区域是一个轮廓,而不是将其分割成两个单独的轮廓。我尝试过破坏层次结构,但没有成功。有什么想法吗?

下面提供了图像和代码。

import cv2
import numpy as np
black = (0,0,0)
# All of these are in hsv format
lb=np.array([0,181,0])
ub=np.array([6,255,255])
# Load img
img = cv2.imread('test.jpg')
img=cv2.resize(img,(400,400))

kernelOpen=np.ones((5,5))
kernelClose=np.ones((20,20))
#convert BGR to HSV
imgHSV= cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
# create the Mask
mask = cv2.inRange(imgHSV, lb, ub)
maskso=cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernelOpen)
masksc=cv2.morphologyEx(maskso,cv2.MORPH_CLOSE,kernelClose)
conts,hiers=cv2.findContours(masksc.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
# Create convex hull
hull = []
for i in range(len(conts)):
# creating convex hull object for each contour
hull.append(cv2.convexHull(conts[i], False))
# Draw contour
cv2.drawContours(img,hull,-1,black,2)

cv2.imshow("image", img)
cv2.waitKey(5000)
cv2.destroyAllWindows()

Without contours drawn

With contours drawn

最佳答案

替换此代码片段

# Create convex hull
hull = []
for i in range(len(conts)):
# creating convex hull object for each contour
hull.append(cv2.convexHull(conts[i], False))
# Draw contour
cv2.drawContours(img,hull,-1,black,2)

# Create convex hull
hull = np.zeros((0, 1, 2), np.int32)
for i in range(len(conts)):
hull = np.concatenate((hull, conts[i]), axis=0)
hull = cv2.convexHull(hull, False)
# Draw contour
cv2.drawContours(img,[hull],-1,black,2)

我得到以下输出,我认为这是您想要的:

Output

我不是收集每个轮廓的单个凸包,而是收集所有轮廓,然后获取所有轮廓点的凸包。

希望有帮助!

----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.8.1
NumPy: 1.18.1
OpenCV: 4.2.0
----------------------------------------

关于python - 如何绘制遮挡/重叠物体的轮廓?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60167582/

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