LoginSignup
2
1

More than 5 years have passed since last update.

Microsoft Bing Image Search API で 写真をPOSTしてImage Insightsを取得する(Python)

Last updated at Posted at 2017-09-07

MSのAPIページにあるサンプルスクリプトとリファレンス通りにしてImage Insights の Similer Images を画像アップロードで取得しようとしたら、「検索に使うクエリーqがないよ」とか言われて動かなかったので、四苦八苦の末正解にたどり着きました。

upload.py
import requests

headers = {
    'Ocp-Apim-Subscription-Key': '<Your API KEY>',
}
uri = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?modulesRequested=similarimages"

image = open('image.jpg', 'rb')
files = {'param_name': ('filename.jpg', image, 'image/jpeg')}

r = requests.post(uri, data={'dummy':"test"},files=files,
                  headers=headers)

ポイントは、headersに  'Content-Type' : 'multipart/form-data' を 書かない ことです。
files = でファイルを添付すれば、勝手にmultipart/form-dataにしてくれるのですが、headersに指定して上書きすると、boundary指定が消えてしまうのです。
どうやらAPIはこれを見ているらしく。これがないと「検索用のクエリーqがないよ」っていうエラーを返されます。insightsが欲しいのに。

ここに辿り着くまでにC#で書いてみたり、UWPアプリ作ったり、Node-redで受け取って調査したり、ラズパイのセキュリティ設定に悩まされたり、、はああ

追記
C#はこちらのスレッドのコードが動きました、
https://stackoverflow.com/questions/41463093/microsoft-cognitive-api-image-search

2
1
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
2
1