node.js - Google Vision API 文本检测按块显示单词
问题描述
有没有办法按块对 Google 的 Document Text Detection API 的文本响应进行分组?如果有提供的解决方案,我可能在文档中忽略了它。我目前正在使用 node.js 从用户提供的图像中获取文本。这是我的代码:
const vision = require('@google-cloud/vision');
const client = new vision.ImageAnnotatorClient({
keyFilename: 'APIKey.json'
});
client
.documentTextDetection('image.jpg')
.then(results => {
res.send(results);
})
.catch(err => {
res.send(err);
});
提前致谢。
解决方案
我不确定是否有标准化的方法来执行此操作,但 Vision API 确实为我们提供了编写块文本所需的一切,包括相关的中断(请参阅Vision API 中断类型)。所以我们可以枚举每个块并从中创建文本。
我没有考虑其他几种中断类型(连字符,SURE_SPACE),但我认为添加这些应该很容易。
例如:
const vision = require('@google-cloud/vision');
const client = new vision.ImageAnnotatorClient({
keyFilename: 'APIKey.json'
});
client
.documentTextDetection('image.jpg')
.then(results => {
console.log("Text blocks: ", getTextBlocks(results));
})
.catch(err => {
console.error("An error occurred: ", err);
});
function getTextBlocks(visionResults) {
let textBlocks = [];
let blockIndex = 0;;
visionResults.forEach(result => {
result.fullTextAnnotation.pages.forEach(page => {
textBlocks = textBlocks.concat(page.blocks.map(block => { return { blockIndex: blockIndex++, text: getBlockText(block) }}));
});
});
return textBlocks;
}
function getBlockText(block) {
let result = '';
block.paragraphs.forEach(paragraph => {
paragraph.words.forEach(word => {
word.symbols.forEach(symbol => {
result += symbol.text;
if (symbol.property && symbol.property.detectedBreak) {
const breakType = symbol.property.detectedBreak.type;
if (['EOL_SURE_SPACE' ,'SPACE'].includes(breakType)) {
result += " ";
}
if (['EOL_SURE_SPACE' ,'LINE_BREAK'].includes(breakType)) {
result += "\n"; // Perhaps use os.EOL for correctness.
}
}
})
})
})
return result;
}
推荐阅读
- java - Android java:如何创建 POJO 并将其转换为 Cloud Firestore REST API 可接受的 JSON
- c# - 管道缓冲区保留直到处理完成
- python - Python 检查两个列表
- .net - 在 .Net Core 中检测 Windows 代理设置
- symfony - 通过 phpspreadsheet 从 Excel 文件导入数据并检查数据库 symfony 4 中是否存在记录
- python-3.x - 如何计算连续字符?
- php - 如何返回找到的项目的结果。但也有一个未找到的项目列表
- kubernetes - 节点中的本地持久卷(尽管使用它的 pod 可以在另一个节点中重新调度,但仍然可以访问)
- php - 如何将目录字符串处理成更小的目录字符串
- ios - 在 Flutter 中的 `ios` 模拟器上运行我的 Flutter 项目时遇到错误(与代码相比)