我正在尝试读取屏幕上的数字,为此我正在使用 pytesseract。问题是,尽管它有效,但它的作用很慢,而且根本不会产生好的结果。例如,对于这张图片:
我可以制作这个阈值图像:
它读取的是 5852 而不是 585,这是可以理解的,但有时使用不同的阈值可能会更糟。例如,它可以将 1 000 000 读取为 1 aaa eee,或将 585 读取为 5385r(是的,它甚至会毫无理由地添加字符)
没有任何方法可以强制 pytesseract 只读取数字或简单地使用比 pytesseract 更好的东西吗?
my code:
from PIL import Image
from pytesseract import pytesseract as pyt
import test
pyt.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'
def tti2(location) :
image_file = location
im = Image.open(image_file)
text = pyt.image_to_string(im)
print(text)
for character in "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ*^&\n" :
text = text.replace(character, "")
return text
test.th("C:\\Users\\Utilisateur\\Pictures\\greenshot\\flea market sniper\\TEST.png")
print(tti2("C:\\Users\\Utilisateur\\Pictures\\greenshot\\flea market sniper\\TESTbis.png"))
“测试”的代码(用于阈值):
import cv2
from PIL import Image
def th(Path) :
img = cv2.imread(Path)
# If your image is not already grayscale :
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
threshold = 60 # to be determined
_, img_binarized = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)
pil_img = Image.fromarray(img_binarized)
Path = Path.replace(".png","")
pil_img.save(Path+"bis.png")
可以使用仅包含数字值的 tessedit_char_whitelist 配置来强制 pytesseract 只读取数字。
您可以尝试使用 Tesseract 文档来改进结果:Tesseract - 提高输出质量 https://tesseract-ocr.github.io/tessdoc/ImproveQuality.html
我还建议您使用:
- 背景为白色,字符字体颜色为黑色。
- 选择所需的超正方 psm 模式。在之前的案例中,我使用 7 psm 模式将图像视为单个文本行。
- 使用 tessedit_char_whitelist 配置仅指定您正在搜索的字符。
考虑到这一点,代码如下:
import cv2
import numpy as np
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract'
originalImage = cv2.imread('1.png')
grayImage = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY)
(_, blackAndWhiteImage) = cv2.threshold(grayImage, 127, 255, cv2.THRESH_BINARY_INV)
text = pytesseract.image_to_string(blackAndWhiteImage, config="--psm 7 --oem 3 -c tessedit_char_whitelist=0123456789")
print('Text: ', text)
cv2.imshow('Image result', blackAndWhiteImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
以及期望的结果:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)