Google App Script(以下GAS)の勉強のために、Googleフォームからアップロードした画像に記載されているテキストをCloud Vision APIを使って抽出するアプリを作成したメモ。
Googleフォームからアップロードされた画像から、Cloud Vision APIを使ってテキストを注する。
勉強のためシンプルに画像アップロード機能を持つGoogleフォームを作成して、フォームのスクリプトエディタにすべての処理を記述する。
function sendform(e) {
const items = e.response.getItemResponses();
var imageFileId;
items.forEach(function(item) {
if (item.getItem().getTitle() == '画像') {
imageFileId = item.getResponse();
return;
}
})
const imageBlobData = DriveApp.getFileById(imageFileId[0]).getBlob().getBytes();
const base64ImageData = Utilities.base64Encode(imageBlobData); // -- (1)
const cloudVisionResponses = JSON.parse(fetch(base64ImageData)); // -- (2)
const readedText = cloudVisionResponses.responses[0].fullTextAnnotation.text;
GmailApp.sendEmail(
'info@example.com',
'OCRアプリケーション',
readedText
);
}
(1) Cloud Vision APIへPOSTする画像データは、base64でエンコードする。
(2) Cloud Vision APIへ画像データをPOSTして、テキストを取得するfetch
関数は以下のようになる。
function fetch(base64ImageData) {
const cloudVisionAccessKey = 'Cloud Vision APIキー';
const cloudVisionUrl = 'https://vision.googleapis.com/v1/images:annotate?key=' + cloudVisionAccessKey
const payload = JSON.stringify({
"requests": [
{
"image": {
"content": base64ImageData
},
"features": [
{
"type": "TEXT_DETECTION",
"maxResults": 1
}
]
}
]
});
const cloudVisionResponse = UrlFetchApp.fetch(cloudVisionUrl, {
method: "POST",
contentType: "application/json",
payload: payload
})
.getContentText();
return cloudVisionResponse;
}
以下の条件を満たせば、思った以上に高い精度でテキストを抽出できるという印象を受けた。
No comments yet.
改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。