如何在我的 OpenCV Python 脚本中改进 HoughLinesP() 的结果
How can I improve the results of HoughLinesP() in my OpenCV Python script
我正在尝试获取此图像中的所有线条:
这是我正在使用的代码:
threshold = 30
minLineLength =10
maxLineGap = 10
lines = cv2.HoughLinesP(img,1,np.pi/360, threshold, minLineLength, maxLineGap)
问题是我的行数太多 (~300):
但如果我增加阈值,它就会开始漏掉一些行:
有什么方法可以减少行数同时保持行检测的准确性吗?
提前致谢!
它在 Python/OpenCV 中对我来说(大部分)都很好。适当调整 HoughP 行参数。
我认为您需要先对图像进行阈值处理。也许把白线变细。
输入:
import cv2
import numpy as np
# read image as color not grayscale
img = cv2.imread("lines.png", cv2.IMREAD_COLOR)
# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# do threshold
thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)[1]
# get hough line segments
threshold = 30
minLineLength =10
maxLineGap = 10
lines = cv2.HoughLinesP(thresh, 1, np.pi/360, threshold, minLineLength, maxLineGap)
# draw lines
results = img.copy()
for [line] in lines:
print(line)
x1 = line[0]
y1 = line[1]
x2 = line[2]
y2 = line[3]
cv2.line(results, (x1,y1), (x2,y2), (0,0,255), 1)
# show lines
cv2.imshow("lines", results)
cv2.waitKey(0)
# write results
cv2.imwrite("lines_hough.png",results)
生成的红色 Hough 线:
你得到很多平行的非常接近的线,你可能想以某种方式合并或缩小列表。
我正在尝试获取此图像中的所有线条:
这是我正在使用的代码:
threshold = 30
minLineLength =10
maxLineGap = 10
lines = cv2.HoughLinesP(img,1,np.pi/360, threshold, minLineLength, maxLineGap)
问题是我的行数太多 (~300):
但如果我增加阈值,它就会开始漏掉一些行:
有什么方法可以减少行数同时保持行检测的准确性吗?
提前致谢!
它在 Python/OpenCV 中对我来说(大部分)都很好。适当调整 HoughP 行参数。
我认为您需要先对图像进行阈值处理。也许把白线变细。
输入:
import cv2
import numpy as np
# read image as color not grayscale
img = cv2.imread("lines.png", cv2.IMREAD_COLOR)
# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# do threshold
thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)[1]
# get hough line segments
threshold = 30
minLineLength =10
maxLineGap = 10
lines = cv2.HoughLinesP(thresh, 1, np.pi/360, threshold, minLineLength, maxLineGap)
# draw lines
results = img.copy()
for [line] in lines:
print(line)
x1 = line[0]
y1 = line[1]
x2 = line[2]
y2 = line[3]
cv2.line(results, (x1,y1), (x2,y2), (0,0,255), 1)
# show lines
cv2.imshow("lines", results)
cv2.waitKey(0)
# write results
cv2.imwrite("lines_hough.png",results)
生成的红色 Hough 线:
你得到很多平行的非常接近的线,你可能想以某种方式合并或缩小列表。