python - 如何使用霍夫变换查找图像中的行数?

标签 python image opencv image-processing hough-transform

我无法使用霍夫变换获得图像中存在的确切行数。

我已经找到图像的 houghLines,现在当使用 hough 线映射图像打印行数时,我无法获得确切的行数。

import cv2
import numpy as np
import matplotlib.pyplot as plt


img=cv2.imread('lines.png')

edges=cv2.Canny(img,0,150)


lines = cv2.HoughLinesP(edges, 2, 1*np.pi/180, 45, minLineLength=1, maxLineGap=1)



for line in lines:
  x1,y1,x2,y2=line[0]
  cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2) 


plt.imshow(img)
print(len(lines))

预期输出为 5,但下图中的实际输出为 7:

input image

最佳答案

不使用 cv2.HoughLinesP(),一种更简单的方法是设置阈值并找到轮廓。遍历 cv2.findContours() 时,您可以使用计数器跟踪行数。如果您坚持使用 cv2.HoughLinesP(),您可以使用 minLineLengthmaxLineGap 参数来正确检测所需的线


阈值

enter image description here

检测线

enter image description here

结果

5

import cv2

image = cv2.imread('1.png')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY_INV)[1]

cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

lines = 0
for c in cnts:
    cv2.drawContours(image, [c], -1, (36,255,12), 3)
    lines += 1

print(lines)
cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()

关于python - 如何使用霍夫变换查找图像中的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57250226/

相关文章:

c++ - opencv:获取从 gphoto2 传输的一系列图像

c++ - Insufficient memory 错误 Opencv/c++

perl - 是否有纯 Perl 模块来创建图像并在图像中放置文本?

android - 在 Android 上使用 "no picture"联系人的系统镜像

python - Porter Stemmer 可以返回词缀而不是词干吗?

python - 在 DataFrame 的开头而不是末尾附加子字符串

java - JButton 仅在鼠标悬停时显示

opencv - 如何找到 OpenCV 类的定义?

python - wxPython 拖放 matplotlib 图形

python - 无法在 Kaggle 笔记本中安装 Python 库