クイック スタート: Bing Image Search REST API と Python を使用して画像を検索する

警告

2020 年 10 月 30 日、Bing Search API は Azure AI サービスから Bing Search Services に移行されました。 このドキュメントは参考用に提供されています。 更新されたドキュメントについては、 Bing検索 API のドキュメントを参照してください。 Bing検索用の新しい Azure リソースを作成する手順については、「 Azure Marketplace を使用して Bing Search リソースを作成する」を参照してください。

このクイック スタートでは、Bing Image Search API に検索要求を送信する方法について説明します。 この Python アプリケーションは、API に検索クエリを送信し、結果の最初の画像の URL を表示します。 このアプリケーションは Python で記述されていますが、API はほとんどのプログラミング言語と互換性のある RESTful Web サービスです。

前提条件

アプリケーションを作成して初期化する

  1. お気に入りの IDE またはエディターで新しい Python ファイルを作成し、次のモジュールをインポートします。 サブスクリプション キー、検索エンドポイント、検索用語の変数を作成します。 search_urlの場合は、次のコードでグローバル エンドポイントを使用することも、リソースの Azure portal に表示されるカスタム サブドメイン エンドポイントを使用することもできます。

    import requests
    import matplotlib.pyplot as plt
    from PIL import Image
    from io import BytesIO
    
    subscription_key = "your-subscription-key"
    search_url = "https://api.cognitive.microsoft.com/bing/v7.0/images/search"
    search_term = "puppies"
    
  2. ディクショナリを作成し、キーを値として追加して、サブスクリプション キーを Ocp-Apim-Subscription-Key ヘッダーに追加します。

    headers = {"Ocp-Apim-Subscription-Key" : subscription_key}
    

検索要求を作成して送信する

  1. 検索要求のパラメーターのディクショナリを作成します。 q パラメーターに検索語句を追加します。 license パラメーターを public に設定して、パブリック ドメイン内の画像を検索します。 imageType を photo に設定して、写真のみを検索します。

    params  = {"q": search_term, "license": "public", "imageType": "photo"}
    
  2. requests ライブラリを使用して、Bing Image Search API を呼び出します。 要求にヘッダーとパラメーターを追加し、応答を JSON オブジェクトとして返します。 応答の thumbnailUrl フィールドから複数のサムネイル画像への URL を取得します。

    response = requests.get(search_url, headers=headers, params=params)
    response.raise_for_status()
    search_results = response.json()
    thumbnail_urls = [img["thumbnailUrl"] for img in search_results["value"][:16]]
    

応答を表示する

  1. matplotlib ライブラリを使用して、4 つの列と 4 つの行を含む新しい図形を作成します。

  2. 図の行と列を反復処理し、PIL ライブラリの Image.open() メソッドを使用して、各スペースに画像のサムネイルを追加します。

  3. plt.show() を使用して図を描画し、画像を表示します。

    f, axes = plt.subplots(4, 4)
    for i in range(4):
        for j in range(4):
            image_data = requests.get(thumbnail_urls[i+4*j])
            image_data.raise_for_status()
            image = Image.open(BytesIO(image_data.content))        
            axes[i][j].imshow(image)
            axes[i][j].axis("off")
    plt.show()
    

JSON 応答の例

Bing Image Search API からの応答は JSON として返されます。 このサンプル応答は、1 つの結果を表示するために切り捨てられました。

{
"_type":"Images",
"instrumentation":{
    "_type":"ResponseInstrumentation"
},
"readLink":"images\/search?q=tropical ocean",
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=tropical ocean&FORM=OIIARP",
"totalEstimatedMatches":842,
"nextOffset":47,
"value":[
    {
        "webSearchUrl":"https:\/\/www.bing.com\/images\/search?view=detailv2&FORM=OIIRPO&q=tropical+ocean&id=8607ACDACB243BDEA7E1EF78127DA931E680E3A5&simid=608027248313960152",
        "name":"My Life in the Ocean | The greatest WordPress.com site in ...",
        "thumbnailUrl":"https:\/\/tse3.mm.bing.net\/th?id=OIP.fmwSKKmKpmZtJiBDps1kLAHaEo&pid=Api",
        "datePublished":"2017-11-03T08:51:00.0000000Z",
        "contentUrl":"https:\/\/mylifeintheocean.files.wordpress.com\/2012\/11\/tropical-ocean-wallpaper-1920x12003.jpg",
        "hostPageUrl":"https:\/\/mylifeintheocean.wordpress.com\/",
        "contentSize":"897388 B",
        "encodingFormat":"jpeg",
        "hostPageDisplayUrl":"https:\/\/mylifeintheocean.wordpress.com",
        "width":1920,
        "height":1200,
        "thumbnail":{
        "width":474,
        "height":296
        },
        "imageInsightsToken":"ccid_fmwSKKmK*mid_8607ACDACB243BDEA7E1EF78127DA931E680E3A5*simid_608027248313960152*thid_OIP.fmwSKKmKpmZtJiBDps1kLAHaEo",
        "insightsMetadata":{
        "recipeSourcesCount":0,
        "bestRepresentativeQuery":{
            "text":"Tropical Beaches Desktop Wallpaper",
            "displayText":"Tropical Beaches Desktop Wallpaper",
            "webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=Tropical+Beaches+Desktop+Wallpaper&id=8607ACDACB243BDEA7E1EF78127DA931E680E3A5&FORM=IDBQDM"
        },
        "pagesIncludingCount":115,
        "availableSizesCount":44
        },
        "imageId":"8607ACDACB243BDEA7E1EF78127DA931E680E3A5",
        "accentColor":"0050B2"
    }]
}

次のステップ