LoginSignup
1
1

More than 5 years have passed since last update.

AzureのBing Searchで画像検索

Posted at

Bing Search APIで画像取得

既に書かれている方も多いかと思いますが、Bing Search APIで
画像を取得してみました。
経緯としては人工知能で学習させるために必要な画像の準備のためです。
調べてみるとバージョンがいろいろあり、今はv5があり、v7がpreviewらしいです。
ということでv5でやってみます。こちらを参考にさせてもらいました。

事前準備

まずは事前準備として、Azureの契約が済んでいることとする。
Azure Portalにアクセスし、左側のメニューから「Cognitive Services」から追加で「Bing Search API」を選択します。
適当に名前を入れて作成が完了するとキーを確認します。
* Keys
xxxxxxxxx

テストデータの接続

まずは接続できるか試してみる。

curl -H 'Ocp-Apim-Subscription-Key:{key}'  https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cat | jq .

上記コマンドでズラズラっとデータが取得できればOKです。

実際のプログラムでの取得

次に実際のプログラムで取得してみます。
言語はわかりやすいpythonでやってみます。
いろいろ突っ込みどころは満載ですが・・・requestsが使いやすいのでそれを使っています。

get_img_from_bing.py
import os
import sys

import json
import re
import requests
import urllib
import shutil

HOST='api.cognitive.microsoft.com'
REST_PATH='/bing/v5.0/images/search'
SAVE_PATH='/photos'
SUBSCRITION_KEY='xxxxx;


def makedir(dstpath):
    if not os.path.isdir(dstpath):
        try:
            os.makedirs(dstpath)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise  # raises the error again

def get_image(index,url,word):
    print(url)
    dstpath=SAVE_PATH+"/"+word+"/"
    makedir(dstpath)
    headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0'}

    try:
        r=requests.get(url, headers=headers,stream=True)
        if r.status_code== 200:
            kaku=r.headers['content-type'].split('/')[1]
            filepath=dstpath+str(index)+'.'+kaku
            with open(filepath,'wb') as f:
                r.raw.decode_content =True
                shutil.copyfileobj(r.raw,f)    
    except :
        pass

def main(argv):
    word='cat'
    #print(word)
    offset=0
    count=150
    headers = {'Ocp-Apim-Subscription-Key':SUBSCRITION_KEY}

    params = {
    'q': word,
    'mkt': 'ja-JP',
    'count': count,
    'offset': offset,
}
    url='https://'+HOST+'/' + REST_PATH +'?q='+word
    data=requests.get(url, headers=headers,params=params).json()
    #print(data['value']['contentUrl'])
    for i,v in enumerate(data['value']):
        url=v['contentUrl']
        #print(i['contentUrl'])
        pattern = r"&r=(http.+)&p="
        img_url = re.search(pattern, url)
        iurl= urllib.parse.unquote(img_url.group(1))
        get_image(offset+i,iurl,word)
    print('end')

if __name__ == '__main__':
    main(sys.argv)

これを実行して猫の画像がphotosの配下に出てくればOKです。
たまにサイトによってはUAがrequestのデフォルトだと弾くところもあるので設定をしています。

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