我想使用轮廓检测 按从出现的顺序对从图像中提取的单词进行排序

问题描述 投票:0回答:1

我正在制作OCR,正在使用轮廓检测​​,我已经提取了单词并绘制了边界框,但是问题是当我裁剪单个单词时,它们没有按顺序排列。我已经尝试过在link中提到的排序方法来对轮廓进行排序,但是它们在对象上的效果最佳,但是在我的情况下,我想使顺序更精确。有时排序不是最好的解决方案,它改变了单词的模式,因为不同的单词在同一行中具有不同大小的边框,并且'x'和'y'的值也随之变化。现在在同一行中,带有大包围盒的单词被视为一个类别,而带有小包围盒的单词被视为另一类别,它们以相同的方式进行排序,这就是要排序的代码。

    sorted_ctrs=sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0] + cv2.boundingRect(ctr)[1] * 
    im.shape[1] )

image of extracted bounded boxesthis is what I get after cropping from sorted contours

还有其他方法可以整理我的单词,使之有意义吗?

sorting opencv ocr contour bounding-box
1个回答
0
投票

您应该先分开不同的行。完成此操作后,您可以简单地从左到右处理轮廓(从x = 0到x = width排序)

首先在黑色背景上绘制找到的轮廓。接下来,对行求和。没有单词/轮廓的行的总和将为0。文本行之间通常会有一些空格,总和=0。您可以使用它来查找文本的每一行的最小和最大高度值。

要找到单词的顺序,请先在第一行的y范围内寻找轮廓,然后寻找最低的x。

输入:enter image description here

结果:enter image description here

代码:

import cv2
import numpy as np
# load image and get dimensions
img = cv2.imread('xmple2.png',0)
h,w = img.shape[:2]
# sum all rows
sumOfRows = np.sum(img, axis=1)

# loop the summed values
startindex = 0
lines = []
compVal = True
for i, val in enumerate(sumOfRows):
    # logical test to detect change between 0 and > 0
    testVal = (val > 0)
    if testVal == compVal:
            # when the value changed to a 0, the previous rows
            # contained contours, so add start/end index to list
            if val == 0:
                lines.append((startindex,i))
            # update startindex, invert logical test
                startindex = i+1
            compVal = not compVal

# example: for each line found, create and display a subimage
for y1,y2 in lines:
    line = img[y1:y2,0:w]
    cv2.imshow('Img',line)
    cv2.waitKey(0)

cv2.destroyAllWindows()
© www.soinside.com 2019 - 2024. All rights reserved.