原项目地址:https://github.com/benjaminwan/OcrLiteOnnx
本文是基于原项目编译好后的OcrLiteOnnx文字识别系统,可以实现提取图片中的文字及文字中心点坐标等功能。
相较于Tesseract这个OCR来说文字识别的准确度要高很多,识别速度也会快,而且可以在本地适配好对应api接口,整个OcrLiteOnnx项目压缩后仅有14M左右,移植起来相对简单。
OcrLiteOnnx的目录结构及使用方法:
![](https://img-blog.csdnimg.cn/img_convert/39b2e3300d6a5c04f38a65b2720762b9.png)
目录结构:
image目录中ocrliteonnx.PNG文件是需要识别的图片文件,默认位置设置在这个目录下,也可以自行更改(同时需要修改run-test.bat中的图片路径)。
models目录中存放已经训练好了的模型。
win_x64目录中存放已经编译好之后的exe文件。
使用方法:
通过调用run-test.bat批处理文件,可以将/image/ocrliteonnx.PNG路径图片中的文字识别出来,并保
存到ocrliteonnx.PNG-result.txt中,以下检测文字是否存在以及获取图片中文字中心点坐标均是通过对
ocrliteonnx.PNG-result.txt文件进行解析得到的结果。
移植方法:
首先将在项目bat文件中配置好需要识别图片路径,然后再执行bat文件,确认可以正常识别图片中的文字及坐标等信息,正常解析处图片后会在图片当前目录下自动生成*result.jpg和*result.txt文件。
将本项目文件夹拷贝到需要移植的自动化工程目录下,通过调用bat文件识别指定目录下的图片文件,然后对结果进行解析获取图片中的文字及坐标信息。
以下是基于python已经做好了的检测图片/窗口中是否存在指定文字、获取指定图片/窗口中对应字段的中心的坐标。
1.check_if_text_in_image:检测图片中是否含有指定text字段
2.check_if_text_in_window:检测指定窗口中是否含有text字段
3.get_text_position_by_image:返回图片中text字段的中心位置坐标
4.get_text_position_in_window:返回指定窗口中text字段的中心位置坐标,不唯一则返回第一个位置坐标
#! /usr/bin/env python3
# coding=utf-8
import os
import time
import win32gui
import pyautogui
class OcrLiteOnnxApi:
def config_runtest(self, path):
# 修改run-test.bat中默认图片文件路径
runtest_path = os.getcwd() + "\\run-test.bat"
file_data = ""
with open(runtest_path, "r", encoding="utf8") as f:
for line in f.readlines():
if "SET TARGET_IMG=" in line:
line = line.replace(line.split("=")[1], path) + "\n"
file_data += line
with open(runtest_path, "w", encoding="utf8") as f:
f.write(file_data)
def anayse_result(self):
# 执行run-test.bat并获取其返回值[text, position, crnntime]
os.chdir(os.getcwd())
res = os.popen("run-test.bat", "r")
result = res.buffer.readlines()
TextBox, crnnTime, textLine, ocrliteonnx = [], [], [], []
for line in result:
trs_code = str(line, encoding="utf8").strip()
if "TextBox[" in trs_code:
text = trs_code.rstrip("]\n").split("),")[1] + "]"
x1 = text.strip().split("x:")[1].split(",")[0]
x2 = text.strip().split("x:")[2].split(",")[0]
y2 = text.strip().split("y:")[2].split("],")[0]
y3 = text.strip().split("y:")[3].split("],")[0]
text_pos = (int(int(x1)/2 + int(x2)/2), int(int(y2)/2 + int(y3)/2))
TextBox.append(text_pos)
elif "crnnTime[" in trs_code:
crnnTime.append(trs_code.strip(")").split("](")[1])
elif "textLine[" in trs_code:
textLine.append(trs_code.strip(")").split("(")[1])
elif "FullDetectTime(" in trs_code:
FullDetectTime = trs_code.strip(")").split("(")[1]
ocrliteonnx.append(f"FullDetectTime:{FullDetectTime}")
print(f"FullDetectTime:{FullDetectTime}")
for i in range(len(TextBox)):
ocrliteonnx.append([textLine[i], TextBox[i], crnnTime[i]])
return ocrliteonnx
def check_if_text_in_image(self, text, image_path=None):
# 判断图片中是否含有指定text字段
if image_path is not None:
OcrLiteOnnxApi().config_runtest(path=image_path)
image_ocr = OcrLiteOnnxApi().anayse_result()
for line in image_ocr:
if text in line[0]:
print(f"图片中存在{text}字段")
return True
print(f"未在图片中找到{text}字段")
return False
def check_if_text_in_window(self, text, title_name):
# 检测title_name窗口中是否含有text字段
try:
image_path = os.getcwd() + "\\image\\ocrliteonnx.PNG"
hwnd = win32gui.FindWindow(None, title_name)
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
time.sleep(0.01)
pyautogui.screenshot(image_path, [left, top, right - left, bottom - top])
time.sleep(0.01)
image_ocr = OcrLiteOnnxApi().anayse_result()
for line in image_ocr:
if text in line[0]:
print(f"{title_name}窗口中存在{text}字段")
return True
print(f"{title_name}窗口中不存在{text}字段")
return False
except Exception as e:
print(e)
return False
def get_text_position_by_image(self, text, image_path=None):
# 返回图片中text字段的中心位置坐标
if image_path is not None:
OcrLiteOnnxApi().config_runtest(path=image_path)
image_ocr = OcrLiteOnnxApi().anayse_result()
for line in image_ocr:
if text in line[0]:
print(f"{text} 中心点坐标:{line[1]}")
return line[1]
print(f"未在图片中找到{text}字段")
return None
def get_text_position_in_window(self, text, title_name=None):
# 返回指定窗口(title_name=None时则在全屏窗口中匹配text字段)中text字段的中心位置坐标,不唯一则返回第一个位置坐标
try:
image_path = os.getcwd() + "\\image\\ocrliteonnx.PNG"
left, top, right, bottom = 0, 0, 0, 0
OcrLiteOnnxApi().config_runtest(image_path)
if title_name is not None:
hwnd = win32gui.FindWindow(None, title_name)
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
time.sleep(0.01)
pyautogui.screenshot(image_path, [left, top, right-left, bottom-top])
else:
pyautogui.screenshot(image_path)
time.sleep(0.01)
image_ocr = OcrLiteOnnxApi().anayse_result()
for line in image_ocr:
if text in line[0]:
position = (left + line[1][0], top + line[1][1])
print(f"{text} 中心点坐标:{position}")
return position
print(f"未在{title_name}窗口中找到{text}字段")
return None
except Exception as e:
print(e)
return None
if __name__ == "__main__":
time.sleep(5)
OcrLiteOnnxApi().get_text_position_in_window("我的手机")
在全屏窗口中匹配"我的手机"字段,并返回该字段中心的坐标,示例如下:
D:\Python37\python.exe D:/OcrLiteOnnx/ocrliteonnx_api.py
FullDetectTime:2559.871300ms
我的手机 中心点坐标:(1091, 701)
进程已结束,退出代码0
![](https://img-blog.csdnimg.cn/img_convert/05f862ca0e16fad02254a1629a12c8e8.jpeg)
图片文字识别示例(其中有极个别文字识别错误,放大文字字体后可以正常识别出来):
![](https://img-blog.csdnimg.cn/img_convert/2b98770d369ea819f2186c6857158fc2.png)
![](https://img-blog.csdnimg.cn/img_convert/5ab1aa73edb67ed72de97e5fe031eab4.jpeg)
![](https://img-blog.csdnimg.cn/img_convert/68f5d41d18c0654e2763798ab620fc13.png)
项目分享链接:https://pan.baidu.com/s/11lqYr8tIyYbCF8yJKxEA0g?pwd=h6dv