如何绘制遮挡/重叠对象的轮廓?

2024-09-30 16:20:48 发布

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

我试图让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


Tags: inimportimgnponesarraycv2轮廓
1条回答
网友
1楼 · 发布于 2024-09-30 16:20:48

替换此代码片段

# 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
                    

相关问题 更多 >