所以我试图在棋盘上获得hough线,但算法只能检测到一条线。我使用的是python 2.7和opencv 3.0。这是代码:
def applyHoughLineTransform():
image1 = cv2.imread('pictures/board1.png',0)
image2 = cv2.imread('pictures/board2.png',0)
image3 = cv2.imread('pictures/board3.png')
image4 = cv2.imread('pictures/board4.png')
lines1 = cv2.HoughLines(image1,1,math.pi/180.0,5)
lines2 = cv2.HoughLines(image2,1,math.pi/180.0,5)
lines1 = lines1[0]
lines2 = lines2[0]
for rho,theta in lines1:
print ('Rho and theta:',rho,theta)
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
print (x1,y1)
print (x2,y2)
cv2.line(image3,(x1,y1),(x2,y2),(0,0,255),2)
for rho,theta in lines2:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
cv2.line(image4,(x1,y1),(x2,y2),(0,0,255),2)
cv2.imwrite('pictures/board1.png',image1)
cv2.imwrite('pictures/board2.png',image2)
cv2.imshow('hough line 1',image3)
cv2.imshow('hough line 2',image4)
这里是我执行hough line算法的canny edge图像:
以下是结果:
如你所见,非常蹩脚。 canny算法似乎提供了非常好的边缘来操作。我不完全确定我做错了什么。我想它与输入houghLines函数的参数有关。如果有人能指出我正确的方向(或完全解决我的问题:))我将非常感激。这是我使用的教程网站的链接: http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html
答案 0 :(得分:12)
从包中检查示例后,这是您应该在Opencv 3.0.0 +中使用它的方法
import cv2
import numpy as np
import math
image1 = cv2.imread('img.png')
gray=cv2.cvtColor(image1,cv2.COLOR_BGR2GRAY)
dst = cv2.Canny(gray, 50, 200)
lines= cv2.HoughLines(dst, 1, math.pi/180.0, 100, np.array([]), 0, 0)
#lines1 = cv2.HoughLines(image1,1,math.pi/180.0,5)
#lines2 = cv2.HoughLines(image2,1,math.pi/180.0,5)
#lines1 = lines1[0]
#lines2 = lines2[0]
a,b,c = lines.shape
for i in range(a):
rho = lines[i][0][0]
theta = lines[i][0][1]
a = math.cos(theta)
b = math.sin(theta)
x0, y0 = a*rho, b*rho
pt1 = ( int(x0+1000*(-b)), int(y0+1000*(a)) )
pt2 = ( int(x0-1000*(-b)), int(y0-1000*(a)) )
cv2.line(image1, pt1, pt2, (0, 0, 255), 2, cv2.LINE_AA)
cv2.imshow('image1',image1)
cv2.waitKey(0)
cv2.destoryAllWindows(0)
答案 1 :(得分:6)
解决此问题的方法是从opencv 3.0切换到2.4。现在我得到了我想要的所有线条。获得的经验教训......有一个原因是测试版!结果如下:
答案 2 :(得分:2)
我在OpenCV 3.4中遇到了同样的问题。罪魁祸首是在numpy数组lines
:
[[[ 7.99000000e+02 1.57079637e+00]]
[[ 9.39000000e+02 1.57079637e+00]]
[[ 1.57100000e+03 1.57079637e+00]]
[[ 6.68000000e+02 1.57079637e+00]]
[[ 5.46000000e+02 1.57079637e+00]]
[[ 1.42700000e+03 1.57079637e+00]]
...
[[ 1.49100000e+03 1.57079637e+00]]]
请注意,这是一个3D数组,而示例代码将其视为2D数组。修复只是从3D数组中提取rho和theta(只改变前两行):
for line in lines:
rho, theta = line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
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)