首页 > 解决方案 > opencv 阈值处理和 pytesseract

问题描述

目前我正在尝试开发一些简单的计算机视觉代码来读取我在使命召唤游戏中的击杀数量并将其作为整数保存到数组中。该代码每秒对我的屏幕进行截图,并使用 opencv 对图像进行阈值处理并将其输入到 pytesseract 中。尽管数字保持不变,但背景噪声会极大地改变图像并强制输入大量空值。如果它错过了一些输入,但它错过了所有数字的 %50 或更多,我没问题。如果有人对具有不同背景的单个数字图像进行阈值处理有任何提示,那将是一个巨大的帮助。

'''

pytesseract.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract'

pyautogui.screenshot('pictures/Kill.png', region = (1822, 48, 30, 23))

img = cv2.imread('pictures/Kill.png')

img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh1 = cv2.threshold(img, 255, 255, cv2.THRESH_TRUNC)

cv2.imwrite('pictures/killthresh1.png',thresh1)

ret, thresh1 = cv2.threshold(img, 180, 255, cv2.THRESH_BINARY)

thresh1 = cv2.bitwise_not(thresh1)

cv2.imwrite('pictures/Killthresh2.png', thresh1)

custom_config = r'-l eng --oem 3 --psm 7 -c 

tessedit_char_whitelist="1234567890" '

killnumber = pytesseract.image_to_string(thresh1, config = custom_config)

'''

原始pyautogui截图

TRUNC 阈值

二进制阈值

注意:这些图像产生“NULL”结果,我不知道为什么

标签: pythonopencvpython-tesseract

解决方案


看完图后,img = cv2.imread('pictures/Kill.png')

适用adaptive-threshold于原始 pyautogui 屏幕截图:

在此处输入图像描述

现在阅读:

txt = pytesseract.image_to_string(thr, config="--psm 7")
print(txt)

结果:

3

代码:


import cv2
import pytesseract

img = cv2.imread("0wHAy.png")
gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thr = cv2.adaptiveThreshold(gry, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
                            cv2.THRESH_BINARY_INV, 21, 9)
txt = pytesseract.image_to_string(thr, config="--psm 7")
print(txt)

推荐阅读