axios await/async で受信した画像を application/octet-stream で Microsoft Custom Vision Service に送るメモです。
使うであろうシチュエーション
以前の記事と同様、LINE BOTのメッセージ画像のような何かしらのサービス内や、画像の取得には一定の設定が必要でセキュアな場所に置かれた公開されていない画像がターゲットです。
axios await/async で受信した画像を application/octet-stream でAzure Face APIに送るメモ
Microsoft Custom Vision Serviceを準備
2020/5/14 の状況で進めます。
Microsoft Custom Vision Service を使用して画像を分類する – Learn | Microsoft Docs
この Microsoft Learn 教材をベースに、絵画とポロック・レンブラント・ピカソの作家を判定するものになります。
Trainを済ませて、Perfomance から Prediction URLをクリックし設定を確認します。
画像ファイルを使うので「If you have an image file:」の設定の部分を使います。
サンプルソース
実際のコードはこちらです。
{{CUSTOM_VISION_API_ENDPOINT_URL}}
はIf you have an image URL:
にある末尾が image のエンドポイントを使いましょう{{Prediction-Key}}
は、さきほどのは
Prediction-Key` の値と置き換えましょう
const axios = require('axios'); const sendCustomVision = async (imageURL) => { ///////// 画像取得 ///////////////////////////////////////////////////// const configImageAPI = { url: imageURL, method: 'get', responseType: 'arraybuffer' }; let responseImageAPI; try { // axios はRequest Configで受信データのタイプを設定できる。今回は arraybuffer が適切。 responseImageAPI = await axios.request(configImageAPI); console.log('image data get'); } catch (error) { console.log('image data Error'); console.error(error); } ///////// Custom Vision API ////////////////////////////////////////////// // If you have an image URL: にあるエンドポイントを使う // 末尾が image のもの const CUSTOM_VISION_API_ENDPOINT_URL = '{{CUSTOM_VISION_API_ENDPOINT_URL}}'; // Prediction-Keyの値を Prediction-Key ヘッダーに入れる // 画像データで送るので Content-type ヘッダーに application/octet-stream 指定 const configCustomVisionAPI = { url: CUSTOM_VISION_API_ENDPOINT_URL, method: 'post', headers: { 'Content-type': 'application/octet-stream', 'Prediction-Key':'{{Prediction-Key}}' }, data: responseImageAPI.data }; // axiosの送信設定 let responseCustomVision; try { // POSTリクエストで送る responseCustomVision = await axios.request(configCustomVisionAPI); console.log("post OK"); // データ送信が成功するとレスポンスが来る console.log(responseCustomVision.data); } catch (error) { console.log("post Error"); // ダメなときはエラー console.error(error); } } // レンブラントっぽい画像 sendCustomVision('https://www.cnn.co.jp/storage/2018/11/26/97e614a5a80cd9b784f4bdc82b4ec331/rembrandt-study-of-the-head-of-a-young-man.jpg');
こちらで、無事送信することができました。以前の Face API の記事で application/octet-stream を扱えるようになったので、すんなり送ることができました。
さらに、このコードを利用して、LINE Botのソースにも Microsoft Custom Vision Service を画像連携して動かせたので、クローズドな画像取得との相性よく作れたかなと思っています。