测试的过程想要得到软件上面的测试数据,当时没办法直接获取到,后面找到一个方法就是图片识别,先使用pyautogui截取需要获取数据的地方,然后通过pytesseract将图片上面的文字转化成字符串就成功了
pip install pytesseract
1. 安装Tesseract-OCR
win上面图片识别需要用到Tesseract-OCR工具,所以需要先安装这个软件
先到网址下载,https://sourceforge.net/projects/tesseract-ocr/
安装之后找到tesseract.exe所在的路径路径,后面调用的时候指定
或者直接找pytesseract.py文件,找到 tesseract_cmd,改变它的值为刚才安装 tesseract.exe 的位置
tesseract_cmd = 'D:\\Program Files\\Tesseract-OCR\\tesseract.exe'
但是我觉得这种直接改库内容好像不太好,还是后面传参就去就好了
2. pytesseract使用
pytesseract的使用比较简单,就是调用image_to_string函数
如下:
import pytesseract
# 指定tesseract.exe所在的位置
pytesseract.pytesseract.tesseract_cmd = 'D:\\Program Files\\Tesseract-OCR\\tesseract.exe'
image = Image.open("test.png")
content = pytesseract.image_to_string(image) # 解析图片
logging.info(content)
image_to_string默认就是只能转换英文,也支持中文,但是我在实际用的过程发现识别率有点低,还好现在没有这方面的需求。
中文的话就是需要添加Tesseract-OCR的中文库chi_sim,然后在调用函数的时候加上chi_sim参数就可以了
import pytesseract
image = Image.open('test.png')
content = pytesseract.image_to_string(image, lang='chi_sim') # 解析图片
logging.info(content)
实际使用要故意把字体调大,截图的时候确保图片的干净程度,这样识别率会更高。
有时候会与识别出来的数据需要在进一步优化,比如我们只想要数字
import pytesseract
# 指定tesseract.exe所在的位置
pytesseract.pytesseract.tesseract_cmd = 'D:\\Program Files\\Tesseract-OCR\\tesseract.exe'
image = Image.open("test.png")
content = pytesseract.image_to_string(image) # 解析图片
logging.info(content)
data = ''.join(list(filter(lambda ch: ch in '0123456789.', content)))
try:
float(data)
except Exception as err:
logging.info(err)
content = pytesseract.image_to_string(image) # 解析图片
logging.info(content)
data = ''.join(list(filter(lambda ch: ch in '0123456789.', content)))
return float(data)