通过 REST API 和 JavaScript 使用计算机视觉功能Use Computer Vision features with the REST API and JavaScript

本指南展示 Azure 认知服务计算机视觉 REST API 的功能。This guide shows the features of the Azure Cognitive Services Computer Vision REST API.

探讨一个使用计算机视觉 REST API 执行光学字符识别 (OCR)、创建智能裁剪的缩略图,以及在图像中检测、标记和描述视觉特征(包括人脸)并对其分类的 JavaScript 应用程序。Explore a JavaScript application that uses the Computer Vision REST API to perform optical character recognition (OCR), create smart-cropped thumbnails, plus detect, categorize, tag, and describe visual features, including faces, in an image. 此示例允许提交图像 URL 来分析或处理图像。This example lets you submit an image URL for analysis or processing. 可以使用此开源示例作为模板,生成自己的 JavaScript 应用,以便使用计算机视觉 REST API。You can use this open source example as a template for building your own JavaScript app to use the Computer Vision REST API.

JavaScript 形式的应用程序已编写好,但尚无计算机视觉功能。The JavaScript form application has already been written, but has no Computer Vision functionality. 在本指南中,请添加特定于计算机视觉 REST API 的代码,以便完成应用程序的功能。In this guide, you add the code specific to the Computer Vision REST API to complete the application's functionality.

先决条件Prerequisites

平台要求Platform requirements

可以使用简单的文本编辑器按照本指南中的步骤操作。You can follow the steps in this guide using a simple text editor.

订阅计算机视觉 API 并获取订阅密钥Subscribe to Computer Vision API and get a subscription key

创建示例之前,必须先订阅 Azure 认知服务中随附的计算机视觉 API。Before creating the example, you must subscribe to Computer Vision API which is part of the Azure Cognitive Services. 有关订阅和密钥管理的详细信息,请参阅订阅For subscription and key management details, see Subscriptions. 主密钥和辅助密钥均适用于本指南。Both the primary and secondary keys are valid to use in this guide.

获取不完整的教程项目Acquire incomplete tutorial project

下载项目Download the project

克隆 Cognitive Services JavaScript Computer Vision Tutorial(认知服务 JavaScript 计算机视觉教程),或下载 .zip 文件并将其解压缩到空目录。Clone the Cognitive Services JavaScript Computer Vision Tutorial, or download the .zip file and extract it to an empty directory.

若要使用已完成的项目(添加了所有教程代码),可以使用 Completed 文件夹中的文件。If you would prefer to use the finished project with all tutorial code added, you can use the files in the Completed folder.

向项目添加教程代码Add tutorial code to the project

JavaScript 应用程序使用六个 .html 文件进行设置,每个文件对应于一个功能。The JavaScript application is set up with six .html files, one for each feature. 每个文件演示的计算机视觉功能(分析、OCR 等)各不相同。Each file demonstrates a different function of Computer Vision (analyze, OCR, etc.). 六个部分并不互相依赖,因此可以将教程代码添加到一个文件、所有六个文件或者部分文件。The six sections do not have interdependencies, so you can add the tutorial code to one file, all six files, or only a couple of files. 可以按任意顺序将教程代码添加到文件中。And you can add the tutorial code to the files in any order.

分析图像Analyze an image

计算机视觉的分析功能可扫描图像中数千个可识别的对象、生物、风景和动作。The Analyze feature of Computer Vision scans an image for thousands of recognizable objects, living things, scenery, and actions. 分析完成以后,分析功能会返回一个 JSON 对象,用描述性标记、颜色分析、标题等对图像进行描述。Once the analysis is complete, Analyze returns a JSON object that describes the image with descriptive tags, color analysis, captions, and more.

若要完成应用程序的分析功能,请执行以下步骤:To complete the Analyze feature of the application, perform the following steps:

为分析按钮添加事件处理程序代码Add the event handler code for the analyze button

在文本编辑器中打开 analyze.html 文件,找到文件底部的 analyzeButtonClick 函数。Open the analyze.html file in a text editor and locate the analyzeButtonClick function near the bottom of the file.

analyzeButtonClick 事件处理程序函数会清除窗体,显示在 URL 中指定的图像,然后调用 AnalyzeImage 函数进行图像分析。The analyzeButtonClick event handler function clears the form, displays the image specified in the URL, then calls the AnalyzeImage function to analyze the image. 将以下代码复制并粘贴到 analyzeButtonClick 函数中。Copy and paste the following code into the analyzeButtonClick function.

