gpt4 book ai didi

opencv - HoughLinesP openCV函数中的多行检测

转载 作者:行者123 更新时间:2023-12-02 16:54:33 24 4
gpt4 key购买 nike

我是Python和OpenCV的新手。我正在尝试使用HoughLinesP函数从互联网上的代码检测单行,检测到3-4行。我尝试使用maxLineGap变量,但没有帮助。

输入图片:
enter image description here
输出图像:
enter image description here

import sys
import math
import cv2 as cv
import numpy as np

def main(argv):

default_file = "line.png"
filename = argv[0] if len(argv) > 0 else default_file
# Loads an image
src = cv.imread(filename, cv.IMREAD_GRAYSCALE)
# Check if image is loaded fine
if src is None:
print ('Error opening image!')
print ('Usage: hough_lines.py [image_name -- default ' + default_file + '] \n')
return -1


dst = cv.Canny(src, 50, 200, None, 3)

# Copy edges to the images that will display the results in BGR
cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR)
cdstP = np.copy(cdst)

lines = cv.HoughLines(dst, 1, np.pi / 180, 150, None, 0, 0)

if lines is not None:
for i in range(0, len(lines)):
rho = lines[i][0][0]
theta = lines[i][0][1]
a = math.cos(theta)
b = math.sin(theta)
x0 = a * rho
y0 = b * rho
pt1 = (int(x0 + 1000*(-b)), int(y0 + 1000*(a)))
pt2 = (int(x0 - 1000*(-b)), int(y0 - 1000*(a)))
cv.line(cdst, pt1, pt2, (0,0,255), 3, cv.LINE_AA)


linesP = cv.HoughLinesP(dst, 1, np.pi / 180, 50, None, 50, 150)

no_of_Lines = 0
if linesP is not None:
for i in range(0, len(linesP)):
l = linesP[i][0]
no_of_Lines = no_of_Lines + 1
cv.line(cdstP, (l[0], l[1]), (l[2], l[3]), (0,0,255), 3, cv.LINE_AA)



print('Number of lines:' + str(no_of_Lines))

cv.imshow("Source", src)
cv.imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst)

cv.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP)

cv.waitKey()
return 0

if __name__ == "__main__":
main(sys.argv[1:])

最佳答案

您的Canny边缘检测器的输出有多条线。结果,函数cv.HoughLines()返回多行。您需要对图像进行骨架化处理,以便将所有行合并为一个。

这是我所做的

由于这是简单的图像,因此我对Canny边缘输出执行了一些形态学操作。膨胀后侵 eclipse 。如果您注意到下面的代码,则我使用了更大的内核大小来执行侵 eclipse 操作,以便获得一条细线。

补充代码:

kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3))
dilation = cv.dilate(dst, kernel, iterations = 1)
kernel1 = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
erosion = cv.erode(dilation, kernel1, iterations = 1)

输出:

这是我在python控制台上得到的:
Number of lines:1

侵 eclipse 后的产量:

enter image description here

霍夫线变换的输出:

enter image description here

概率霍夫线变换的输出:

enter image description here

注意:

尝试识别图像之前,请务必确保图像中有细线。

关于opencv - HoughLinesP openCV函数中的多行检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49993616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com