改进HoughLines以进行水平线检测(Python,OpenCV)

时间:2017-09-28 15:15:19

标签: python opencv hough-transform houghlinesp

我有这张源图片:

src

我的目标是删除底线,同时保持字母/数字不变。

这是我使用的代码:

import cv2
import numpy as np

img = cv2.imread('src.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

edges = cv2.Canny(gray,100,200,apertureSize = 5)

minLineLength = 0
maxLineGap = 19
lines = cv2.HoughLinesP(edges,1,np.pi/180,15,minLineLength,maxLineGap)
for x in range(0, len(lines)):
    for x1,y1,x2,y2 in lines[x]:
        cv2.line(img,(x1,y1),(x2,y2),(255,255,255),2)

cv2.imshow('hough',img)
cv2.waitKey(0)

我现在取得的最好成绩是:

out

如何更好地改进,尽可能清洁图像? 例如,图像周围的所有碎片,单词下面的点和(静止)线,我该如何删除它们?

谢谢。

OT:有没有办法创建一个改变参数(apertureSize,minLineLength,maxLineGap等)的轨迹栏来实时查看结果?

2 个答案:

答案 0 :(得分:1)

一旦你有来自霍夫的线段,你可以搜索它们以找到可能属于底线的那一部分(即正确的角度和截距)然后沿着这个预测的线移除所有黑点,而不仅仅是找到的线段。霍夫。

另一个提示,尝试cv :: adaptivethreshold而不是canny,并尝试首先进行小高斯模糊以删除背景斑点。

编辑:您正在使用HoughP,它可以单独找到每个留置权段。你正在寻找单个(破损)线,所以使用常规Hough可能会更好,并从结果中选择图像下半部分中最强的水平线 - 然后沿该方向擦除所有点。

ot:cv :: namedWindow可以有trackbar,您可以轻松取回值

答案 1 :(得分:1)

根据@Link的要求:

我在python方面经验有限,所以我不知道这段代码的线程安全性如何,但这应该向您展示在python OpenCV中创建轨迹栏的基础知识。

def onChange(pos):
    global img
    global gray
    global dst

    dst = np.copy(img)

    apertureSize = cv2.getTrackbarPos("ApertureSize", "Result")
    minLineLength = cv2.getTrackbarPos("LineLength", "Result")
    maxLineGap = cv2.getTrackbarPos("LineGap", "Result")

    # according to OpenCV, aperture size must be odd and between 3 and 7
    if apertureSize % 2 == 0:
        apertureSize += 1
    if apertureSize < 3:
        apertureSize = 3

    edges = cv2.Canny(gray,100,200,apertureSize = apertureSize)

    lines = cv2.HoughLinesP(edges,1,np.pi/180,15,minLineLength,maxLineGap)
    for x in range(0, len(lines)):
        for x1,y1,x2,y2 in lines[x]:
            cv2.line(dst,(x1,y1),(x2,y2),(255,255,255),2)

#Run Main
if __name__ == "__main__" :

    img = cv2.imread("image.png", -1)
    dst = np.copy(img)

    cv2.namedWindow("Result", cv2.WINDOW_NORMAL)

    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    #default values for trackbars
    defaultApertureSize = 5
    minLineLength = 0
    maxLineGap = 19

    # according to OpenCV, aperture size must be odd and between 3 and 7
    # the aperture size range is (0 - 6)
    cv2.createTrackbar("ApertureSize", "Result", defaultApertureSize, 6, onChange)

    # line length range is (0 - 10)
    cv2.createTrackbar("LineLength", "Result", minLineLength, 10, onChange)

    # line gap range is (0 - 19)
    cv2.createTrackbar("LineGap", "Result", maxLineGap, 19, onChange)

    while True:
        cv2.imshow("Result", dst)
        key = cv2.waitKey(1)
        if key == ord('q'):
            break

    cv2.destroyAllWindows()