function analyzeButtonClick() {

    // Clear the display fields.
    $("#sourceImage").attr("src", "#");
    $("#responseTextArea").val("");
    $("#captionSpan").text("");
    
    // Display the image.
    var sourceImageUrl = $("#inputImage").val();
    $("#sourceImage").attr("src", sourceImageUrl);
    
    AnalyzeImage(sourceImageUrl, $("#responseTextArea"), $("#captionSpan"));
}

添加用于 REST API 调用的包装器Add the wrapper for the REST API call

AnalyzeImage 函数包装进行图像分析的 REST API 调用。The AnalyzeImage function wraps the REST API call to analyze an image. 成功返回后,指定的文本区域将显示格式化的 JSON 分析结果,且指定的范围中将显示题注。Upon a successful return, the formatted JSON analysis will be displayed in the specified textarea, and the caption will be displayed in the specified span.

复制 AnalyzeImage 函数代码并将其粘贴到 analyzeButtonClick 函数下方。Copy and paste the AnalyzeImage function code to just underneath the analyzeButtonClick function.

/* Analyze the image at the specified URL by using Microsoft Cognitive Services Analyze Image API.
 * @param {string} sourceImageUrl - The URL to the image to analyze.
 * @param {<textarea> element} responseTextArea - The text area to display the JSON string returned
 *                             from the REST API call, or to display the error message if there was 
 *                             an error.
 * @param {<span> element} captionSpan - The span to display the image caption.
 */
function AnalyzeImage(sourceImageUrl, responseTextArea, captionSpan) {
    // Request parameters.
    var params = {
        "visualFeatures": "Categories,Description,Color",
        "details": "",
        "language": "en",
    };
    
    // Perform the REST API call.
    $.ajax({
        url: common.uriBasePreRegion + 
             $("#subscriptionRegionSelect").val() + 
             common.uriBasePostRegion + 
             common.uriBaseAnalyze +
             "?" + 
             $.param(params),
                    
        // Request headers.
        beforeSend: function(jqXHR){
            jqXHR.setRequestHeader("Content-Type","application/json");
            jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", 
                encodeURIComponent($("#subscriptionKeyInput").val()));
        },
        
        type: "POST",
        
        // Request body.
        data: '{"url": ' + '"' + sourceImageUrl + '"}',
    })
    
    .done(function(data) {
        // Show formatted JSON on webpage.
        responseTextArea.val(JSON.stringify(data, null, 2));
        
        // Extract and display the caption and confidence from the first caption in the description object.
        if (data.description && data.description.captions) {
            var caption = data.description.captions[0];
            
            if (caption.text && caption.confidence) {
                captionSpan.text("Caption: " + caption.text +
                    " (confidence: " + caption.confidence + ").");
            }
        }
    })
    
    .fail(function(jqXHR, textStatus, errorThrown) {
        // Prepare the error string.
        var errorString = (errorThrown === "") ? "Error. " : errorThrown + " (" + jqXHR.status + "): ";
        errorString += (jqXHR.responseText === "") ? "" : (jQuery.parseJSON(jqXHR.responseText).message) ? 
            jQuery.parseJSON(jqXHR.responseText).message : jQuery.parseJSON(jqXHR.responseText).error.message;
        
        // Put the error JSON in the response textarea.
        responseTextArea.val(JSON.stringify(jqXHR, null, 2));
        
        // Show the error message.
        alert(errorString);
    });
}

运行 Analyze 函数Run the Analyze function

保存 analyze.html 文件,然后在 Web 浏览器中将其打开。Save the analyze.html file and open it in a Web browser. 在“订阅密钥”字段中填写订阅密钥,并验证确保“订阅区域中”使用的区域正确无误 。Put your subscription key into the Subscription Key field and verify that you are using the correct region in Subscription Region. 输入图像 URL 进行分析,然后单击“分析图像”按钮以分析图像并查看结果 。Enter a URL to an image to analyze, then click the Analyze Image button to analyze an image and see the result.

识别地标Recognize a landmark

计算机视觉的地标功能可以分析图像中是否存在自然的和人工的地标,例如山脉或著名建筑。The Landmark feature of Computer Vision analyzes an image for natural and artificial landmarks, such as mountains or famous buildings. 分析完以后,地标功能会返回一个 JSON 对象,其中标识了图像中发现的地标。Once the analysis is complete, Landmark returns a JSON object that identifies the landmarks found in the image.

若要完成应用程序的地标功能,请执行以下步骤:To complete the Landmark feature of the application, perform the following steps:

为地标按钮添加事件处理程序代码Add the event handler code for the landmark button

在文本编辑器中打开 landmark.html 文件,找到文件底部的 landmarkButtonClick 函数。Open the landmark.html file in a text editor and locate the landmarkButtonClick function near the bottom of the file.

