首页 > 解决方案 > 光学字符识别。字符分割阶段

问题描述

我正在尝试实现 OCR 系统的其中一个阶段。字符分割阶段。代码如下所示。代码很简单:

假设每个选定的轮廓都是一个符号。

该算法的结果并不令人满意。有时,角色很突出。有时只突出显示部分字符,有时突出显示几个字符。请帮助代码,我真的希望它能够正确突出显示字符。

更新 1.我正在尝试为不同的字体实现字符分割系统。原来不同字体的腐蚀和膨胀操作没有通用的参数

测试图像:

测试图像

字符选择1的结果(字符的小部分):

字符的小部分

字符选择2的结果(字符的大部分): 双字符

完整结果(字符的所有部分):

完整结果

import cv2
import numpy as np

def letters_extract(image_file):
    img = cv2.imread(image_file)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

    img_dilate = cv2.dilate(thresh, np.ones((1, 1), np.uint8), iterations=1)
    # img_erode = cv2.erode(img_dilate, np.ones((3, 3), np.uint8), iterations=1)

    # Get contours
    contours, hierarchy = cv2.findContours(img_dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

    letters = []
    for idx, contour in enumerate(contours):
        (x, y, w, h) = cv2.boundingRect(contour)
        if hierarchy[0][idx][3] == 0:
            letter_crop = gray[y:y + h, x:x + w]       
            letters.append(letter_crop)
            cv2.imwrite(r'D:\projects\proj\test\tnr\{}.png'.format(idx), letter_crop)

    return letters

letters_extract(r'D:\projects\proj\test\test_tnr.png')

标签: pythonopencvcharacterocr

解决方案


运行您的代码(为调试而稍作修改),它看起来相当不错(我只更改了膨胀掩码):

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


def letters_extract(image_file):
    img = cv2.imread(image_file)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
    plt.figure(figsize=(20, 20))
    plt.imshow(thresh)
    plt.show()

    img_dilate = cv2.erode(thresh, np.ones((2,1), np.uint8))
    plt.figure(figsize=(20, 20))
    plt.imshow(img_dilate)
    plt.show()

    contours, hierarchy = cv2.findContours(img_dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

    im_with_aabb = img.copy()
    for idx, contour in enumerate(contours):
        (x, y, w, h) = cv2.boundingRect(contour)
        if hierarchy[0][idx][3] == 0:     
            color = (255, 0, 0)
            thickness = 1
            im_with_aabb = cv2.rectangle(im_with_aabb, (x,y), (x+w,y+h), color, thickness)

    return im_with_aabb

im_with_aabb = letters_extract('test.png')
plt.figure(figsize=(20, 20))
plt.imshow(im_with_aabb)
plt.show()

但是几个字符仍然存在问题。如果您的输入图像看起来不错(不同位置的相同字符之间没有高可变性),我可以建议将每个字符作为模板进行模板匹配。

如果数据具有很高的可变性,那么您应该使用像tesseract这样的预训练 NN 。


推荐阅读