我试图使用opencv(python)中的harris角点检测来检测图像中的所有角点.但是由于线条的粗细,我在一个角落里得到了多个角落.我能做些什么来纠正这一点吗.

密码

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()
密码>

This is the input image

Output image(that i got)

推荐答案

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

Current scenario:

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

enter image description here

在上面的例子中,有许多(据说)彼此靠近的角点.

Approach:

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

# 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)

enter image description here

Suggestions:

为了得到更准确的结果,你可以试着找出某个距离内所有点的平均值.这些线将在靠近线交点的位置重合.

Python相关问答推荐

在输入行运行时停止代码

如何使用使用来自其他列的值的公式更新一个rabrame列?

从旋转的DF查询非NaN值

Python将一个列值分割成多个列,并保持其余列相同

如何将相同组的值添加到嵌套的Pandas Maprame的倒数第二个索引级别

如何使用matplotlib查看并列直方图

python的文件. truncate()意外地没有截断'

如何在python tkinter中绑定键盘上的另一个回车?

Networkx中K-Shell最核心的 node

django中没有预期的输出

Df.Drop_Duplates(),以极点表示?

在Polars中查找给定列的范围内的最大值?

为列PANAS中的每个字符串值创建累计和列

获取Python中的层次 struct 数据

如何在Python中返回多行SQL查询

我的tkinter应用程序不会改变它正在加载的文件

NetCDF:使用MSWEP再分析数据集计算沿所有坐标的年降水量总和

为什么我不能从我的Django views.py文件中导入通用部件?

安装句子转换器时出错

一种处理Django查询集数据的轻量级方法