landmarkButtonClick 事件处理程序函数会清除窗体,显示在 URL 中指定的图像,然后调用 IdentifyLandmarks 函数进行图像分析。The landmarkButtonClick event handler function clears the form, displays the image specified in the URL, then calls the IdentifyLandmarks function to analyze the image. 将以下代码复制并粘贴到 landmarkButtonClick 函数中。Copy and paste the following code into the landmarkButtonClick function.

function landmarkButtonClick() {

    // Clear the display fields.
    $("#sourceImage").attr("src", "#");
    $("#responseTextArea").val("");
    $("#captionSpan").text("");
    
    // Display the image.
    var sourceImageUrl = $("#inputImage").val();
    $("#sourceImage").attr("src", sourceImageUrl);
    
    IdentifyLandmarks(sourceImageUrl, $("#responseTextArea"), $("#captionSpan"));
}

添加用于 REST API 调用的包装器Add the wrapper for the REST API call

IdentifyLandmarks 函数包装进行图像分析的 REST API 调用。The IdentifyLandmarks function wraps the REST API call to analyze an image. 成功返回以后,会在指定的文本区域显示格式化的 JSON 分析,并会按指定的时间间隔显示标题。Upon a successful return, the formatted JSON analysis will be displayed in the specified textarea, and the caption will be displayed in the specified span.

复制 IdentifyLandmarks 函数代码并将其粘贴到 landmarkButtonClick 函数下方。Copy and paste the IdentifyLandmarks function code to just underneath the landmarkButtonClick function.

/* Identify landmarks in the image at the specified URL by using Microsoft Cognitive Services 
 * Landmarks API.
 * @param {string} sourceImageUrl - The URL to the image to analyze for landmarks.
 * @param {<textarea> element} responseTextArea - The text area to display the JSON string returned
 *                             from the REST API call, or to display the error message if there was 
 *                             an error.
 * @param {<span> element} captionSpan - The span to display the image caption.
 */
function IdentifyLandmarks(sourceImageUrl, responseTextArea, captionSpan) {
    // Request parameters.
    var params = {
        "model": "landmarks"
    };
    
    // Perform the REST API call.
    $.ajax({
        url: common.uriBasePreRegion + 
             $("#subscriptionRegionSelect").val() + 
             common.uriBasePostRegion + 
             common.uriBaseLandmark +
             "?" + 
             $.param(params),
                    
        // Request headers.
        beforeSend: function(jqXHR){
            jqXHR.setRequestHeader("Content-Type","application/json");
            jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", 
                encodeURIComponent($("#subscriptionKeyInput").val()));
        },
        
        type: "POST",
        
        // Request body.
        data: '{"url": ' + '"' + sourceImageUrl + '"}',
    })
    
    .done(function(data) {
        // Show formatted JSON on webpage.
        responseTextArea.val(JSON.stringify(data, null, 2));
        
        // Extract and display the caption and confidence from the first caption in the description object.
        if (data.result && data.result.landmarks) {
            var landmark = data.result.landmarks[0];
            
            if (landmark.name && landmark.confidence) {
                captionSpan.text("Landmark: " + landmark.name +
                    " (confidence: " + landmark.confidence + ").");
            }
        }
    })
    
    .fail(function(jqXHR, textStatus, errorThrown) {
        // Prepare the error string.
        var errorString = (errorThrown === "") ? "Error. " : errorThrown + " (" + jqXHR.status + "): ";
        errorString += (jqXHR.responseText === "") ? "" : (jQuery.parseJSON(jqXHR.responseText).message) ? 
            jQuery.parseJSON(jqXHR.responseText).message : jQuery.parseJSON(jqXHR.responseText).error.message;
        
        // Put the error JSON in the response textarea.
        responseTextArea.val(JSON.stringify(jqXHR, null, 2));
        
        // Show the error message.
        alert(errorString);
    });
}

运行 landmark 函数Run the landmark function

保存 landmark.html 文件,然后在 Web 浏览器中将其打开。Save the landmark.html file and open it in a Web browser. 在“订阅密钥”字段中填写订阅密钥,并验证确保“订阅区域中”使用的区域正确无误 。Put your subscription key into the Subscription Key field and verify that you are using the correct region in Subscription Region. 输入要分析的图像的 URL,然后单击“分析图像”按钮对图像进行分析并查看结果。 Enter a URL to an image to analyze, then click the Analyze Image button to analyze an image and see the result.

识别名人Recognize celebrities

