OpenCV houghLinesP参数

Jan*_*ney 18 python opencv houghlinesp

我使用HoughLinesP和Python中的OpenCV在这个图像中找到棋盘上的线很困难.

为了理解HoughLinesP的参数,我提出了以下代码:

import numpy as np
import cv2
from matplotlib import pyplot as plt
from matplotlib import image as image

I = image.imread('chess.jpg') 
G = cv2.cvtColor(I, cv2.COLOR_BGR2GRAY)

# Canny Edge Detection:
Threshold1 = 150;
Threshold2 = 350;
FilterSize = 5
E = cv2.Canny(G, Threshold1, Threshold2, FilterSize)

Rres = 1
Thetares = 1*np.pi/180
Threshold = 1
minLineLength = 1
maxLineGap = 100
lines = cv2.HoughLinesP(E,Rres,Thetares,Threshold,minLineLength,maxLineGap)
N = lines.shape[0]
for i in range(N):
    x1 = lines[i][0][0]
    y1 = lines[i][0][1]    
    x2 = lines[i][0][2]
    y2 = lines[i][0][3]    
    cv2.line(I,(x1,y1),(x2,y2),(255,0,0),2)

plt.figure(),plt.imshow(I),plt.title('Hough Lines'),plt.axis('off')
plt.show()
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,这只能找到一行.如果我将maxLineGap减少到1,它会获得数千.

我理解为什么会这样,但我如何选择一组合适的参数来合并所有这些共线?我错过了什么吗?

我想保持代码简单,因为我正在使用它作为此功能的实例.

在此先感谢您的帮助!

更新:这与HoughLines完美配合.

并且似乎没有边缘检测问题,因为Canny正常工作.

但是,我仍然需要让HoughLinesP工作.有任何想法吗??

图片在这里:结果

Jan*_*ney 45

好吧,我终于找到了问题,并认为我会分享其他人驱动坚果的解决方案.问题是在HoughLinesP函数中,有一个额外的参数,"lines"是多余的,因为函数的输出是相同的:

cv2.HoughLinesP(image,rho,theta,threshold [,lines [,minLineLength [,maxLineGap]]])

这会导致参数出错,因为它们以错误的顺序读取.为了避免与参数的顺序混淆,最简单的解决方案是在函数内部指定它们,如下所示:

lines = cv2.HoughLinesP(E,rho = 1,theta = 1*np.pi/180,threshold = 100,minLineLength = 100,maxLineGap = 50)
Run Code Online (Sandbox Code Playgroud)

这完全解决了我的问题,我希望它能帮助别人.

  • [OpenCV教程](https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html)尚不能明确阐明这一点,直到目前,它实际上仍在犯同样的错误。感谢您指出这一点。 (3认同)

Fur*_*sen 6

  • Edges:边缘检测器的输出。
  • lines:一个向量,用于存储线的起点和终点的坐标。
  • rho:分辨率参数 \rho(以像素为单位)。
  • theta:参数θ的分辨率(以弧度为单位)。
  • 阈值:检测直线的最小相交点数量。

示例应用程序

import cv2
import numpy as np

img = cv2.imread('sudoku.png', cv2.IMREAD_COLOR)
# Convert the image to gray-scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the edges in the image using canny detector
edges = cv2.Canny(gray, 50, 200)
# Detect points that form a line
lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=10, maxLineGap=250)
# Draw lines on the image
for line in lines:
    x1, y1, x2, y2 = line[0]
    cv2.line(img, (x1, y1), (x2, y2), (255, 0, 0), 3)

# Show result
img = cv2.resize(img, dsize=(600, 600))
cv2.imshow("Result Image", img)

if cv2.waitKey(0) & 0xff == 27:  
    cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述