阅读文本时出现 Pytesseract 随机错误

Pytesseract random bug when reading text

我正在为视频游戏创建一个机器人,我必须阅读屏幕上显示的一些信息。鉴于信息始终位于同一位置,我可以毫无问题地截取屏幕截图并将图片裁剪到正确的位置。

90% 的时间,识别是完美的,但有时它会 return 一些看起来完全随机的东西(见下面的例子)。

我试过将图片变成黑白的,但没有成功,并尝试更改pytesseract配置(config = ("-l fra --oem 1 --psm 6"))

def readScreenPart(x,y,w,h):
    monitor = {"top": y, "left": x, "width": w, "height": h}
    output = "monitor.png"
    with mss.mss() as sct:
        sct_img = sct.grab(monitor)        
        mss.tools.to_png(sct_img.rgb, sct_img.size, output=output)

    img = cv2.imread("monitor.png")
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cv2.imwrite("result.png", img)
    config = ("-l fra --oem 1 --psm 6")

    return pytesseract.image_to_string(img,config=config)

示例:这张图片产生了一个错误,它 return 是字符串 "IRPMV/LEIILK"

另一张图片

现在我不知道问题出在哪里,因为它不仅仅是一个错误的字符,而是一个完全随机的结果..

感谢您的帮助

正如评论所说,这是关于你的文字和背景颜色。 Tesseract 基本上对深色背景上的浅色文本毫无用处,这是我在将其提供给 tesseract 之前应用于任何文本图像的几行:

# convert color image to grayscale
grayscale_image = cv2.cvtColor(your_image, cv2.COLOR_BGR2GRAY)

# Otsu Tresholding method find perfect treshold, return an image with only black and white pixels
_, binary_image = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)

# we just don't know if the text is in black and background in white or vice-versa
# so we count how many black pixels and white pixels there are
count_white = numpy.sum(binary > 0)
count_black = numpy.sum(binary == 0)

# if there are more black pixels than whites, then it's the background that is black so we invert the image's color
if count_black > count_white:
    binary_image = 255 - binary_image

black_text_white_background_image = binary_image

现在无论原始图像的颜色是什么颜色,您都可以确保在白色背景上有黑色文本,而且如果字符的高度为 35 像素,Tesseract 是(奇怪的)最有效的,较大的字符不会显着降低精度,但仅仅缩短几个像素就会使 tesseract 变得无用!

预处理是把图片扔进Pytesseract之前的一个重要步骤。通常,您希望所需的文本为黑色,背景为白色。目前,您的前景文字是绿色而不是白色。这是修复格式的简单过程

  • 将图像转换为灰度
  • 大津获取二值图像的阈值
  • 反转图像

原图

大津的门槛

反转图像

Pytesseract 的输出

122 Vitalité

其他图片

200 Vitalité

在反转图像之前,最好对文本执行 morphological operations 到 smooth/filter。但是对于你的图片,文字不需要额外的平滑处理

import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

image = cv2.imread('3.png',0)
thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
result = 255 - thresh

data = pytesseract.image_to_string(result, lang='eng',config='--psm 6')
print(data)

cv2.imshow('thresh', thresh)
cv2.imshow('result', result)
cv2.waitKey()