3

I want to read a column of number from an attached image (png file).

click to see image

My code is

import cv2
import pytesseract
import os

img = cv2.imread(os.path.join(image_path, image_name), 0)
config= "-c 
        tessedit_char_whitelist=01234567890.:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

pytesseract.image_to_string(img, config=config)

This code gives me the output string: 'n113\nun\n1.08'. As we can see, there are two problems:

  1. It fails to recognize a decimal point in 1.13 (see attached picture).
  2. It totally cannot read 1.11 (see attached picture). It just returns 'nun'.

What is a solution to these problems?

Bests

nathancy
  • 42,661
  • 14
  • 115
  • 137
MollyBFL
  • 41
  • 4

1 Answers1

1

You need to preprocess the image. A simple approach is to resize the image, convert to grayscale, and obtain a binary image using Otsu's threshold. From here we can apply a slight gaussian blur then invert the image so the desired text to extract is in white with the background in black. Here's the processed image ready for OCR

Result from OCR

1.13
1.11
1.08

Code

import cv2
import pytesseract
import imutils

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

# Resize, grayscale, Otsu's threshold
image = cv2.imread('1.png')
image = imutils.resize(image, width=400)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Blur and perform text extraction
thresh = 255 - cv2.GaussianBlur(thresh, (5,5), 0)
data = pytesseract.image_to_string(thresh, lang='eng',config='--psm 6')
print(data)

cv2.imshow('thresh', thresh)
cv2.waitKey()
nathancy
  • 42,661
  • 14
  • 115
  • 137
  • Just wondering (1) why you have to resize am image such that width=400? (2) why you set ksize parameter in GaussianBlur to be (5, 5)? – MollyBFL Feb 04 '20 at 07:50
  • The image is enlarged to help the OCR process, the amount that you enlarge the image is arbitrary. The Gaussian blur kernel is set to `(5,5)` to help smooth the image and remove tiny dots before thresholding. Its just a typical kernel size. Other sizes that can work are `(3,3)` or `(7,7)` depending on the image and the amount of noise present – nathancy Feb 04 '20 at 21:08