python - 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)
'''
注意:这些图像产生“NULL”结果,我不知道为什么
解决方案
看完图后,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)
推荐阅读
- c - 如何使用C计算目录中的文件
- sql - 与另一个表的 SQL 连接导致重复记录
- c - gdb 调试 8 字节间隙是干什么用的?
- yaml - 请用适当的例子解释 YAML 中不同类型的 Context
- firebase - 如何将 Flutter Web 与 Firebase 集成?
- python - 如何按熊猫中的相似行分组
- python - /sitemap.xml Django 中的 NoReverseMatch
- linux - 如何减慢管道中的第一个程序,直到第二个程序准备好
- visual-c++ - Boost不承认自己是一个班级
- python - 如何在 python3 中使新的 Python 类型适应 SQL 语法