MollyBFL
MollyBFL

Reputation: 41

Recognize specific numbers from table image with Pytesseract OCR

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

Upvotes: 3

Views: 1495

Answers (1)

nathancy
nathancy

Reputation: 46600

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()

Upvotes: 1

Related Questions