1

I am trying to detect the text from the images but fail due to some unknown reasons.

import pytesseract as pt
from PIL import Image
import re
image = Image.open('sample.jpg')
custom_config = r'--oem 3 --psm 7 outbase digits'
number = pt.image_to_string(image, config=custom_config)
print('Number: ', number)
Number:  0 50 100 200 250 # This is the output that I am getting.
Expected --> 0,0,0,0,0,1,0,8
scee
  • 15
  • 6
  • Hi @scee welcome to SO! You mention that the conversion fails. Can you provide some more details as to what error messages (if any) you got? What is your OS ? – vyi May 17 '21 at 07:23
  • @vvy, I am using macos. The conversion is not necessary fail but it's producing the wrong output. I will update the question. – scee May 17 '21 at 09:04
  • before sending it to tesseract, try use some morphological operations such as thresholding. tesseract works better in black/white images. – Tyr May 17 '21 at 09:11

1 Answers1

0

OCR using tesseract on crude/raw image inputs might not give you expected result. For the given image, a somewhat better result can be obtained using grayscale conversion followed by thresholding operation

enter image description here

To perform the conversion and thresholding operation you may use ImageMagick as follows:

$ convert input_image.jpg -colorspace gray grayscale_image.jpg
$ convert grayscale_image.jpg -threshold 45% thresholded_image.jpg
$ convert thresholded_image.jpg -morphology Dilate Rectangle:4,3 dilated_binary.jpg
$ python run_tesseract.py
 00000109

A more robust approach to OCR is via training the tesseract engine discussed here

vyi
  • 1,078
  • 1
  • 19
  • 46
  • Thank you @vvy. I am wondering if there is a way to execute in just python file. – scee May 18 '21 at 00:16
  • In that case, **OpenCV** will help you achieve the same. [Something like this](https://nanonets.com/blog/ocr-with-tesseract/#preprocessingfortesseract) – vyi May 18 '21 at 06:33