2

I am performing some OCR operation with tesseract. I have written a simple python wrapper for that. The problem is I am getting unwanted line gaps between sentences in the end text file, which I need to remove programmatically. for example:

1 tbsp peanut or corn oil, plus a little
extra for Cooking the scallops

2 tbsp bottled mild or medium Thai
green curry paste
2 tbsp water

2 tsp light soy sauce

Please note some line gaps--which I need to remove. Please share some tips if you experienced similar problems. Thank you.

Here is the wrapper:

from PIL import Image
import subprocess
import os
from wand.image import Image
import markdown2
from textblob import TextBlob

import util
import errors

tesseract_exe = "tesseract" # Name of executable to be called at command line
scratch_text_name_root = "temp" # Leave out the .txt extension
cleanup_scratch_flag = True # Temporary files cleaned up after OCR operation
pagesegmode = "-psm 0"


def call_tesseract(input_file, output_file):
    args = [tesseract_exe, input_file, output_file, pagesegmode]
    proc = subprocess.Popen(args)
    retcode = proc.wait()
    if retcode !=0:
        errors.check_for_errors()


def retrieve_text(scratch_text_name_root):
    inf = file(scratch_text_name_root + '.txt')
    text = inf.read()
    inf.close()
    return text

def write_to_file(filename, string):
    File = open(filename, 'w')
    File.write(string)
    File.close()


def image_to_string(filename):
    try:
        call_tesseract(filename, scratch_text_name_root)
        text = retrieve_text(scratch_text_name_root)
    finally:
        try:
            os.remove(scratch_text_name_root)
        except OSError:
            pass

        return text    

filename = "book/0001.bin.png"
text = image_to_string(filename)
print "writing to file"
write_to_file("0002.bin.txt", text)
Anay Bose
  • 880
  • 1
  • 14
  • 24

1 Answers1

2

Im not sure why tesseract gives you these empty lines, but maybe a simple workaround help you:

Just remove these empty lines. There are many ways to do this, for example look here: https://stackoverflow.com/a/3711884/4175009

or here:

https://stackoverflow.com/a/2369474/4175009

These solutions both suppose that you read the file line by line.

I like this solution because you can use it driectly at your finished string and it handles OS differences in line endings (\n, \n\r, \r\n).

Community
  • 1
  • 1
Entwicklerpages
  • 126
  • 1
  • 7