PyTesseract - Text broken by horizontal white lines

Viewed 394

It is a classic PyTesseract problem of noisy image scanning. However, in this case dot matrix printer is printing some horizontal white lines in the text. Attached are some samples. I am not sure what kind of preprocessing will improve the scanning of the text.
Sample image
Using below command following output comes for below sample:

tesseract test.png stdout  --psm 6 --dpi 120

Output: (Expected is "RVC 64.80%" )

PRVG
64.5056"

Sample 2
For Above image pytesseract gives

152.00 KILOGRAW
817.51 USO

and the expected is - 152.00 KILOGRAM 617.51 USD

I know the images are noisy so please do not post obvious answer that as the images are noisy so the output is bad. As I always get same text from the printer so I can apply same type of preprocessing.

1 Answers

The first one picture,handle code:

from PIL import Image
import numpy as np
import pytesseract
import time
from collections import Counter

img = Image.open('OCR.png').convert('L')
pixelArray = img.load()
threshold = 240
table = []
for y in range(img.size[1]): # binaryzation
    List = []
    for x in range(img.size[0]):
        if pixelArray[x,y] < threshold:
            List.append(0)
        else:
            List.append(256)
    table.append(List)

img = Image.fromarray(np.array(table))
img.show()

def operation(image):
    resultList = []
    pixelList = image.load()
    flag = False
    for y in range(image.size[1]):
        temp = []
        linePixel = 0
        for x in range(image.size[0]):
            if not pixelList[x,y]:
                linePixel += 1
            temp.append(pixelList[x,y])
        if linePixel >= 35: # judge the black dot in one line
            flag = True
            resultList.append(temp)
        elif flag:
            # resultList.append([0]*image.size[0]) # to check the handling lines
            flag = False
        else:
            resultList.append([256] * image.size[0])
    return Image.fromarray(np.array(resultList))

for i in range(6):
    img = operation(img)

img.show()
print(pytesseract.image_to_string(img,config='--psm 6'))

The first measure for handling(binaryzation):

enter image description here

The second measure is to remove the white line(judge black pixels in one line):

enter image description here

And finally,the result is:

"RVC
64.80%"
Related