0

我正在尝试使用Hough lines transform检测报纸文章的预处理二进制图像的背景线。

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

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

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,255,0),2)
    
cv.imshow('lines',image)
path='../outputs'
cv.imwrite(os.path.join(path , 'line.jpg'), image)
cv.waitKey(0)

预期的输出是这样的:在此处输入图像描述

但是我从上面的代码得到的输出是这样的: 在此处输入图像描述

输入图像为: 在此处输入图像描述

4

1 回答 1

1

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

结果

#------------------#
# 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, 150, 255, 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,rho=np.pi/180,theta=np.pi/180,threshold=10,minLineLength=minLineLength,maxLineGap=maxLineGap)
lines3 = cv2.HoughLinesP(thresh2,rho=np.pi/180,theta=np.pi/180,threshold=10,minLineLength=minLineLength,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], Lines[row, 2], Lines[row, 3]
    cv2.line(image,(x1,y1),(x2,y2),(0,255,0),2)

# Visualize results
cv2.imshow('lines',image)
cv2.waitKey(0)
于 2021-02-24T19:23:26.057 回答