使用openCV确定文本中的分隔线

2024-05-15 00:09:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检测扫描文档中的分割线,而不是使用cv2.Canny,而是使用cv2.threshold来获得一个非常干净的预处理图像。但是,我的cv2.HoughLines参数可能不正确,并且在最终输出中出现了混乱。而线条并没有以设定的颜色出现。你知道吗

我的代码是:

import cv2
import numpy as np
from matplotlib import pyplot as plt

## (1) read
img = cv2.imread("q11.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.figure(figsize=(17,17))
plt.imshow(gray,cmap='gray')

## (2) threshold
th, threshed = cv2.threshold(gray, 200, 20, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)
plt.figure(figsize=(15,15))
plt.imshow(threshed,cmap='gray')

## (3) HoughLines
lines = cv2.HoughLines(threshed,rho=1,theta=np.pi/180,threshold = 800)
for i in range(len(lines)):
    for rho,theta in lines[i]:
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a*rho
        y0 = b*rho
        x1 = int(x0 + 1000*(-b))
        y1 = int(y0 + 1000*(a))
        x2 = int(x0 - 1000*(-b))
        y2 = int(y0 - 1000*(a))
    cv2.line(threshed,(x1,y1),(x2,y2),(0,0,255),2)

plt.figure(figsize=(10, 10))
plt.subplot(111),plt.imshow(threshed)
plt.title('hough'), plt.xticks([]), plt.yticks([])

原图为: enter image description here

经过cv2.thresholdcv2.THRESH_BINARY_INV|cv2.THRESH_OTSU我得到: enter image description here

我想要: enter image description here

我得到的是:

enter image description here


Tags: importthresholdnppltcv2intfigureimshow
1条回答
网友
1楼 · 发布于 2024-05-15 00:09:11

这里有一个简单的方法

  • 将图像转换为灰度和高斯模糊
  • 阈值图像
  • 扩张以增强轮廓
  • 检测线

门槛

下一步,我们扩展以增强轮廓,然后使用^{}来检测线条。你提到

The lines don`t show as the set color

这是因为您试图在二值图像(阈值图像)上绘制线。因为它只有一个通道,所以像素只有白色或黑色。因此它不会显示颜色。你必须把它画在彩色图像上

import cv2
import numpy as np

image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)

thresh = cv2.threshold(blur,190, 255,cv2.THRESH_BINARY_INV)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (5,5))
dilate = cv2.dilate(thresh, kernel, iterations=1)

minLineLength = 10
maxLineGap = 200
lines = cv2.HoughLinesP(dilate,1,np.pi/180,100,minLineLength,maxLineGap)
for line in lines:
    for x1,y1,x2,y2 in line:
        cv2.line(image,(x1,y1),(x2,y2),(0,0,255),3)

cv2.imshow('image', image)
cv2.imshow('thresh', thresh)
cv2.waitKey()

相关问题 更多 >

    热门问题