计算机视觉的名人功能分析图像中是否存在名人。The Celebrities feature of Computer Vision analyzes an image for famous people. 分析完以后,名人功能会返回一个 JSON 对象,其中标识了图像中发现的名人。Once the analysis is complete, Celebrities returns a JSON object that identifies the Celebrities found in the image.

若要完成应用程序的名人功能,请执行以下步骤:To complete the Celebrities feature of the application, perform the following steps:

为名人按钮添加事件处理程序代码Add the event handler code for the celebrities button

在文本编辑器中打开 celebrities.html 文件,找到文件底部的 celebritiesButtonClick 函数。Open the celebrities.html file in a text editor and locate the celebritiesButtonClick function near the bottom of the file.

celebritiesButtonClick 事件处理程序函数会清除窗体,显示在 URL 中指定的图像,然后调用 IdentifyCelebrities 函数进行图像分析。The celebritiesButtonClick event handler function clears the form, displays the image specified in the URL, then calls the IdentifyCelebrities function to analyze the image. 将以下代码复制并粘贴到 celebritiesButtonClick 函数中。Copy and paste the following code into the celebritiesButtonClick function.

function celebritiesButtonClick() {

    // Clear the display fields.
    $("#sourceImage").attr("src", "#");
    $("#responseTextArea").val("");
    $("#captionSpan").text("");
    
    // Display the image.
    var sourceImageUrl = $("#inputImage").val();
    $("#sourceImage").attr("src", sourceImageUrl);
    
    IdentifyCelebrities(sourceImageUrl, $("#responseTextArea"), $("#captionSpan"));
}

添加用于 REST API 调用的包装器Add the wrapper for the REST API call

/* Identify celebrities in the image at the specified URL by using Microsoft Cognitive Services 
 * Celebrities API.
 * @param {string} sourceImageUrl - The URL to the image to analyze for celebrities.
 * @param {<textarea> element} responseTextArea - The text area to display the JSON string returned
 *                             from the REST API call, or to display the error message if there was 
 *                             an error.
 * @param {<span> element} captionSpan - The span to display the image caption.
 */
function IdentifyCelebrities(sourceImageUrl, responseTextArea, captionSpan) {
    // Request parameters.
    var params = {
        "model": "celebrities"
    };
    
    // Perform the REST API call.
    $.ajax({
        url: common.uriBasePreRegion + 
             $("#subscriptionRegionSelect").val() + 
             common.uriBasePostRegion + 
             common.uriBaseCelebrities +
             "?" + 
             $.param(params),
                    
        // Request headers.
        beforeSend: function(jqXHR){
            jqXHR.setRequestHeader("Content-Type","application/json");
            jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", 
                encodeURIComponent($("#subscriptionKeyInput").val()));
        },
        
        type: "POST",
        
        // Request body.
        data: '{"url": ' + '"' + sourceImageUrl + '"}',
    })
    
    .done(function(data) {
        // Show formatted JSON on webpage.
        responseTextArea.val(JSON.stringify(data, null, 2));
        
        // Extract and display the caption and confidence from the first caption in the description object.
        if (data.result && data.result.celebrities) {
            var celebrity = data.result.celebrities[0];
            
            if (celebrity.name && celebrity.confidence) {
                captionSpan.text("Celebrity name: " + celebrity.name +
                    " (confidence: " + celebrity.confidence + ").");
            }
        }
    })
    
    .fail(function(jqXHR, textStatus, errorThrown) {
        // Prepare the error string.
        var errorString = (errorThrown === "") ? "Error. " : errorThrown + " (" + jqXHR.status + "): ";
        errorString += (jqXHR.responseText === "") ? "" : (jQuery.parseJSON(jqXHR.responseText).message) ? 
            jQuery.parseJSON(jqXHR.responseText).message : jQuery.parseJSON(jqXHR.responseText).error.message;
        
        // Put the error JSON in the response textarea.
        responseTextArea.val(JSON.stringify(jqXHR, null, 2));
        
        // Show the error message.
        alert(errorString);
    });
}

运行 celebrities 函数Run the celebrities function

保存 celebrities.html 文件,然后在 Web 浏览器中将其打开。Save the celebrities.html file and open it in a Web browser. 在“订阅密钥”字段中填写订阅密钥,并验证确保“订阅区域中”使用的区域正确无误 。Put your subscription key into the Subscription Key field and verify that you are using the correct region in Subscription Region. 输入图像 URL 进行分析,然后单击“分析”按钮以分析图像并查看结果 。Enter a URL to an image to analyze, then click the Analyze Image button to analyze an image and see the result.

智能生成缩略图Intelligently generate a thumbnail

