如何强制 tesseract 从左到右阅读,Python

How to force tesseract to read left to right, Python

我有一个条形图,我想从中提取数据点。

但是,当 tesseract 读取图像时,它是从左到右和从上到下读取的。从我的输出中,您可以看到以从左到右的顺序读取具有相同高度的条:

60.8
58.8 58.8 
58.1
56.9 56.8
54.6 547
51.8 52.2
51:3 
48.7

Jul 2019 Oct 2019 Jan 2020 Apr 2020

我不想同时读取相同高度的条。相反,我希望 tesseract 只从左到右阅读(而不是它似乎正在做的额外的从上到下)。

我在另一个 post 中读到图像应该转置以实现此目的,但如果我这样做,tesseract 似乎无法读取转置图像。

您的任何见解都会有所帮助。谢谢

from PIL import Image, ImageEnhance, ImageFilter
#from pytesseract import image_to_string
import pytesseract
import cv2


pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
from pytesseract import image_to_string
im = Image.open(r'C:\Users\Root\im.png')
print(im)

#Resizing and Transposing
new_size = tuple(6*y for y in im.size)
im = im.resize(new_size, Image.ANTIALIAS)
im  = im.transpose(Image.ROTATE_90)
im.save(r'C:\Users\Root\test.png', 'PNG')

#Grayscale for enhanced reading quality
im = cv2.imread(r'C:\Users\Root\test.png')
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

print(image_to_string(gray, lang='eng'))

不幸的是,这不是最便携的解决方案,但如果您要有很多像这样的条形图,您可以将图像从左到右切成小块,然后 运行 每个切片上的 OCR 分别:

width, height = im.size
numBars = 12
bottomLabelHeight = 100
leftOffset = 10
rightOffset = 20
barWidth = (width - leftOffset - rightOffset) // numBars
for i in range(leftOffset + barWidth, width - rightOffset, barWidth):
    left = i - barWidth
    right = i
    top = 0
    bottom = height - bottomLabelHeight
    bar = im.crop((left, top, right, bottom)).convert('L') # Convert to grayscale
    # bar.show() # uncomment to show bar for testing

    # Need digits whitelist for OCR to work properly
    value = image_to_string(bar, lang='eng', 
        config='--psm 10 --oem 3 -c tessedit_char_whitelist=.0123456789')
    print(value)

    # Read label for bar
    top = height - bottomLabelHeight
    bottom = height
    label = im.crop((left, top, right, bottom)).convert('L')
    print(image_to_string(label, lang='eng'))

输出:

60.8

58.1
Jul 2019
58.8

56.9

51.8
Oct 2019
54.6

56.8

58.8
Jan 2020
54.2

51.3

52.2
Apr 2020
48.7