在OpenCV中找到包含文本行的轮廓

8
我正在编写一个文本识别程序,但在轮廓排序方面遇到了问题。该程序对于一行文本可以正常工作,但是当涉及整个文本块时,我的程序在80%的情况下无法检测到文本行。有什么非常有效的方法可以提取一行文本,然后逐个提取所有其他行吗?
我想要实现的目标:

enter image description here

1个回答

25

实现这个过程需要以下步骤:

  1. 找到最优二值化图像的阈值。我使用了Otsu阈值。
  2. 找到适当的形态学操作,使其在水平方向上形成一个单一的区域。选择宽度大于高度的核。
  3. 在结果轮廓上绘制边界框。

更新

以下是实现方法:

x = 'C:/Users/Desktop/text.jpg' 

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

#--- performing Otsu threshold ---
ret,thresh1 = cv2.threshold(gray, 0, 255,cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)
cv2.imshow('thresh1', thresh1)

enter image description here

#--- choosing the right kernel
#--- kernel size of 3 rows (to join dots above letters 'i' and 'j')
#--- and 10 columns to join neighboring letters in words and neighboring words
rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 3))
dilation = cv2.dilate(thresh1, rect_kernel, iterations = 1)
cv2.imshow('dilation', dilation)

enter image description here

#---Finding contours ---
_, contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

im2 = img.copy()
for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        cv2.rectangle(im2, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('final', im2)

enter image description here


@Mithor 对不起,我只有Python版本。 - Jeru Luke
3
很棒。我喜欢那个用宽卷积核膨胀字母和单词来连接的技巧。 - bfris
2
谢谢。这节省了我很多时间。 - Anton Kot
有没有办法以字符串格式提取这个文本? - Rudra shah
1
@Rudrashah 你可以对提取的部分执行OCR,以获取字符串格式的结果。 - Jeru Luke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接