我无法使用霍夫变换获得图像中存在的确切行数。
我已经找到图像的 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:
最佳答案
不使用 cv2.HoughLinesP()
,一种更简单的方法是设置阈值并找到轮廓。遍历 cv2.findContours()
时,您可以使用计数器跟踪行数。如果您坚持使用 cv2.HoughLinesP()
,您可以使用 minLineLength 和 maxLineGap 参数来正确检测所需的线
阈值
检测线
结果
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/