Python cv2 HoughLines网格线检测 [英] Python cv2 HoughLines grid line detection
问题描述
我在图像中有一个简单的网格,我正在尝试确定网格大小,例如6x6、12x12等.使用Python和cv2.
I have a simple grid in an image, I am trying to determine the grid size, e.g. 6x6, 12x12, etc. Using Python and cv2.
我正在使用上面的3x3网格进行测试,我打算通过检测图像中的垂直/水平线数来确定网格的大小:
I am testing it with the above 3x3 grid, I was planning to determine the grid size by counting how many vertical / horizontal lines there are by detecting them in the image:
import cv2
import numpy as np
im = cv2.imread('photo2.JPG')
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
imgSplit = cv2.split(im)
flag,b = cv2.threshold(imgSplit[2],0,255,cv2.THRESH_OTSU)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(1,1))
cv2.erode(b,element)
edges = cv2.Canny(b,150,200,3,5)
while(True):
img = im.copy()
lines = cv2.HoughLinesP(edges,1,np.pi/2,2, minLineLength = 620, maxLineGap = 100)[0]
for x1,y1,x2,y2 in lines:
cv2.line(img,(x1,y1),(x2,y2),(0,255,0),1)
cv2.imshow('houghlines',img)
if k == 27:
break
cv2.destroyAllWindows()
我的代码检测到这些行,如下所示,但是在我的图像中,对于每行都检测到多行:
My code detects the lines, as can be seen below, however there are multiple lines detected for each line in my image:
(图像中的每一行都有两条1px的绿线)
(there are two 1px green lines drawn for every line in the image)
我不能简单地将行数除以2,因为(取决于网格的大小)有时只画一条线.
I cannot simply divide the number of lines by two because (depending on the grid size) sometimes just the one line will be drawn.
如何为原始图像中检测到的每条线更准确地检测并绘制一条线?
How can I more accurately detect and draw a single line for every line detected in the original image?
我已经调整了阈值设置,将图像缩小为黑白,但是我仍然得到多行.我认为这是因为检测到了精巧的边缘?
I have tweaked threshold settings, reducing the image to black and white, yet I still get multiple lines. I assume this is because of the canny edge detection?
推荐答案
我最终遍历了这些行并删除了彼此之间10px之内的行:
I ended up iterating through the lines and removing lines that were within 10px of one another:
lines = cv2.HoughLinesP(edges,1,np.pi/180,275, minLineLength = 600, maxLineGap = 100)[0].tolist()
for x1,y1,x2,y2 in lines:
for index, (x3,y3,x4,y4) in enumerate(lines):
if y1==y2 and y3==y4: # Horizontal Lines
diff = abs(y1-y3)
elif x1==x2 and x3==x4: # Vertical Lines
diff = abs(x1-x3)
else:
diff = 0
if diff < 10 and diff is not 0:
del lines[index]
gridsize = (len(lines) - 2) / 2
这篇关于Python cv2 HoughLines网格线检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!