python 中的数字识别(OpenCV 和 pytesseract)

TL-*_*-Py 2 python ocr opencv machine-learning image-processing

我目前正在尝试从小屏幕截图中检测数字。然而,我发现准确性相当差。我一直在使用 OpenCV,图像以 RGB 格式捕获并转换为灰度,然后使用全局值执行阈值处理(我发现自适应效果不太好)。

下面是其中一个数字的灰度示例,后面是阈值保持后的图像示例(数字范围为 1-99)。请注意,图像的初始屏幕截图非常小,因此被放大。

在此输入图像描述

在此输入图像描述

任何有关如何使用 OpenCV 或完全不同的系统提高准确性的建议都非常感谢。下面包含一些代码,该函数传递数字的 RGB 屏幕截图。

def getNumber(image):
    image = cv2.resize(image, (0, 0), fx=3, fy=3)
    img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    thresh, image_bin = cv2.threshold(img, 125, 255, cv2.THRESH_BINARY)

    image_final = PIL.Image.fromarray(image_bin)

    txt = pytesseract.image_to_string(
        image_final, config='--psm 13 --oem 3 -c tessedit_char_whitelist=0123456789')
    return txt
Run Code Online (Sandbox Code Playgroud)

小智 5

这是我可以改进的地方,使用 otsu treshold 比给出任意值更有效地将文本与背景分开。超立方体在白色背景上的黑色文本上效果更好,而且我还添加了填充,因为超立方体很难识别距离边框太近的字符。

这是最终图像 [final_image][1] 和 pytesseract 设法读取“46”

import cv2,numpy,pytesseract
def getNumber(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # Otsu Tresholding automatically find best threshold value
    _, binary_image = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)
    
    # invert the image if the text is white and background is black
    count_white = numpy.sum(binary_image > 0)
    count_black = numpy.sum(binary_image == 0)
    if count_black > count_white:
        binary_image = 255 - binary_image
        
    # padding
    final_image = cv2.copyMakeBorder(image, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=(255, 255, 255))
    txt = pytesseract.image_to_string(
        final_image, config='--psm 13 --oem 3 -c tessedit_char_whitelist=0123456789')

    return txt
Run Code Online (Sandbox Code Playgroud)

函数执行如下:

>> getNumber(cv2.imread(img_path))
Run Code Online (Sandbox Code Playgroud)

编辑:请注意,您不需要此行:

image_final = PIL.Image.fromarray(image_bin)
Run Code Online (Sandbox Code Playgroud)

因为你可以将 numpy 数组格式的图像传递给 pytesseractr (cv2 使用),而 Tesseract 的精度仅在 35 像素以下的字符(而且更大,35px 高度实际上是最佳高度)下下降,所以我没有调整它的大小。[1]: https: //i.stack.imgur.com/OaJgQ.png