回答
如果总是提示OCR截图错误,可能是以下原因导致的,请逐一排查:
-
权限未正确授予
- 确保已通过
auto.waitFor()
请求无障碍服务和屏幕截图权限 - 在代码中添加权限检测:
if (!requestScreenCapture()) { toastLog("请打开权限!"); exit(); }
- 确保已通过
-
截图时机过早
- 在
requestScreenCapture()
后需要等待1-2秒再截图:
sleep(1000); // 等待1秒 const img = captureScreen();
- 在
-
OCR识别参数问题
- 确保使用正确的OCR函数:
const text = ocr.recognizeText(img); // 仅返回文本 // 或 const result = ocr.recognize(img); // 返回带坐标的详细信息
-
图片处理问题
- 如果识别失败,可尝试对图片进行预处理:
// 灰度处理 images.grayscale(img); // 或缩放图片 images.resize(img, [800, 1200]);
-
添加错误处理
try { const res = ocr.recognize(img); } catch (e) { toastLog("OCR识别失败:" + e); }
完整示例代码:
// 文档地址 https://docs.hamibot.com/
auto.waitFor();
if (!requestScreenCapture()) {
toastLog("请授予屏幕截图权限!");
exit();
}
sleep(1000); // 等待权限生效
const img = captureScreen();
try {
const text = ocr.recognizeText(img);
toastLog("识别结果:" + text);
} catch (e) {
toastLog("识别错误:" + e);
}
ℹ️ 本回答由 AI 生成,内容仅供参考