Last active
September 30, 2019 17:09
-
-
Save aymericdelab/55060bbbb21d333c0a01b8699db14e97 to your computer and use it in GitHub Desktop.
Download Bing Images using the Image Search API from Azure Cognitive Services
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"from azure.cognitiveservices.search.imagesearch import ImageSearchAPI\n", | |
"from msrest.authentication import CognitiveServicesCredentials\n", | |
"from PIL import Image\n", | |
"import requests\n", | |
"from io import BytesIO\n", | |
"import os\n", | |
"\n", | |
"# create an Azure account \n", | |
"# and get your API key from here: \n", | |
"# https://azure.microsoft.com/en-us/services/cognitive-services/bing-image-search-api/\n", | |
"KEY1='XXXXXXXXXXXXXXXXXXXXXXXXX'\n", | |
"subscription_key = KEY1\n", | |
"founders = [\"Jeff Bezos\",\"Bill Gates\",\"Larry Page\"]\n", | |
"offsets=[0,150,300,450]\n", | |
"\n", | |
"client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))\n", | |
"\n", | |
"for founder in founders:\n", | |
" prefix=r'.\\data\\bing\\{}'.format(founder)\n", | |
" os.makedirs(prefix)\n", | |
" count=0\n", | |
" \n", | |
" for offset in offsets:\n", | |
" image_results = client.images.search(\n", | |
" query=founder,\n", | |
" count=150,\n", | |
" offset=offset,\n", | |
" image_content='Face',\n", | |
" image_type='Photo')\n", | |
" for result in image_results.value:\n", | |
" url=result.content_url\n", | |
" try:\n", | |
" response = requests.get(url)\n", | |
" img = Image.open(BytesIO(response.content))\n", | |
" path=prefix+'\\{}.{}.jpg'.format(count,founder)\n", | |
" img.save(path)\n", | |
" count+=1\n", | |
" except:\n", | |
" print('Connection error or wrong format')" | |
] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "sagemaker", | |
"language": "python", | |
"name": "sagemaker" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.6.9" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment