【问题标题】:How to read numbers on screen efficiently (pytesseract)?如何有效地读取屏幕上的数字(pytesseract)?
【发布时间】:2023-01-31 22:28:24
【问题描述】:

我正在尝试读取屏幕上的数字,为此我正在使用 pytesseract。问题是,尽管它有效,但它工作缓慢并且根本没有给出好的结果。例如,这张图片:

我可以制作这个阈值图像:

它读取 5852 而不是 585,这是可以理解的,但有时使用不同的阈值可能会更糟。例如,它可以将 1 000 000 读取为 1 aaa eee,或者将 585 读取为 5385r(是的,它甚至可以无缘无故地添加字符)

没有任何方法可以强制 pytesseract 只读取数字或简单地使用比 pytesseract 更好用的东西吗?

我的代码:

from PIL import Image
from pytesseract import pytesseract as pyt
import test
pyt.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'

def tti2(location) :
    image_file = location
    im = Image.open(image_file)
    text = pyt.image_to_string(im)
    print(text)
    for character in "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ*^&\n" :
        text = text.replace(character, "")
    return text

test.th("C:\\Users\\Utilisateur\\Pictures\\greenshot\\flea market sniper\\TEST.png")
print(tti2("C:\\Users\\Utilisateur\\Pictures\\greenshot\\flea market sniper\\TESTbis.png"))

“测试”代码(用于阈值):

import cv2
from PIL import Image

def th(Path) :
    img = cv2.imread(Path)
    # If your image is not already grayscale :
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    threshold = 60 # to be determined
    _, img_binarized = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)
    pil_img = Image.fromarray(img_binarized)
    Path = Path.replace(".png","")
    pil_img.save(Path+"bis.png")

【问题讨论】:

    标签: python automation python-tesseract


    【解决方案1】:

    一种强制 pytesseract 只读数字的方法可以使用仅包含数字值的 tessedit_char_whitelist 配置来完成。 您可以尝试使用 Tesseract 文档改进结果。 Tesseract - Improving the quality of the output

    另外我建议你使用:

    • 背景为白色,字符字体颜色为黑色。
    • 选择所需的 tesseract psm 模式。在之前的案例中,我使用 7 psm 模式将图像视为单个文本行。
    • 使用 tessedit_char_whitelist 配置仅指定您要搜索的字符。

    考虑到这一点,这里是代码:

    import cv2
    import numpy as np
    import pytesseract
    
    pytesseract.pytesseract.tesseract_cmd = r'C:Program FilesTesseract-OCR	esseract'
    originalImage = cv2.imread('1.png')
    grayImage = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY)
    (_, blackAndWhiteImage) = cv2.threshold(grayImage, 127, 255, cv2.THRESH_BINARY_INV)
    text = pytesseract.image_to_string(blackAndWhiteImage, config="--psm 7 --oem 3 -c tessedit_char_whitelist=0123456789")
    print('Text: ', text)
    cv2.imshow('Image result', blackAndWhiteImage)
    
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    和期望的结果: Result image

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多