2

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

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

我尝试将图片变成黑白但没有成功,并尝试更改 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)

示例:此图片生成一个错误,它返回字符串“IRPMV/LEIILK”

在此处输入图像描述

另一个图像

在此处输入图像描述

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

谢谢你的帮助

4

2 回答 2

1

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

  • 将图像转换为灰度
  • 获得二值图像的 Otsu 阈值
  • 反转图像

原始图像

在此处输入图像描述

大津的门槛

在此处输入图像描述

反转图像

在此处输入图像描述

Pytesseract 的输出

第122章

其他图片

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

200 活力

在反转图像之前,执行形态学操作以平滑/过滤文本可能是个好主意。但是对于您的图像,文本不需要额外的平滑

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()
于 2019-09-20T20:30:13.703 回答
0

正如评论所说,这与您的文本和背景颜色有关。对于深色背景上的浅色文本,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 无用!

于 2019-09-20T13:05:57.027 回答