1. 项目概述
在自动化脚本开发领域,屏幕文字识别(OCR)是提升脚本智能化程度的关键技术。EasyClick作为移动端自动化工具,通过调用OCR API可以实现对屏幕文字的精准识别,进而完成更复杂的自动化操作。本教程将完整演示如何通过EasyClick对接通用OCR API,实现从截图到文字识别的全流程。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 环境准备与配置
2.1 开发环境搭建
首先需要准备EasyClick的开发环境:
- 下载最新版EasyClick IDE(当前推荐v5.6.3+)
- 安装Java运行环境(JRE 1.8+)
- 配置Android调试桥(ADB)连接测试设备
注意:确保测试设备已开启USB调试模式,不同品牌手机开启方式可能不同,通常需要在"开发者选项"中启用。
2.2 OCR服务申请
选择讯飞OCR开放平台作为服务提供商:
- 注册讯飞开放平台账号
- 创建新应用并开通"通用文字识别"服务
- 获取API Key和API Secret(32位字符串)
关键参数示例:
javascript复制const OCR_CONFIG = {
host: "api.xf-yun.com",
apiKey: "your_api_key_32chars",
apiSecret: "your_api_secret_32chars",
path: "/v1/private/sf8e6aca1"
}
3. 核心功能实现
3.1 屏幕截图处理
EasyClick提供内置截图函数:
lua复制function captureScreen()
local imgPath = "/sdcard/screen.png"
snapShot(imgPath) -- EasyClick原生截图函数
return imgPath
end
图像处理注意事项:
- 截图格式必须为PNG/JPG
- 建议分辨率控制在1080P以内
- 单张图片Base64编码后不超过4MB
3.2 签名生成算法
OCR API需要HMAC-SHA256签名:
lua复制function generateSignature(apiSecret, date)
local signatureOrigin = string.format("host: %s\ndate: %s\nPOST %s HTTP/1.1",
OCR_CONFIG.host, date, OCR_CONFIG.path)
local hmac = crypto.hmac_sha256(signatureOrigin, apiSecret)
return crypto.base64_encode(hmac)
end
日期格式要求:
- 必须使用RFC1123格式
- 时区为GMT/UTC
- 示例:"Wed, 11 Aug 2021 06:55:18 GMT"
3.3 API请求构造
完整的请求示例:
lua复制function ocrRequest(imagePath)
local date = os.date("!%a, %d %b %Y %H:%M:%S GMT")
local signature = generateSignature(OCR_CONFIG.apiSecret, date)
local authOrigin = string.format(
'api_key="%s", algorithm="hmac-sha256", headers="host date request-line", signature="%s"',
OCR_CONFIG.apiKey, signature)
local authorization = crypto.base64_encode(authOrigin)
local imageData = readFileBase64(imagePath)
local headers = {
["Host"] = OCR_CONFIG.host,
["Date"] = date,
["Authorization"] = authorization,
["Content-Type"] = "application/json"
}
local body = {
header = { app_id = OCR_CONFIG.appId, status = 3 },
parameter = {
sf8e6aca1 = {
category = "ch_en_public_cloud",
result = { encoding = "utf8", compress = "raw", format = "json" }
}
},
payload = {
sf8e6aca1_data_1 = {
encoding = "jpg",
status = 3,
image = imageData
}
}
}
local response = http.post(
"https://"..OCR_CONFIG.host..OCR_CONFIG.path,
json.encode(body),
headers
)
return json.decode(response)
end
4. 结果处理与优化
4.1 响应数据解析
典型响应结构:
json复制{
"header": {
"code": 0,
"message": "success",
"sid": "ase000d1688@hu17b34308ea40210882"
},
"payload": {
"result": {
"compress": "raw",
"encoding": "utf8",
"format": "json",
"text": "ewogICJwYWdlcyI6IFt7ICJjb250ZW50IjogIuS9oOWlve+8miJ9XQp9"
}
}
}
解码处理:
lua复制local resultJson = crypto.base64_decode(response.payload.result.text)
local resultData = json.decode(resultJson)
4.2 精度优化技巧
-
图像预处理:
- 使用
image.contrast()增加对比度 - 对低光照图片使用
image.brightness(1.2)
- 使用
-
区域识别优化:
lua复制-- 只识别屏幕特定区域 local region = {left=100, top=200, right=300, bottom=400} snapShotRegion(imgPath, region) -
多结果校验:
lua复制-- 连续识别3次取最优结果 local results = {} for i=1,3 do table.insert(results, ocrRequest(imagePath)) sleep(200) end
5. 完整示例代码
lua复制-- 配置区
OCR_CONFIG = {
host = "api.xf-yun.com",
apiKey = "your_api_key",
apiSecret = "your_api_secret",
appId = "your_app_id",
path = "/v1/private/sf8e6aca1"
}
-- 主函数
function main()
-- 1. 截图
local imgPath = captureScreen()
-- 2. OCR识别
local response = ocrRequest(imgPath)
-- 3. 处理结果
if response.header.code == 0 then
local result = processOCRResult(response)
toast("识别成功:"..result)
else
toast("识别失败:"..response.header.message)
end
end
-- 辅助函数
function captureScreen()
local imgPath = "/sdcard/ocr_temp.png"
snapShot(imgPath)
return imgPath
end
function generateSignature(apiSecret, date)
local signatureOrigin = string.format("host: %s\ndate: %s\nPOST %s HTTP/1.1",
OCR_CONFIG.host, date, OCR_CONFIG.path)
local hmac = crypto.hmac_sha256(signatureOrigin, apiSecret)
return crypto.base64_encode(hmac)
end
function ocrRequest(imagePath)
local date = os.date("!%a, %d %b %Y %H:%M:%S GMT")
local signature = generateSignature(OCR_CONFIG.apiSecret, date)
local authOrigin = string.format(
'api_key="%s", algorithm="hmac-sha256", headers="host date request-line", signature="%s"',
OCR_CONFIG.apiKey, signature)
local authorization = crypto.base64_encode(authOrigin)
local imageData = readFileBase64(imagePath)
local headers = {
["Host"] = OCR_CONFIG.host,
["Date"] = date,
["Authorization"] = authorization,
["Content-Type"] = "application/json"
}
local body = {
header = { app_id = OCR_CONFIG.appId, status = 3 },
parameter = {
sf8e6aca1 = {
category = "ch_en_public_cloud",
result = { encoding = "utf8", compress = "raw", format = "json" }
}
},
payload = {
sf8e6aca1_data_1 = {
encoding = "jpg",
status = 3,
image = imageData
}
}
}
local response = http.post(
"https://"..OCR_CONFIG.host..OCR_CONFIG.path,
json.encode(body),
headers
)
return json.decode(response)
end
function processOCRResult(response)
local resultJson = crypto.base64_decode(response.payload.result.text)
local resultData = json.decode(resultJson)
-- 简单提取所有文字内容
local text = ""
for _,page in ipairs(resultData.pages or {}) do
for _,line in ipairs(page.lines or {}) do
text = text..line.content.."\n"
end
end
return text
end
-- 启动
main()
6. 常见问题排查
6.1 签名验证失败
可能原因:
- 时间不同步:确保设备时间与网络时间同步
- Secret错误:检查API Secret是否包含特殊字符
- 编码问题:签名前字符串必须为UTF-8编码
解决方案:
lua复制-- 调试用签名验证
function debugSignature()
local testDate = "Wed, 11 Aug 2021 06:55:18 GMT"
local testSecret = "apisecretXXXXXXXXXXXXXXXXXXXXXXX"
local expected = "/mg2h9BCkespilZ94HUBaQVPq2v7PxYF90teTBlaxd8="
local actual = generateSignature(testSecret, testDate)
toast("签名验证:"..tostring(actual == expected))
end
6.2 图像识别率低
优化方案:
-
增加图像预处理:
lua复制function preprocessImage(path) local img = image.read(path) img = image.grayscale(img) img = image.threshold(img, 0.5) image.write(img, path) end -
调整识别参数:
lua复制parameter = { sf8e6aca1 = { category = "ch_en_public_cloud", result = { encoding = "utf8", compress = "raw", format = "json", min_confidence = 0.8 -- 提高置信度阈值 } } }
6.3 性能优化建议
-
缓存机制:
lua复制local cache = {} function smartOCR(imagePath) local hash = crypto.md5(imagePath) if cache[hash] then return cache[hash] end cache[hash] = ocrRequest(imagePath) return cache[hash] end -
异步处理:
lua复制function asyncOCR(callback) thread.create(function() local result = ocrRequest(captureScreen()) callback(result) end) end
7. 扩展应用场景
7.1 游戏自动化案例
自动识别游戏对话框:
lua复制function checkDialog()
local region = {left=100, top=500, right=900, bottom=700}
local tempPath = "/sdcard/dialog.png"
snapShotRegion(tempPath, region)
local result = ocrRequest(tempPath)
if string.find(result, "确定") then
tap(800, 650) -- 点击确定按钮
end
end
7.2 电商比价脚本
识别商品价格:
lua复制function getPrice()
local priceArea = {left=200, top=300, right=400, bottom=350}
snapShotRegion("/sdcard/price.png", priceArea)
local result = ocrRequest("/sdcard/price.png")
local price = string.match(result, "%d+%.?%d*")
return tonumber(price)
end
7.3 文档扫描工具
多页文档处理:
lua复制function scanDocument(pages)
local results = {}
for i=1,pages do
toast("请翻到第"..i.."页")
sleep(3000)
table.insert(results, ocrRequest(captureScreen()))
end
return table.concat(results, "\n\n")
end
在实际项目中,建议将OCR功能封装为独立模块,通过事件回调机制与其他模块交互。对于企业级应用,可以考虑搭建本地OCR服务集群来提升响应速度和稳定性。
