
GASでCloud Vision APIを利用する
タイトルそのままです。ちょっと試しに動かしたかったのでやってみました。
Cloud Vision APIについては公式ページから引用
Vision API
Google Cloud の Vision API は REST API や RPC API を介して強力な事前トレーニング済み機械学習モデルを提供します。画像にラベルを割り当てることで、事前定義済みの数百万のカテゴリに画像を高速に分類できます。オブジェクトや顔を検出し、印刷テキストや手書き文字を読み取り、有用なメタデータを画像カタログに作成します。
準備
デベロッパーコンソールから Cloud Vision APIを有効にして、APIキーも設定しておきます。
※あとGCPの管理画面から請求先登録をする必要があります
GAS
// プロパティに関する情報
const sp = PropertiesService.getScriptProperties();
const FOLDER_ID = sp.getProperty('FOLDER_ID');
const GOOGLE_API_KEY = sp.getProperty('GOOGLE_API_KEY');
function main() {
const imageFiles = getImgFileFromDrive();
// 画像ファイルをVision APIで処理
imageFiles.forEach(image => {
const resultMessage = analyzeImage(image);
console.log(resultMessage);
});
}
// Googleドライブからファイル取得
function getImgFileFromDrive() {
let images = [];
const folder = DriveApp.getFolderById(FOLDER_ID);
const files = folder.getFiles();
while (files.hasNext()) {
const file = files.next();
const blob = file.getBlob();
const content_type = blob.getContentType();
const base64EncodedFile = Utilities.base64Encode(blob.getBytes());
images.push(base64EncodedFile);
}
return images;
}
// Vision APIで画像を解析して結果を取得
function analyzeImage(image) {
const apiKey = GOOGLE_API_KEY;
const url = 'https://vision.googleapis.com/v1/images:annotate?key=' + apiKey;
// 画像からテキストの検出
const body = {
"requests": [
{
"image": {
"content": image
},
"features": [
{
"type": "DOCUMENT_TEXT_DETECTION",
}
],
"imageContext": {
"languageHints": ["jp-t-i0-handwrit"]
}
}
]
};
const head = {
"method": "post",
"contentType": "application/json",
"payload": JSON.stringify(body),
"muteHttpExceptions": true
};
const response = UrlFetchApp.fetch(url, head);
const obj = JSON.parse(response.getContentText());
const result = obj.responses[0].textAnnotations[0].description;
return result;
}
ネットからお借りした手書きの文字
以下の画像はGoogle Drive内のフォルダに保存してあります。



結果

1枚目:松~(なんでなん・・・)
2枚目:「について」も(2017になってしまいました。
3枚目:最後の漢字が難しくて、間違い探すのめんどう~
という結果でした。
補足
手書き文字を検出したいなら、
"type": "DOCUMENT_TEXT_DETECTION"
日本語ってのをどうすれいいのか良くわからんかったのですが、リファレンスを参考に以下のようにしています(あっているのか不明)
"languageHints": ["jp-t-i0-handwrit"]
手書き文字ではない場合、かなり精度よく抽出してくれます(フォントがNGでなければおそらく)。いい感じに annotationされた箇所を抽出することもできるっぽいですが、よく分かってないです。
それと、Vison APIへはbase64形式にエンコードした画像を渡す必要があります。
"image": {
"content": image
},
テキストを全部セルに書き出して、そこからSpreadSheetの関数で抽出してやればうまいこと使えるんじゃないかと想像しています。