Home > Software design >  Using pytesseract to get numbers from an image
Using pytesseract to get numbers from an image

Time:06-24

I'm trying to take an image that's just a number 1-10 in a bubble font and use pytesseract to get the number. picture in question

Here is an article that makes this process seem straightforward: https://towardsdatascience.com/read-text-from-image-with-one-line-of-python-code-c22ede074cac

lives = pyautogui.locateOnScreen('pics/lives.png', confidence = 0.9)

ss = pyautogui.screenshot(region=(lives[0] lives[2],lives[1],lives[2]-6,lives[3]))
ss.save('pics/tempLives.png')
img = cv2.imread('pics/tempLives.png')
cv2.imwrite('pics/testPic.png',img)

test = pytesseract.image_to_string(img)
print(test)

I know 'img' is the same as the image provided because I've used ss.save cv2.imwrite to see it.

I suppose my question is why it works so well in the article yet I cannot manage to get anything to print? I suppose the bubble font makes it trickier, but in the article those blue parentheses were read easily, so that makes me think this font wouldn't be too hard. Thanks for any help!

CodePudding user response:

There are many cases when PyTesseract fails to recognize the text, and in some cases we have to give it some hints.

In the specific image you have posted, we better add config=" --psm 6" argument.

According to Tesseract documentation regarding PSM:

6 Assume a single uniform block of text.


Here is a code sample that manages to identify the text from the posted image:

import cv2
import pytesseract
#pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'  # May be required when using Windows

img = cv2.imread('pics/testPic.png')  # Reading the input image (the PNG image from the posted question).

text = pytesseract.image_to_string(img, config=" --psm 6")  # Execute PyTesseract OCR with "PSM 6" configuration (Assume a single uniform block of text)

print(text)  # Prints the text (prints 10).

Note:
The OCR is not always working, and there are many techniques to improve the OCR accuracy.

  • Related