计算机视觉的缩略图功能根据图像生成缩略图。The Thumbnail feature of Computer Vision generates a thumbnail from an image. 缩略图功能可以使用智能裁剪功能 来标识图像中的感兴趣区域,使缩略图聚焦在该区域,目的是生成更美的缩略图。By using the Smart Crop feature, the Thumbnail feature will identify the area of interest in an image and center the thumbnail on this area, to generate more aesthetically pleasing thumbnail images.

若要完成应用程序的缩略图功能,请执行以下步骤:To complete the Thumbnail feature of the application, perform the following steps:

为缩略图按钮添加事件处理程序代码Add the event handler code for the thumbnail button

在文本编辑器中打开 thumbnail.html 文件,找到文件底部的 thumbnailButtonClick 函数。Open the thumbnail.html file in a text editor and locate the thumbnailButtonClick function near the bottom of the file.

thumbnailButtonClick 事件处理程序函数会清除窗体,显示在 URL 中指定的图像,然后通过调用 getThumbnail 函数两次来创建两个缩略图,一个经过智能裁剪,另一个没有智能裁剪。The thumbnailButtonClick event handler function clears the form, displays the image specified in the URL, then calls the getThumbnail function twice to create two thumbnails, one smart cropped and one without smart crop. 将以下代码复制并粘贴到 thumbnailButtonClick 函数中。Copy and paste the following code into the thumbnailButtonClick function.

function thumbnailButtonClick() {

    // Clear the display fields.
    document.getElementById("sourceImage").src = "#";
    document.getElementById("thumbnailImageSmartCrop").src = "#";
    document.getElementById("thumbnailImageNonSmartCrop").src = "#";
    document.getElementById("responseTextArea").value = "";
    document.getElementById("captionSpan").text = "";
    
    // Display the image.
    var sourceImageUrl = document.getElementById("inputImage").value;
    document.getElementById("sourceImage").src = sourceImageUrl;
    
    // Get a smart cropped thumbnail.
    getThumbnail (sourceImageUrl, true, document.getElementById("thumbnailImageSmartCrop"), 
        document.getElementById("responseTextArea"));
    
    // Get a non-smart-cropped thumbnail.
    getThumbnail (sourceImageUrl, false, document.getElementById("thumbnailImageNonSmartCrop"),
        document.getElementById("responseTextArea"));
}

添加用于 REST API 调用的包装器Add the wrapper for the REST API call

getThumbnail 函数包装进行图像分析的 REST API 调用。The getThumbnail function wraps the REST API call to analyze an image. 成功返回后,缩略图会显示在指定的 img 元素中。Upon a successful return, the thumbnail will be displayed in the specified img element.

复制以下 getThumbnail 函数并将其粘贴到 thumbnailButtonClick 函数下方。Copy and paste the following getThumbnail function to just underneath the thumbnailButtonClick function.

/* Get a thumbnail of the image at the specified URL by using Microsoft Cognitive Services
 * Thumbnail API.
 * @param {string} sourceImageUrl URL to image.
 * @param {boolean} smartCropping Set to true to use the smart cropping feature which crops to the
 *                                more interesting area of an image; false to crop for the center
 *                                of the image.
 * @param {<img> element} imageElement The img element in the DOM which will display the thumbnail image.
 * @param {<textarea> element} responseTextArea - The text area to display the Response Headers returned
 *                             from the REST API call, or to display the error message if there was 
 *                             an error.
 */
function getThumbnail (sourceImageUrl, smartCropping, imageElement, responseTextArea) {
    // Create the HTTP Request object.
    var xhr = new XMLHttpRequest();
    
    // Request parameters.
    var params = "width=100&height=150&smartCropping=" + smartCropping.toString();

    // Build the full URI.
    var fullUri = common.uriBasePreRegion + 
                  document.getElementById("subscriptionRegionSelect").value + 
                  common.uriBasePostRegion + 
                  common.uriBaseThumbnail +
                  "?" + 
                  params;
    
    // Identify the request as a POST, with the URI and parameters.
    xhr.open("POST", fullUri);
    
    // Add the request headers.
    xhr.setRequestHeader("Content-Type","application/json");
    xhr.setRequestHeader("Ocp-Apim-Subscription-Key", 
        encodeURIComponent(document.getElementById("subscriptionKeyInput").value));
    
    // Set the response type to "blob" for the thumbnail image data.
    xhr.responseType = "blob";
    
    // Process the result of the REST API call.
    xhr.onreadystatechange = function(e) {
        if(xhr.readyState === XMLHttpRequest.DONE) {
            
            // Thumbnail successfully created.
            if (xhr.status === 200) {
                // Show response headers.
                var s = JSON.stringify(xhr.getAllResponseHeaders(), null, 2);
                responseTextArea.value = JSON.stringify(xhr.getAllResponseHeaders(), null, 2);
                
                // Show thumbnail image.
                var urlCreator = window.URL || window.webkitURL;
                var imageUrl = urlCreator.createObjectURL(this.response);
                imageElement.src = imageUrl;
            } else {
                // Display the error message. The error message is the response body as a JSON string. 
                // The code in this code block extracts the JSON string from the blob response.
                var reader = new FileReader();
                
                // This event fires after the blob has been read.
                reader.addEventListener('loadend', (e) => {
                    responseTextArea.value = JSON.stringify(JSON.parse(e.srcElement.result), null, 2);
                });
                
                // Start reading the blob as text.
                reader.readAsText(xhr.response);
            }
        }
    }
    
    // Execute the REST API call.
    xhr.send('{"url": ' + '"' + sourceImageUrl + '"}');
}

