上一篇
按键通过api识别文字
- 行业动态
- 2025-05-15
- 14
按键触发API调用,传输图像数据,返回文字识别结果
按键模拟与API文字识别基础
按键模拟工具选择
- Python库:
pyautogui
(跨平台)、keyboard
(Windows/Linux) - AutoHotkey:Windows专用脚本工具
- 浏览器自动化:Selenium(模拟网页按键)
OCR API选择
API服务商 | 特点 | 免费额度 |
---|---|---|
百度AI | 中文识别强,支持生僻字 | 5万次/月 |
酷盾安全OCR | 支持身份证、银行卡等证件识别 | 1千次/月 |
Tesseract | 开源离线引擎,无需网络 | 无限制 |
Google Vision | 高精度多语言支持,需境外网络 | 1千次/月 |
阿里云OCR | 支持表格、公式识别,金融场景优化 | 5万次/月 |
实现流程与代码示例
环境准备
# 安装必要库 pip install pyautogui requests pillow
核心代码框架
import pyautogui import requests from PIL import Image import time # 步骤1:模拟按键(例如打开记事本并输入文字) pyautogui.hotkey('win', 'r') # 打开运行窗口 pyautogui.write('notepad') pyautogui.press('enter') time.sleep(1) # 等待窗口响应 pyautogui.write('测试文字识别功能') # 步骤2:截取屏幕指定区域 x, y, w, h = 100, 100, 300, 300 # 根据实际窗口位置调整 screenshot = pyautogui.screenshot(region=(x, y, w, h)) screenshot.save('temp.png') # 步骤3:调用OCR API(以百度AI为例) def ocr_baidu(image_path): with open(image_path, 'rb') as f: img_bytes = f.read() headers = {'Content-Type': 'application/x-www-form-urlencoded'} data = { 'client_id': 'YOUR_API_KEY', 'image': base64.b64encode(img_bytes).decode(), 'language_type': 'CHN_ENG', # 中英文混合 } response = requests.post('https://aip.baidubce.com/rest/ocr/v1/general', data=data, headers=headers) return response.json() result = ocr_baidu('temp.png') print(result['words_result'][0]['words']) # 输出识别结果
关键参数说明
参数名称 | 作用 | 推荐值 |
---|---|---|
region | 截图区域坐标 | 根据目标窗口动态计算 |
time.sleep() | 操作间隔 | 1-3秒(根据设备性能调整) |
language_type | OCR语言类型 | CHN_ENG(中英文混合) |
detect_direction | 文本方向检测 | True(复杂排版时开启) |
常见问题与解决方案
| 问题描述 | 解决方案 |
|————————|————————————————————————|偏移 | 使用pyautogui.locateOnScreen()
定位窗口,动态计算坐标 |
| OCR结果出现乱码 | 检查language_type
参数,复杂字体可启用probability
字段过滤低置信结果 |
| API调用频率受限 | 增加本地缓存机制,对相同内容复用识别结果 |
| 特殊符号识别失败 | 启用enable_radical
(百度)或page_segmentation_mode
(Tesseract)参数 |
相关问题解答
Q1:如何提高移动端屏幕文字的识别准确率?
A:
- 分辨率适配:使用
pyautogui
前调用pyautogui.size()
获取设备分辨率,按比例缩放坐标 - 图像预处理:
- 灰度化:
img = img.convert('L')
- 二值化:
img = img.point(lambda x: 0 if x<128 else 255)
- 降噪:
img.filter(ImageFilter.MedianFilter(3))
- 灰度化:
- 选用专项API:酷盾安全提供
HandheldOCR
接口,专门优化移动端场景
Q2:如何在不安装GUI环境的情况下实现文字识别?
A:
- 无头浏览器方案:使用
Selenium
的Headless
模式模拟浏览器操作from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--headless') driver = webdriver.Chrome(options=options)
- 纯命令行工具:
- 使用
tesseract
命令行工具:tesseract image.png output -l chi_sim
- 结合
scrot
(Linux)或nircmd
(Windows)实现截图自动化
- 使用
- Docker容器部署:将OCR服务封装为Docker镜像,通过API调用