快速入門:使用 Bing 圖像式搜尋用戶端程式庫
警告
2020 年 10 月 30 日,Bing 搜尋 API 已從 Azure AI 服務移至Bing 搜尋服務。 本文件僅供參考之用。 如需更新的文件,請參閱 Bing 搜尋 API 文件。 如需針對 Bing 搜尋建立新 Azure 資源的指示,請參閱透過 Azure Marketplace 建立 Bing 搜尋資源。
使用本快速入門,開始使用 C# 用戶端程式庫從 Bing 圖像式搜尋服務取得影像見解。 雖然 Bing 圖像式搜尋具有與大部分程式設計語言相容的 REST API,但此用戶端程式庫可提供簡單的方法,將服務整合到您的應用程式。 此範例的原始程式碼可以在 GitHub 上找到。
參考文件 | 程式庫來源程式碼 | 套件 (NuGet) | 範例
Prerequisites
- Visual Studio 2019。
- 如果您使用 Linux/MacOS,則可以使用 Mono來執行此應用程式。
- NuGet 圖像式搜尋套件。
- 在 Visual Studio 的 [方案總管] 中,以滑鼠右鍵按一下專案,然後從功能表選取
Manage NuGet Packages
。 安裝Microsoft.Azure.CognitiveServices.Search.VisualSearch
套件。 安裝 NuGet 套件也會安裝:- Microsoft.Rest.ClientRuntime
- Microsoft.Rest.ClientRuntime.Azure
- Newtonsoft.Json
- 在 Visual Studio 的 [方案總管] 中,以滑鼠右鍵按一下專案,然後從功能表選取
建立 Azure 資源
藉由建立下列其中一項 Azure 資源,開始使用 Bing 圖像式搜尋 API:
- 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
- 選取
S9
定價層。
- 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
- 針對您的應用程式,跨多個 Azure AI 服務使用相同的金鑰和端點。
建立應用程式並將其初始化
在 Visual Studio 中,建立新專案。 接著,新增下列指示詞。
using Microsoft.Azure.CognitiveServices.Search.VisualSearch; using Microsoft.Azure.CognitiveServices.Search.VisualSearch.Models;
使用訂用帳戶金鑰具現化用戶端。
var client = new VisualSearchClient(new ApiKeyServiceClientCredentials("YOUR-ACCESS-KEY"));
傳送搜尋要求
在影像中建立
FileStream
(在此案例中為TestImages/image.jpg
)。 接著,使用用戶端透過client.Images.VisualSearchMethodAsync()
傳送搜尋要求。System.IO.FileStream stream = new FileStream(Path.Combine("TestImages", "image.jpg"), FileMode.Open); // The knowledgeRequest parameter is not required if an image binary is passed in the request body var visualSearchResults = client.Images.VisualSearchMethodAsync(image: stream, knowledgeRequest: (string)null).Result;
剖析先前查詢的結果:
// Visual Search results if (visualSearchResults.Image?.ImageInsightsToken != null) { Console.WriteLine($"Uploaded image insights token: {visualSearchResults.Image.ImageInsightsToken}"); } else { Console.WriteLine("Couldn't find image insights token!"); } // List of tags if (visualSearchResults.Tags.Count > 0) { var firstTagResult = visualSearchResults.Tags[0]; Console.WriteLine($"Visual search tag count: {visualSearchResults.Tags.Count}"); // List of actions in first tag if (firstTagResult.Actions.Count > 0) { var firstActionResult = firstTagResult.Actions[0]; Console.WriteLine($"First tag action count: {firstTagResult.Actions.Count}"); Console.WriteLine($"First tag action type: {firstActionResult.ActionType}"); } else { Console.WriteLine("Couldn't find tag actions!"); } }
後續步驟
使用本快速入門,開始使用 Java 用戶端程式庫從 Bing 圖像式搜尋服務取得影像見解。 雖然 Bing 圖像式搜尋具有與大部分程式設計語言相容的 REST API,但此用戶端程式庫可提供簡單的方法,將服務整合到您的應用程式。 此快速入門的原始程式碼可以在 GitHub 上找到。
使用適用於 Java 的 Bing 圖像式搜尋用戶端程式庫:
- 上傳影像以傳送圖像式搜尋要求。
- 取得影像深入解析權杖和圖像式搜尋標籤。
參考文件 | 程式庫原始程式碼 | 成品 (Maven) | 範例
必要條件
- Azure 訂用帳戶 - 建立免費帳戶
- 最新版的 Java Development Kit (JDK)
- Gradle 建置工具,或其他相依性管理員
建立 Azure 資源
藉由建立下列其中一項 Azure 資源,開始使用 Bing 圖像式搜尋 API:
- 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
- 選取
S9
定價層。
- 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
- 針對您的應用程式,跨多個 Azure AI 服務使用相同的金鑰和端點。
從資源取得金鑰之後,請為名為 BING_SEARCH_V7_SUBSCRIPTION_KEY
的金鑰建立環境變數。
建立新的 Gradle 專案
在主控台視窗 (例如 cmd、PowerShell 或 Bash) 中,為您的應用程式建立新的目錄,並瀏覽至該目錄。
mkdir myapp && cd myapp
從您的工作目錄執行 gradle init
命令。 此命令會建立 Gradle 的基本組建檔案,包括 build.gradle.kts,此檔案將在執行階段用來建立及設定您的應用程式。
gradle init --type basic
出現選擇 DSL 的提示時,請選取 [Kotlin]。
找出 build.gradle.kts,並使用您慣用的 IDE 或文字編輯器加以開啟。 然後,在此組建組態中複製下列內容:
plugins {
java
application
}
application {
mainClassName = "main.java.BingVisualSearchSample"
}
repositories {
mavenCentral()
}
dependencies {
compile("org.slf4j:slf4j-simple:1.7.25")
compile("com.microsoft.azure.cognitiveservices:azure-cognitiveservices-visualsearch:1.0.2-beta")
compile("com.google.code.gson:gson:2.8.5")
}
建立範例應用程式的資料夾。 從工作目錄執行下列命令:
mkdir -p src/main/java
為您想要上傳至 API 的影像建立資料夾。 將影像放在 resources 資料夾內。
mkdir -p src/main/resources
瀏覽至新的資料夾,並建立名為 BingVisualSearchSample.java 的檔案。 在您慣用的編輯器或 IDE 中開啟該檔案,並新增下列 import
陳述式:
package main.java;
import com.google.common.io.ByteStreams;
import com.google.gson.Gson;
import com.microsoft.azure.cognitiveservices.search.visualsearch.BingVisualSearchAPI;
import com.microsoft.azure.cognitiveservices.search.visualsearch.BingVisualSearchManager;
import com.microsoft.azure.cognitiveservices.search.visualsearch.models.CropArea;
import com.microsoft.azure.cognitiveservices.search.visualsearch.models.ErrorResponseException;
import com.microsoft.azure.cognitiveservices.search.visualsearch.models.Filters;
import com.microsoft.azure.cognitiveservices.search.visualsearch.models.ImageInfo;
import com.microsoft.azure.cognitiveservices.search.visualsearch.models.ImageKnowledge;
import com.microsoft.azure.cognitiveservices.search.visualsearch.models.ImageTag;
import com.microsoft.azure.cognitiveservices.search.visualsearch.models.KnowledgeRequest;
import com.microsoft.azure.cognitiveservices.search.visualsearch.models.VisualSearchRequest;
然後,建立新的類別。
public class BingVisualSearchSample {
}
在應用程式的 main
方法中,為資源的 Azure 端點和金鑰建立變數。 如果您在啟動應用程式後才建立環境變數,則必須先關閉執行該應用程式的編輯器、IDE 或殼層,再重新加以開啟,才能存取該變數。 然後,為您要上傳的影像建立 byte[]
。 為稍後將定義的方法建立 try
區塊,然後載入影像,並使用 toByteArray()
將其轉換成位元組。
// IMPORTANT: MAKE SURE TO USE S9 PRICING TIER OF THE BING SEARCH V7 API KEY FOR VISUAL SEARCH.
// Otherwise, you will get an invalid subscription key error.
public static void main(String[] args) {
// Set the BING_SEARCH_V7_SUBSCRIPTION_KEY environment variable with your subscription key,
// then reopen your command prompt or IDE. If not, you may get an API key not found exception.
final String subscriptionKey = System.getenv("BING_SEARCH_V7_SUBSCRIPTION_KEY");
BingVisualSearchAPI client = BingVisualSearchManager.authenticate(subscriptionKey);
//runSample(client);
byte[] imageBytes;
try {
imageBytes = ByteStreams.toByteArray(ClassLoader.getSystemClassLoader().getResourceAsStream("image.jpg"));
visualSearch(client, imageBytes);
searchWithCropArea(client, imageBytes);
// wait 1 second to avoid rate limiting
Thread.sleep(1000);
searchWithFilter(client);
searchUsingCropArea(client);
searchUsingInsightToken(client);
}
catch (java.io.IOException f) {
System.out.println(f.getMessage());
f.printStackTrace();
}
catch (java.lang.InterruptedException f){
f.printStackTrace();
}
}
安裝用戶端程式庫
本快速入門會使用 Gradle 相依性管理員。 您可以在 Maven 中央存放庫中找到用戶端程式庫和其他相依性管理員的資訊。
在專案的 build.gradle.kts 檔案中,請務必將用戶端程式庫納入為 implementation
陳述式。
dependencies {
compile("org.slf4j:slf4j-simple:1.7.25")
compile("com.microsoft.azure.cognitiveservices:azure-cognitiveservices-visualsearch:1.0.2-beta")
compile("com.google.code.gson:gson:2.8.5")
}
程式碼範例
這些程式碼片段說明如何使用 Bing 圖像式搜尋用戶端程式庫和 Java 來執行下列工作:
驗證用戶端
注意
本快速入門假設您已針對名為 BING_SEARCH_V7_SUBSCRIPTION_KEY
的 Bing 圖像式搜尋金鑰建立環境變數。
在您的 main 方法中,請務必使用您的訂用帳戶金鑰來具現化 BingVisualSearchAPI 物件。
BingVisualSearchAPI client = BingVisualSearchManager.authenticate(subscriptionKey);
傳送圖像式搜尋要求
在新方法中,請使用用戶端的 bingImages().visualSearch() 方法來傳送影像位元組陣列 (以 main()
方法建立的)。
public static void visualSearch(BingVisualSearchAPI client, byte[] imageBytes){
System.out.println("Calling Bing Visual Search with image binary");
ImageKnowledge visualSearchResults = client.bingImages().visualSearch()
.withImage(imageBytes)
.execute();
PrintVisualSearchResults(visualSearchResults);
}
列印影像深入解析權杖和圖像式搜尋標籤
檢查 ImageKnowledge 物件是否為 Null。 如果不是,請列印影像深入解析權杖、標籤數目、動作數目,和第一個動作類型。
static void PrintVisualSearchResults(ImageKnowledge visualSearchResults) {
if (visualSearchResults == null) {
System.out.println("No visual search result data.");
} else {
// Print token
if (visualSearchResults.image() != null && visualSearchResults.image().imageInsightsToken() != null) {
System.out.println("Found uploaded image insights token: " + visualSearchResults.image().imageInsightsToken());
} else {
System.out.println("Couldn't find image insights token!");
}
// List tags
if (visualSearchResults.tags() != null && visualSearchResults.tags().size() > 0) {
System.out.format("Found visual search tag count: %d\n", visualSearchResults.tags().size());
ImageTag firstTagResult = visualSearchResults.tags().get(0);
// List of actions in first tag
if (firstTagResult.actions() != null && firstTagResult.actions().size() > 0) {
System.out.format("Found first tag action count: %d\n", firstTagResult.actions().size());
System.out.println("Found first tag action type: " + firstTagResult.actions().get(0).actionType());
}
} else {
System.out.println("Couldn't find image tags!");
}
}
}
執行應用程式
您可以使用下列命令來建置應用程式:
gradle build
使用 run
目標執行應用程式:
gradle run
清除資源
如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除其關聯的任何其他資源。
後續步驟
使用本快速入門,開始使用 JavaScript 用戶端程式庫從 Bing 圖像式搜尋服務取得影像見解。 雖然 Bing 圖像式搜尋具有與大部分程式設計語言相容的 REST API,但此用戶端程式庫可提供簡單的方法,將服務整合到您的應用程式。 此範例的原始程式碼可以在 GitHub 上找到。
必要條件
- 最新版的 Node.js。
- 適用於 JavaScript 的 Bing 圖像式搜尋 SDK
- 若要安裝,請執行
npm install @azure/cognitiveservices-visualsearch
- 若要安裝,請執行
- 來自
@azure/ms-rest-azure-js
套件中的CognitiveServicesCredentials
類別,用來驗證用戶端。- 若要安裝,請執行
npm install @azure/ms-rest-azure-js
- 若要安裝,請執行
建立 Azure 資源
藉由建立下列其中一項 Azure 資源,開始使用 Bing 圖像式搜尋 API:
- 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
- 選取
S9
定價層。
- 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
- 針對您的應用程式,跨多個 Azure AI 服務使用相同的金鑰和端點。
建立應用程式並將其初始化
在您最愛的 IDE 或編輯器中建立新的 JavaScript 檔案,然後新增下列需求。 接著為您的訂用帳戶金鑰、自訂組態識別碼,以及您要上傳影像的檔案路徑,建立變數。
const os = require("os"); const async = require('async'); const fs = require('fs'); const Search = require('@azure/cognitiveservices-visualsearch'); const CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials; let keyVar = 'YOUR-VISUAL-SEARCH-ACCESS-KEY'; let credentials = new CognitiveServicesCredentials(keyVar); let filePath = "../Data/image.jpg";
具現化用戶端。
let visualSearchClient = new Search.VisualSearchClient(credentials);
搜尋影像
使用
fs.createReadStream()
來讀入您的影像檔案,以及為您的搜尋要求和結果建立變數。 然後使用用戶端來搜尋影像。let fileStream = fs.createReadStream(filePath); let visualSearchRequest = JSON.stringify({}); let visualSearchResults; try { visualSearchResults = await visualSearchClient.images.visualSearch({ image: fileStream, knowledgeRequest: visualSearchRequest }); console.log("Search visual search request with binary of image"); } catch (err) { console.log("Encountered exception. " + err.message); }
剖析先前查詢的結果:
// Visual Search results if (visualSearchResults.image.imageInsightsToken) { console.log(`Uploaded image insights token: ${visualSearchResults.image.imageInsightsToken}`); } else { console.log("Couldn't find image insights token!"); } // List of tags if (visualSearchResults.tags.length > 0) { let firstTagResult = visualSearchResults.tags[0]; console.log(`Visual search tag count: ${visualSearchResults.tags.length}`); // List of actions in first tag if (firstTagResult.actions.length > 0) { let firstActionResult = firstTagResult.actions[0]; console.log(`First tag action count: ${firstTagResult.actions.length}`); console.log(`First tag action type: ${firstActionResult.actionType}`); } else { console.log("Couldn't find tag actions!"); } } else { console.log("Couldn't find image tags!"); }
後續步驟
使用本快速入門,開始使用 Python 用戶端程式庫從 Bing 圖像式搜尋服務取得影像見解。 雖然 Bing 圖像式搜尋具有與大部分程式設計語言相容的 REST API,但此用戶端程式庫可提供簡單的方法,將服務整合到您的應用程式。 此範例的原始程式碼位於 GitHub
參考文件 | 程式庫來源程式碼 | 套件 (PyPi) | 範例
Prerequisites
- Python 2.x 或 3.x
- 建議使用虛擬環境。 使用 venv 模組來安裝和初始化虛擬環境。
- 適用於 Python 的 Bing 圖像式搜尋用戶端程式庫。 您可以使用下列命令加以安裝:
cd mytestenv
python -m pip install azure-cognitiveservices-search-visualsearch
建立 Azure 資源
藉由建立下列其中一項 Azure 資源,開始使用 Bing 圖像式搜尋 API:
- 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
- 選取
S9
定價層。
- 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
- 針對您的應用程式,跨多個 Azure AI 服務使用相同的金鑰和端點。
建立應用程式並將其初始化
在您慣用的 IDE 或編輯器中建立新的 Python 專案,以及新增下列匯入陳述式。
import http.client, urllib.parse import json import os.path from azure.cognitiveservices.search.visualsearch import VisualSearchClient from azure.cognitiveservices.search.visualsearch.models import ( VisualSearchRequest, CropArea, ImageInfo, Filters, KnowledgeRequest, ) from msrest.authentication import CognitiveServicesCredentials
為您的訂用帳戶金鑰、自訂組態識別碼,以及您要上傳的影像,建立變數。
subscription_key = 'YOUR-VISUAL-SEARCH-ACCESS-KEY' PATH = 'C:\\Users\\USER\\azure-cognitive-samples\\mytestenv\\TestImages\\' image_path = os.path.join(PATH, "image.jpg")
具現化用戶端
client = VisualSearchClient(endpoint="https://api.cognitive.microsoft.com", credentials=CognitiveServicesCredentials(subscription_key))
傳送搜尋要求
在影像檔案開啟狀態下,將
VisualSearchRequest()
序列化,並將它當作visual_search()
的knowledge_request
參數傳遞。with open(image_path, "rb") as image_fd: # You need to pass the serialized form of the model knowledge_request = json.dumps(VisualSearchRequest().serialize()) print("\r\nSearch visual search request with binary of dog image") result = client.images.visual_search(image=image_fd, knowledge_request=knowledge_request)
如果傳回了任何結果,請列印結果、標記及第一個標記中的動作。
if not result: print("No visual search result data.") # Visual Search results if result.image.image_insights_token: print("Uploaded image insights token: {}".format(result.image.image_insights_token)) else: print("Couldn't find image insights token!") # List of tags if result.tags: first_tag = result.tags[0] print("Visual search tag count: {}".format(len(result.tags))) # List of actions in first tag if first_tag.actions: first_tag_action = first_tag.actions[0] print("First tag action count: {}".format(len(first_tag.actions))) print("First tag action type: {}".format(first_tag_action.action_type)) else: print("Couldn't find tag actions!") else: print("Couldn't find image tags!")