'Trouble recognizing digits in pytesseract

I wanna recognize images like these: (image1) (image2)

But im having trouble doing so with pytesseract

My Code:

import pytesseract
from PIL import Image


img = Image.open('crop.png')

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

I also tried this:

import cv2
import pytesseract

img = cv2.imread("crop.png")
img = cv2.bitwise_not(img)
_, binary = cv2.threshold(img, 150, 255, cv2.THRESH_BINARY)
txt = pytesseract.image_to_string(binary)
print(txt)

this time i was able to recognize Image1 but not Image2



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source