如何在opencv/python中找到轮廓上的特定点

2024-04-19 15:39:30 发布

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

我已经用opencv创建了一些轮廓,我需要确定轮廓上的一个特定点,通常是V形的最里面的点。在所附的图像中,我要标识的点用绿色箭头表示。在

Example

左边是一个简单的例子,可以通过计算轮廓的凸包,然后找到离外壳最远的点来进行识别(例如)。在

然而,在附加图像的右侧是一个更困难的情况,我得到了几个轮廓,而不是一个轮廓,而且漂亮的“V”形不存在,因此无法识别“V”的最内侧点。如红色虚线所示,一种解决方案可能是外推较高的轮廓,直到它与较低的轮廓相交。有人知道我该怎么做吗?或者有更好的解决方案?在

我试过:

  • 膨胀/腐蚀(当多个轮廓接近时起作用,否则不起作用)

  • hough变换p(容易误定位目标点)

任何建议都将不胜感激。在


Tags: 定位图像目标情况箭头解决方案外壳opencv
1条回答
网友
1楼 · 发布于 2024-04-19 15:39:30

此解决方案适用于您提供的两个图像。对于所有其他具有相似颜色和指向右侧的“v”形(或至少是部分“v”形)的图像,这应该是一个很好的解决方案。在

让我们先看看更简单的图像。我从使用颜色空间分割图像开始。在

# Convert frame to hsv color space
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Define range of pink color in HSV
(b,r,g,b1,r1,g1) = 0,0,0,110,255,255
lower = np.array([b,r,g])
upper = np.array([b1,r1,g1])
# Threshold the HSV image to get only pink colors
mask = cv2.inRange(hsv, lower, upper)

color spaces

接下来,我找到了mid_point,在该行的上方和下方有相等数量的白色。在

^{pr2}$

然后,我从中点开始对图像进行泛洪处理: 背景=np.零((h+2,w+2),np.uint8公司)在

kernel = np.ones((k_size, k_size),np.uint8)  
cv2.floodFill(mask, bg, (0, mid_point), 123)

floodfilled

现在我有了泛光图像,我知道我要寻找的点是离图像右侧最近的灰色像素。在

# Find the gray pixel that is furthest to the right
idx = 0
while True:
    column = mask_temp[:,idx:idx+1]
    element_id, gray_px, found = 0, [], False
    for element in column:
        if element == 123:
            v_point = idx, element_id
            found = True
        element_id += 1
    # If no gray pixel is found, break out of the loop
    if not found: break
    idx += 1

结果是:

result1

现在来看看更难的图像。在右侧图像中,“v”未完全连接:

does not connect

为了关闭“v”,我反复放大检查是否连接的掩码:

# Flood fill and dilate loop
k_size, iters = 1, 1
while True:
    bg = np.zeros((h+2, w+2), np.uint8)
    mask_temp = mask.copy()    
    kernel = np.ones((k_size, k_size),np.uint8)    
    mask_temp = cv2.dilate(mask_temp,kernel,iterations = iters)
    cv2.floodFill(mask_temp, bg, (0, mid_point), 123)
    cv2.imshow('mask', mask_temp)
    cv2.waitKey()
    k_size += 1
    iters += 1
    # Break out of the loop of the right side of the image is black
    if mask_temp[h-1,w-1]==0 and mask_temp[1, w-1]==0: break

dilation

这是结果输出:

output2

相关问题 更多 >