如何使用OpenCV Python检测并增加图像文本中两行之间的间距?

4

enter image description here

如果初始图像如上所示,那么我可以成功地在两行之间引入空格,并得到下面的图像。 enter image description here 使用以下代码:
import os
import cv2
def space_between_lines_and_skewness_correction(file_path):
    img = cv2.imread(os.path.expanduser(file_path))
    grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    th, threshed = cv2.threshold(grey, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
    pts = cv2.findNonZero(threshed)
    ret = cv2.minAreaRect(pts)
    (cx, cy), (w, h), ang = ret

    if w < h:
        w, h = h, w
        ang += 90
    M = cv2.getRotationMatrix2D((cx, cy), ang, 1.0)
    rotated = cv2.warpAffine(threshed, M, (img.shape[1], img.shape[0]))
    hist = cv2.reduce(rotated, 1, cv2.REDUCE_AVG).reshape(-1)
    th = 2
    H, W = img.shape[:2]
    delimeter = [y for y in range(H - 1) if hist[y] <= th < hist[y + 1]]
    arr = []
    y_prev = 0
    y_curr = 0
    for y in delimeter:
        y_prev = y_curr
        y_curr = y
        arr.append(rotated[y_prev:y_curr, 0:W])

    arr.append(rotated[y_curr:H, 0:W])
    space_arr = np.zeros((10, W))
    final_img = np.zeros((1, W))

    for im in arr:
        v = np.concatenate((space_arr, im), axis=0)
        final_img = np.concatenate((final_img, v), axis=0)
    return final_img

上述代码将消除偏斜并引入空间。 但在某些情况下,上述代码无效。 这些情况包括:enter image description here 图像的输出为 enter image description here 如何处理此类情况? 注意: 我尝试将其调整为更大的尺寸,并进行逐像素迭代和构建自定义算法以解决此问题,但这需要大量时间来解决,并且有时会出现内存错误。 请注意:上述代码的输入实际上是此处提供的图像的反向图像(白色背景)。
1个回答

2
也许这可以帮助你:
def detect_letters(img):

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

    # just to remove noise
    thresh_val, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    num_labels, _, stats, centroids = cv2.connectedComponentsWithStats(thresh)

    for i in range(num_labels):
        leftmost_x = stats[i, cv2.CC_STAT_LEFT]
        topmost_y = stats[i, cv2.CC_STAT_TOP]
        width = stats[i, cv2.CC_STAT_WIDTH]
        height = stats[i, cv2.CC_STAT_HEIGHT]

        # enclose all detected components in a blue rectangle
        cv2.rectangle(img, (leftmost_x, topmost_y), (leftmost_x + width, topmost_y + height), (255, 0, 0), 2)

    cv2.imshow("window", img)
    cv2.waitKey(0) & 0xFF

输入:

enter image description here

输出:

enter image description here

以上解决方案的主要目的是获取每个字母周围的包围矩形。

现在,您只需要将所有这些字母向上或向下移动到您想要的位置。

例如,请参见以下链接中足球如何移动:https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_core/py_basic_ops/py_basic_ops.html

由于您现在知道每个字母的最顶部和最底部y坐标,因此可以看出它们当前相距多远,如果它们非常接近,则像上面链接中那样移动字母。

同一行的字母的顶点坐标或质心之间的差异非常小。您可以设置容差范围以识别所有这些字母。

如果有任何问题,请随时提问。


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