0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Cordovaでcustom vision api を呼び出してみた

Posted at

概要

Cordovaでアプリ開発を行なっています。カメラで撮った画像をcustom vision apiで分類しようとした際にajaxで画像の渡し方でハマっていたので、ご参考までに。

Cordovaでカメラ撮影

index.js
function takePicture () {
      navigator.camera.getPicture(
                    cameraSuccess, cameraError,
                    {
                      quality: 50,
                      destinationType: Camera.DestinationType.DATA_URL,
                      correctOrientation: true,
                      saveToPhotoAlbum: true
                    });
          }

destinaitonTypeにはFILE_URIとDATA_URLのどちらかを指定できますが、今回はbase64で返ってくるDATA_URLを指定します。

Custom Vision Service

Custom Vision ServeiceでURLとPrediction-Keyを取得してください。Performanceの画面からPrediction URLをクリックすることで以下の画面が出てくると思います。その際出来ているモデルをPublishすることを忘れないように。
2種類のPrediction APIがありますが、今回はimage fileの方のURLを用います。
customvision.png

AjaxでAPI通信

今回ハマったところはAPIにbase64の形式で画像を渡そうとしていたところでした。base64ではなくblobで渡す必要がありました。

index.js
//base64 to blob
var dataURItoBlob = function(base64_image) {
        var binary = atob(base64_image.split( "," )[1]);
        var array = [];
        for (var i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        return new Blob([new Uint8Array(array)], {
        });
     }

function predict(image) {
        var blob = dataURItoBlob(image);
        $.ajax({
            url: "your url",
            beforeSend: function(xhrObj) {
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/octet-stream");
                xhrObj.setRequestHeader("Prediction-key","your key");
            },
            type: "POST",
            data: blob,
            processData: false,
            contentType: false
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    }

もっと簡単なやり方があるかもしれませんが、一応通信することが出来ました。他にもあればご教授いただきたいと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?