如何使用 PyTesseract OCR 从图像中读取数字?

How to read digits from an image with PyTesseract OCR?

我正在尝试让 PyTesseract OCR 从这张裁剪得很好的简单图像中读取数字,但由于某些原因,它无法做到这一点。

from PIL import Image
import pytesseract as p

def obtain_balance(a):
    im = Image.open(a)
    width,height = im.size
    a = 300*5 - 120
    # print(width,height)
    left = 155+a
    top = 5
    right = 360+a 
    bottom = 120
    m1 = im.crop((left, top, right, bottom)) 
    text = p.image_to_string(m1,lang='eng',config='--psm 13 --oem 3 -c tessedit_char_whitelist=0123456789').split()
    print(text)
    m1.show()
    return text

obtain_balance('cur.jpg')

输出:

[]

执行 OCR 时,对图像进行预处理很重要,这样所需的前景文本为黑色,背景为白色。为此,我们可以使用 OpenCV 对图像进行 Otsu 阈值处理并获得二值图像。然后我们应用轻微的高斯模糊来平滑图像,然后再将其放入 Pytesseract。我们使用 --psm 6 配置将图像视为单个统一的文本块。有关更多配置选项,请参阅


这是预处理图像和 Pytesseract 的结果

PRACTICE ACCOUNT
,047.26~ i

代码

import cv2
import pytesseract

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

image = cv2.imread('1.png', 0)
thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
thresh = cv2.GaussianBlur(thresh, (3,3), 0)
data = pytesseract.image_to_string(thresh, lang='eng',config='--psm 6')
print(data)

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