Python cv2 HoughLines网格线检测

标签 python opencv image-processing numpy hough-transform

我在图像中有一个简单的网格,我正在尝试确定网格大小,例如6x6、12x12 等。使用 Python 和 cv2。

enter image description here

我正在用上面的 3x3 网格对其进行测试,我计划通过检测图像中有多少垂直/水平线来确定网格大小:

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()

我的代码检测到线条,如下所示,但是我的图像中的每条线都检测到多条线:

enter image description here

(图中每条线都有两条1px的绿线)

我不能简单地将线数除以二,因为(取决于网格大小)有时只会绘制一条线。

如何更准确地检测原始图像中检测到的每条线并绘制一条线?

我调整了阈值设置,将图像缩小为黑白,但我仍然看到多条线。我认为这是因为精明的边缘检测?

最佳答案

我最终遍历了这些线并删除了彼此相距 10 像素以内的线:

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网格线检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19054055/

相关文章:

python - OpenCV canny 边缘检测在理想正方形上无法正常工作

python - 使用opencv识别OCR期间的元音字符

python - Python OpenCV 和 MATLAB 之间的不同颜色结果

image-processing - 如何转换图像?

Python Plotly - 带注释的热图 - 添加布局

python - 如何在python中将列表拆分为给定数量的子列表

python - 使用 python 写入文本文件时,我需要更新特定列

python - 尝试使用 Matplotlib 安装 OpenCV

c++ - 如何检测opencv中所有具有相同颜色值的相邻像素

python - 插入行 python gdata.spreadsheets.client