'Extract text from image using pytesseract in two-tones background
I'm trying to extract text from an image using pytesseract on Python. This is the image where I want to extract the text:
This is the image after applying threshold:
Console Output:
20 hours
20 hours
Bhours
This is the code I'm using:
from pytesseract import *
import cv2
path = r"path where image is located" #path of image
folderPath = r"path for saving output image"
grey_image = cv2.imread(path,0) #import image
_,bt = cv2.threshold(grey_image, 150 ,255,cv2.THRESH_BINARY) #variable means binary threshold
cv2.imwrite(folderPath + "\\" + "test.png", bt) #Saving result
imageout = pytesseract.image_to_string(bt) #Convert image to text
print(imageout) #Print text in console
I've been trying different ranges of thresholding but still can't get a precise output.
What do you suggest for getting a precise result?
Solution 1:[1]
Because you are dealing with an image containing white characters over a dark background, it is recommended to invert it prior using pytesseract.
This is done using inverted_grey_image = cv2.bitwise_not(grey_image).
You may then adjust the threshold in threshold: _,bt = cv2.threshold(inverted_grey_image, 140 ,255,cv2.THRESH_BINARY)
Below is the full code:
from pytesseract import *
import cv2
path = r"path where image is located" #path of image
folderPath = r"path for saving output image"
grey_image = cv2.imread(path,0) #import image
inverted_grey_image = cv2.bitwise_not(grey_image)
_,bt = cv2.threshold(inverted_grey_image, 140 ,255,cv2.THRESH_BINARY) #variable means binary threshold
cv2.imwrite(folderPath + "/" + "test.png", bt) #Saving result
imageout = pytesseract.image_to_string(bt) #Convert image to text
print(imageout)
It returns:
20 hours
20 hours
3 hours
EDIT: I am currently dealing with a similar OCR problem: you may want to check this recent post for inspiration.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sheldon |