运行 thumbnail 函数Run the thumbnail function

保存 thumbnail.html 文件,然后在 Web 浏览器中将其打开。Save the thumbnail.html file and open it in a Web browser. 将订阅密钥置于“订阅密钥”字段中, 然后在“订阅区域”中验证是否使用了正确的区域。 Put your subscription key into the Subscription Key field and verify that you are using the correct region in Subscription Region. 输入要分析的图像的 URL,然后单击“生成缩略图”按钮对图像进行分析并查看结果。 Enter a URL to an image to analyze, then click the Generate Thumbnails button to analyze an image and see the result.

读取打印文本 (OCR)Read printed text (OCR)

计算机视觉的光学字符识别 (OCR) 功能分析图像中是否有印刷体文本。The Optical Character Recognition (OCR) feature of Computer Vision analyzes an image of printed text. 分析完以后,OCR 会返回一个 JSON 对象,其中包含图像中的文本和文本位置。After the analysis is complete, OCR returns a JSON object that contains the text and the location of the text in the image.

若要完成应用程序的 OCR 功能,请执行以下步骤:To complete the OCR feature of the application, perform the following steps:

为 OCR 按钮添加事件处理程序代码Add the event handler code for the OCR button

在文本编辑器中打开 ocr.html 文件,找到文件底部的 ocrButtonClick 函数。Open the ocr.html file in a text editor and locate the ocrButtonClick function near the bottom of the file.

ocrButtonClick 事件处理程序函数会清除窗体,显示在 URL 中指定的图像,然后调用 ReadOcrImage 函数进行图像分析。The ocrButtonClick event handler function clears the form, displays the image specified in the URL, then calls the ReadOcrImage function to analyze the image. 将以下代码复制并粘贴到 ocrButtonClick 函数中。Copy and paste the following code into the ocrButtonClick function.

function ocrButtonClick() {

    // Clear the display fields.
    $("#sourceImage").attr("src", "#");
    $("#responseTextArea").val("");
    $("#captionSpan").text("");
    
    // Display the image.
    var sourceImageUrl = $("#inputImage").val();
    $("#sourceImage").attr("src", sourceImageUrl);
    
    ReadOcrImage(sourceImageUrl, $("#responseTextArea"));
}

添加用于 REST API 调用的包装器Add the wrapper for the REST API call

ReadOcrImage 函数包装进行图像分析的 REST API 调用。The ReadOcrImage function wraps the REST API call to analyze an image. 成功返回以后,会在指定的文本区域显示格式化的 JSON,用于描述文本和文本位置。Upon a successful return, the formatted JSON describing the text and the location of the text will be displayed in the specified textarea.

复制以下 ReadOcrImage 函数并将其粘贴到 ocrButtonClick 函数下方。Copy and paste the following ReadOcrImage function to just underneath the ocrButtonClick function.

/* Recognize and read printed text in an image at the specified URL by using Microsoft Cognitive 
 * Services OCR API.
 * @param {string} sourceImageUrl - The URL to the image to analyze for printed text.
 * @param {<textarea> element} responseTextArea - The text area to display the JSON string returned
 *                             from the REST API call, or to display the error message if there was 
 *                             an error.
 */
