具有计算图像中水平线数量并以字符串类型返回的功能

问题描述 投票:0回答:2

这是我要计算行数的图像我已经尝试过此代码:“这是图像”Horizontal Line detection with OpenCV但是它也将输出作为图像以及以下代码返回:Python How to detect vertical and horizontal lines in an image with HoughLines with OpenCV?我只想将其返回为数字

python opencl
2个回答
0
投票

如果使用lines = cv2.HoughLinesP(...),则只需取len(lines)即可获得行数。如果没有,您使用了什么?您可以参考其他一些stackoverflow帖子,但是可以发布用于计算行的代码吗?


0
投票

希望以下代码对您有所帮助。

import cv2
img = cv2.imread("lines.png")
h,w = img.shape[0:2]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
edges = cv2.Canny(img, 50, 200, None, 3)


def dist(x, y, x1, y1):
    return ((x-x1)**2+(y-y1)**2)**(0.5)


def slope(x, y, x1, y1):
    if y1 != y:
        return ((x1-x)/(y1-y))
    else:
        return 0


fld = cv2.ximgproc.createFastLineDetector()
lines = fld.detect(edges)
no_of_hlines = 0
#result_img = fld.drawSegments(img, lines)
for line in lines:
    x0 = int(round(line[0][0]))
    y0 = int(round(line[0][1]))
    x1 = int(round(line[0][2]))
    y1 = int(round(line[0][3]))
    d = dist(x0, y0, x1, y1)
    if d>150: #You can adjust the distance for precision
        m = (slope(x0, y0, x1, y1))
        if m ==0: #slope for horizontal lines and adjust slope for vertical lines
            no_of_hlines+=1
            cv2.line(img, (x0, y0), (x1, y1), (255, 0, 255), 1, cv2.LINE_AA)
print(no_of_hlines)
cv2.imshow("lines",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
© www.soinside.com 2019 - 2024. All rights reserved.