0

我不知道该怎么做,但我需要帮助才能让我的微软自定义愿景发挥作用。我正在使用 javascript 将我的 html 文档链接到自定义视觉,但我不知道如何使用与我的 html 和 js 文件位于同一文件夹中的本地图像文件,有人可以帮助我使用任何代码吗?

        },
        type: "POST",
        // Request body
        data: "{body}",
    })
    .done(function(data) {
        alert("success");
    })
    .fail(function() {
        alert("error");
    });
});

说明告诉我将 {body} 更改为

4

1 回答 1

1

几点:

  • 最新的 API 是 v3.0(不是您提到的 2.0),请参见此处
  • 他们在页面上提供的代码示例中有一个小错误:标题键Prediction-Key出现了 2 次(key大写与小写)。你只需要它1次
  • 从安全方面考虑,不能直接在js中加载本地文件

因此,如果您想“从头开始”,您可以执行以下操作,而必须手动选择文件:

<!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
    <input type='file' accept='image/*' onchange='openFile(event)' />
    <br />
    <img id='output' style="height:100px; width:100px;" />

    <script type="text/javascript">
        var openFile = function(file) {
            var input = file.target;

            var reader = new FileReader();
            reader.onload = function(){
                var dataURL = reader.result;

                var params = {
                    // Request parameters
                    "application": "myTestApp"
                };

                var parts = dataURL.split(';base64,');
                var contentType = parts[0].split(':')[1];
                var raw = window.atob(parts[1]);
                var rawLength = raw.length;

                var uInt8Array = new Uint8Array(rawLength);

                for (var i = 0; i < rawLength; ++i) {
                    uInt8Array[i] = raw.charCodeAt(i);
                }

                var imgContent = new Blob([uInt8Array], { type: contentType });

                $.ajax({
                    url: "https://southcentralus.api.cognitive.microsoft.com/customvision/v3.0/Prediction/__YOUR_APPLICATION_ID__/classify/iterations/__YOUR_ITERATION_ID__/image?" + $.param(params),
                    beforeSend: function(xhrObj){
                        // Request headers
                        xhrObj.setRequestHeader("Prediction-Key","__YOUR_PREDICTION_KEY__");
                        xhrObj.setRequestHeader("Content-Type","application/octet-stream");
                    },
                    type: "POST",
                    // Request body
                    data: imgContent,
                    processData: false
                })
                .done(function(data) {
                    alert("success");
                    console.log(data);
                })
                .fail(function() {
                    alert("error");
                });
            };

            reader.readAsDataURL(input.files[0]);
        };
    </script>
</body>
</html>

此外,您可以在此处查看 Node.js 中的现有示例,它们从本地文件调用预测:https ://github.com/Azure-Samples/cognitive-services-node-sdk-samples/tree/主/样品/customvision

于 2019-04-08T09:24:36.913 回答