function ReadOcrImage(sourceImageUrl, responseTextArea) {
    // Request parameters.
    var params = {
        "language": "unk",
        "detectOrientation ": "true",
    };

    // Perform the REST API call.
    $.ajax({
        url: common.uriBasePreRegion + 
             $("#subscriptionRegionSelect").val() + 
             common.uriBasePostRegion + 
             common.uriBaseOcr +
             "?" + 
             $.param(params),
        
        // Request headers.
        beforeSend: function(jqXHR){
            jqXHR.setRequestHeader("Content-Type","application/json");
            jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", 
                encodeURIComponent($("#subscriptionKeyInput").val()));
        },
        
        type: "POST",
        
        // Request body.
        data: '{"url": ' + '"' + sourceImageUrl + '"}',
    })
    
    .done(function(data) {
        // Show formatted JSON on webpage.
        responseTextArea.val(JSON.stringify(data, null, 2));
    })
    
    .fail(function(jqXHR, textStatus, errorThrown) {
        // Put the JSON description into the text area.
        responseTextArea.val(JSON.stringify(jqXHR, null, 2));
        
        // Display error message.
        var errorString = (errorThrown === "") ? "Error. " : errorThrown + " (" + jqXHR.status + "): ";
        errorString += (jqXHR.responseText === "") ? "" : (jQuery.parseJSON(jqXHR.responseText).message) ? 
            jQuery.parseJSON(jqXHR.responseText).message : jQuery.parseJSON(jqXHR.responseText).error.message;
        alert(errorString);
    });
}

运行 OCR 函数Run the OCR function

保存 ocr.html 文件,然后在 Web 浏览器中将其打开。Save the ocr.html file and open it in a Web browser. 在“订阅密钥”字段中填写订阅密钥,并验证确保“订阅区域中”使用的区域正确无误 。Put your subscription key into the Subscription Key field and verify that you are using the correct region in Subscription Region. 输入要读取其文本的图像的 URL,然后单击“读取图像”按钮对图像进行分析并查看结果。 Enter a URL to an image of text to read, then click the Read Image button to analyze an image and see the result.

读取手写文本(手写识别)Read handwritten text (handwriting recognition)

计算机视觉的手写体识别功能可分析图像中的手写文本。The Handwriting Recognition feature of Computer Vision analyzes an image of handwritten text. 分析完以后,手写识别功能会返回一个 JSON 对象,其中包含图像中的文本和文本位置。After the analysis is complete, Handwriting Recognition returns a JSON object that contains the text and the location of the text in the image.

若要完成应用程序的手写识别功能,请执行以下步骤:To complete the Handwriting Recognition feature of the application, perform the following steps:

为手写按钮添加事件处理程序代码Add the event handler code for the handwriting button

在文本编辑器中打开 handwriting.html 文件,找到文件底部的 handwritingButtonClick 函数。Open the handwriting.html file in a text editor and locate the handwritingButtonClick function near the bottom of the file.

handwritingButtonClick 事件处理程序函数会清除窗体,显示在 URL 中指定的图像,然后调用 HandwritingImage 函数进行图像分析。The handwritingButtonClick event handler function clears the form, displays the image specified in the URL, then calls the HandwritingImage function to analyze the image.

将以下代码复制并粘贴到 handwritingButtonClick 函数中。Copy and paste the following code into the handwritingButtonClick function.

function handwritingButtonClick() {

    // Clear the display fields.
    $("#sourceImage").attr("src", "#");
    $("#responseTextArea").val("");
    
    // Display the image.
    var sourceImageUrl = $("#inputImage").val();
    $("#sourceImage").attr("src", sourceImageUrl);
    
    ReadHandwrittenImage(sourceImageUrl, $("#responseTextArea"));
}

添加用于 REST API 调用的包装器Add the wrapper for the REST API call

ReadHandwrittenImage 函数包装两个进行图像分析所需的 REST API 调用。The ReadHandwrittenImage function wraps the two REST API calls needed to analyze an image. 由于手写识别很耗时,因此使用一个两步过程。Because Handwriting Recognition is a time consuming process, a two step process is used. 第一个调用提交图像进行分析;第二个调用检索完成处理时检测到的文本。The first call submits the image for processing; the second call retrieves the detected text when the processing is complete.

检索文本以后,会在指定的文本区域显示格式化的 JSON,用于描述文本和文本位置。After the text is retrieved, the formatted JSON describing the text and the location of the text will be displayed in the specified textarea.

复制以下 ReadHandwrittenImage 函数并将其粘贴到 handwritingButtonClick 函数下方。Copy and paste the following ReadHandwrittenImage function to just underneath the handwritingButtonClick function.

/* Recognize and read text from an image of handwriting at the specified URL by using Microsoft 
 * Cognitive Services Recognize Handwritten Text API.
 * @param {string} sourceImageUrl - The URL to the image to analyze for handwriting.
 * @param {<textarea> element} responseTextArea - The text area to display the JSON string returned
 *                             from the REST API call, or to display the error message if there was 
 *                             an error.
 */
