opencv中的角点检测

Yad*_*u B 5 python opencv image-processing computer-vision corner-detection

我试图使用 opencv(python) 中的哈里斯角点检测来检测图像中的所有角点。但由于线的粗细,我在一个角上得到了多个角。我能做些什么来纠正这个问题吗?

代码

import numpy as np
import cv2 as cv
filename = 'Triangle.jpg'
img = cv.imread(filename)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv.cornerHarris(gray,2,3,0.04)
#result is dilated for marking the corners, not important
dst = cv.dilate(dst,None)
# Threshold for an optimal value, it may vary depending on the image.
img[dst>0.01*dst.max()]=[0,0,255]
cv.imshow('dst',img)
if cv.waitKey(0) & 0xff == 27:
    cv.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)

这是输入图像

输出图像(我得到的)

Jer*_*uke 2

如果您的期望是在每个线相交处获得单个角点,那么以下是一种简单的方法。

当前场景:

# visualize the corners
mask = np.zeros_like(gray)
mask[dst>0.01*dst.max()] = 255
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在上面,有许多(假设的)角点彼此靠近。

方法:

现在的想法是只保留一个彼此非常接近的点,同时丢弃其余的点。为此,我计算每个角点之间的距离并保留那些超过阈值的角点。

# storing coordinate positions of all points in a list
coordinates = np.argwhere(mask)
coor_list = coordinates.tolist()

# points beyond this threshold are preserved
thresh = 20

# function to compute distance between 2 points
def distance(pt1, pt2):
    (x1, y1), (x2, y2) = pt1, pt2
    dist = math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
    return dist

# 
coor_list_2 = coor_list.copy()

# iterate for every 2 points
i = 1    
for pt1 in coor_list:
    for pt2 in coor_list[i::1]:
        if(distance(pt1, pt2) < thresh):
          # to avoid removing a point if already removed
          try:
            coor_list_2.remove(pt2)      
          except:
            pass
    i+=1

# draw final corners
img2 = img.copy()
for pt in coor_list_2:
    img2 = cv2.circle(img2, tuple(reversed(pt)), 3, (0, 0, 255), -1)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

建议:

为了获得更准确的结果,您可以尝试查找某个邻近范围内所有点的平均值。这些将在线的交点附近重合。