如何使用概率霍夫线变换检测所有垂直背景线?

问题描述

我正在尝试使用霍夫线变换检测报纸文章的预处理二进制图像的背景线。

我使用的代码如下,它只检测到一条垂直背景线,但我想检测所有垂直背景线。

如何改进我的代码以检测所有仅垂直背景线,正如我在预期输出图像中标记的那样?

import cv2 as cv
import numpy as np
import os
    
#binary image
image = cv.imread('../outputs/contour.jpg')
gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)  # convert2grayscale
(thresh,binary) = cv.threshold(gray,150,255,cv.THRESH_BINARY | cv.THRESH_OTSU)
#cv.imshow('binary',binary)
#cv.waitKey(0)
    
minLineLength = 10
maxLineGap = 40
lines=np.array([])
    
lines = cv.houghlinesp(binary,rho=np.pi/180,theta=np.pi/180,threshold=10,lines=lines,minLineLength=minLineLength,maxLineGap=maxLineGap)

for x1,y1,x2,y2 in lines[0]:
   cv.line(image,(x1,y1),(x2,y2),(0,0),2)
    
cv.imshow('lines',image)
path='../outputs'
cv.imwrite(os.path.join(path,'line.jpg'),image)
cv.waitKey(0)

预期的输出是这样的:

enter image description here

但是我从上面的代码得到的输出是这样的:

enter image description here

输入图像为:

enter image description here

解决方法

这是一个蛮力解决方案,您可能希望优化参数以使其更好:

result

#------------------#
# Import Libraries #
#------------------#
import matplotlib.pyplot as plt
import numpy as np
import cv2

# Read Image
image = cv2.imread('input.jpg',0)
# Gaussian Blur 
blur = cv2.GaussianBlur(image,(13,13),5)
# Morphological opening
kernel = np.ones((11,11),dtype=np.uint8)
opening = cv2.morphologyEx(blur,cv2.MORPH_OPEN,kernel)

# Thresholding
(_,thresh) = cv2.threshold(opening,150,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)
(_,thresh2) = cv2.threshold(image,cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# Stacking the image to draw lines in colour
image = np.stack([image,image,image],axis=2)

# Define Hough Parameters
minLineLength = 40
maxLineGap = 10
# Hough Lines Detection
lines1 = cv2.HoughLinesP(thresh,rho=np.pi/180,theta=np.pi/180,threshold=1,minLineLength=minLineLength,maxLineGap=maxLineGap)
lines2 = cv2.HoughLinesP(thresh,threshold=10,maxLineGap=maxLineGap)
lines3 = cv2.HoughLinesP(thresh2,maxLineGap=maxLineGap)

# Stack the detections
Lines = np.vstack([lines1[0],lines2[0],lines3[0]])

# Draw the Lines
for row in range(Lines.shape[0]):
    x1,y1,x2,y2 = Lines[row,0],Lines[row,1],2],3]
    cv2.line(image,(x1,y1),(x2,y2),(0,0),2)

# Visualize results
cv2.imshow('lines',image)
cv2.waitKey(0)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...