function ReadHandwrittenImage(sourceImageUrl, responseTextArea) {
    // Request parameters.
    var params = {
        "handwriting": "true",
    };

    // This operation requires two REST API calls. One to submit the image for processing,
    // the other to retrieve the text found in the image. 
    //
    // Perform the first REST API call to submit the image for processing.
    $.ajax({
        url: common.uriBasePreRegion + 
             $("#subscriptionRegionSelect").val() + 
             common.uriBasePostRegion + 
             common.uriBaseHandwriting +
             "?" + 
             $.param(params),
        
        // Request headers.
        beforeSend: function(jqXHR){
            jqXHR.setRequestHeader("Content-Type","application/json");
            jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", 
                encodeURIComponent($("#subscriptionKeyInput").val()));
        },
        
        type: "POST",
        
        // Request body.
        data: '{"url": ' + '"' + sourceImageUrl + '"}',
    })
    
    .done(function(data, textStatus, jqXHR) {
        // Show progress.
        responseTextArea.val("Handwritten image submitted.");
        
        // Note: The response may not be immediately available. Handwriting Recognition is an
        // async operation that can take a variable amount of time depending on the length
        // of the text you want to recognize. You may need to wait or retry this GET operation.
        //
        // Try once per second for up to ten seconds to receive the result.
        var tries = 10;
        var waitTime = 100;
        var taskCompleted = false;
        
        var timeoutID = setInterval(function () { 
            // Limit the number of calls.
            if (--tries <= 0) {
                window.clearTimeout(timeoutID);
                responseTextArea.val("The response was not available in the time allowed.");
                return;
            }

            // The "Operation-Location" in the response contains the URI to retrieve the recognized text.
            var operationLocation = jqXHR.getResponseHeader("Operation-Location");
            
            // Perform the second REST API call and get the response.
            $.ajax({
                url: operationLocation,
                
                // Request headers.
                beforeSend: function(jqXHR){
                    jqXHR.setRequestHeader("Content-Type","application/json");
                    jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key",
                        encodeURIComponent($("#subscriptionKeyInput").val()));
                },
                
                type: "GET",
            })
            
            .done(function(data) {
                // If the result is not yet available, return.
                if (data.status && (data.status === "NotStarted" || data.status === "Running")) {
                    return;
                }
                
                // Show formatted JSON on webpage.
                responseTextArea.val(JSON.stringify(data, null, 2));
                
                // Indicate the task is complete and clear the timer.
                taskCompleted = true;
                window.clearTimeout(timeoutID);
            })
            
            .fail(function(jqXHR, textStatus, errorThrown) {
                // Indicate the task is complete and clear the timer.
                taskCompleted = true;
                window.clearTimeout(timeoutID);
                
                // Display error message.
                var errorString = (errorThrown === "") ? "Error. " : errorThrown + " (" + jqXHR.status + "): ";
                errorString += (jqXHR.responseText === "") ? "" : (jQuery.parseJSON(jqXHR.responseText).message) ? 
                    jQuery.parseJSON(jqXHR.responseText).message : jQuery.parseJSON(jqXHR.responseText).error.message;
                alert(errorString);
            });
        }, waitTime);
    })
    
    .fail(function(jqXHR, textStatus, errorThrown) {
        // Put the JSON description into the text area.
        responseTextArea.val(JSON.stringify(jqXHR, null, 2));
        
        // Display error message.
        var errorString = (errorThrown === "") ? "Error. " : errorThrown + " (" + jqXHR.status + "): ";
        errorString += (jqXHR.responseText === "") ? "" : (jQuery.parseJSON(jqXHR.responseText).message) ? 
            jQuery.parseJSON(jqXHR.responseText).message : jQuery.parseJSON(jqXHR.responseText).error.message;
        alert(errorString);
    });
}

运行 handwriting 函数Run the handwriting function

保存 handwriting.html 文件,然后在 Web 浏览器中将其打开。Save the handwriting.html file and open it in a Web browser. 在“订阅密钥”字段中填写订阅密钥,并验证确保“订阅区域中”使用的区域正确无误 。Put your subscription key into the Subscription Key field and verify that you are using the correct region in Subscription Region. 输入要读取其文本的图像的 URL,然后单击“读取图像”按钮对图像进行分析并查看结果。 Enter a URL to an image of text to read, then click the Read Image button to analyze an image and see the result.

后续步骤Next steps

在本指南中,已使用计算机视觉 REST API 和 JavaScript 来测试了许多可用的图像分析功能。In this guide, you used the Computer Vision REST API with JavaScript to test many of the available image analysis features. 接下来,请参阅参考文档以了解有关所涉及 API 的更多信息。Next, see the reference documentation to learn more about the APIs involved.