OpenCV:检测到多条线的矩形边缘和不正确的“y”边缘绘制

问题描述 投票:0回答:1

我正在使用 Python 中的 OpenCV 库,并尝试检测图像中矩形形状的长边和短边。我使用了 Canny 边缘检测器,然后应用霍夫变换来检测线条。但是,我遇到一个问题,输出检测到多条相同长度的线,并且没有正确绘制“y”边缘。

这是我的代码的简化版本:

import cv2
import numpy as np

img = cv2.imread(r"C:\Users\Asus Hn004W\Desktop\1.jpeg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 78, 106, apertureSize=3)

lines = cv2.HoughLines(edges, 1, np.pi/180, 200)

for r_theta in lines:
    arr = np.array(r_theta[0], dtype=np.float64)
    r, theta = arr
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*r
    y0 = b*r

    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))

    cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)

cv2.imshow('', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

我想了解为什么检测到多条相同长度的线以及为什么未正确绘制“y”边缘。我应该对代码进行哪些修改才能准确检测和绘制矩形形状的边缘?

提前感谢您的帮助。enter image description here

python opencv image-processing edge-detection hough-transform
1个回答
0
投票

多行

所有票数高于阈值的结果将从

HoughLines()
返回。

因此,您应该采用一些后处理来决定您的结果。 通常采用称为“非极大值抑制”的过程。

未正确绘制“y”边缘

也许,你的阈值(

200
)对于垂直线来说太大了(或者精明的结果不好)。

© www.soinside.com 2019 - 2024. All rights reserved.