|
1 | | -"""Bing Visual Search upload image example""" |
| 1 | +# Download and install Python at https://www.python.org/ |
| 2 | +# Run the following in a command console window: pip3 install requests |
2 | 3 |
|
3 | | -# Download and install Python at https://www.python.org/ |
4 | | -# Run the following in a command console window |
5 | | -# pip3 install requests |
| 4 | +import json |
| 5 | +import os |
| 6 | +from pprint import pprint |
| 7 | +import requests |
6 | 8 |
|
7 | | -import requests, json |
| 9 | +''' |
| 10 | +This sample uses the Bing Visual Search API with a local, query image and returns several web links |
| 11 | +and data of the exact image and/or similar images. |
| 12 | +''' |
8 | 13 |
|
9 | | -# Add your Bing Search V7 endpoint to your environment variables. |
10 | | -BASE_URI = os.environ['BING_SEARCH_V7_ENDPOINT'] + '/bing/v7.0/images/visualsearch' |
| 14 | +# Add your Bing Search V7 subscriptionKey and endpoint to your environment variables. |
| 15 | +endpoint = os.environ['BING_SEARCH_V7_ENDPOINT'] + '/bing/v7.0/images/visualsearch' |
| 16 | +subscription_key = os.environ['BING_SEARCH_V7_SUBSCRIPTION_KEY'] |
11 | 17 |
|
12 | | -# Add your Bing Search V7 subscription key to your environment variables. |
13 | | -SUBSCRIPTION_KEY = os.environ['BING_SEARCH_V7_SUBSCRIPTION_KEY'] |
| 18 | +image_path = 'YOUR-IMAGE.xxx' # for example: my_image.jpg |
14 | 19 |
|
15 | | -imagePath = 'your-image-path' |
| 20 | +headers = {'Ocp-Apim-Subscription-Key': subscription_key} |
16 | 21 |
|
17 | | -HEADERS = {'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY} |
18 | | - |
19 | | -file = {'image' : ('myfile', open(imagePath, 'rb'))} |
20 | | - |
21 | | -def main(): |
| 22 | +file = {'image' : ('YOUR-IMAGE', open(image_path, 'rb'))} # YOUR-IMAGE is the name of the image file (no extention) |
22 | 23 |
|
23 | | - try: |
24 | | - response = requests.post(BASE_URI, headers=HEADERS, files=file) |
25 | | - response.raise_for_status() |
26 | | - print_json(response.json()) |
27 | | - |
28 | | - except Exception as ex: |
29 | | - raise ex |
30 | | - |
31 | | - |
32 | | -def print_json(obj): |
33 | | - """Print the object as json""" |
34 | | - print(json.dumps(obj, sort_keys=True, indent=2, separators=(',', ': '))) |
35 | | - |
36 | | - |
| 24 | +try: |
| 25 | + response = requests.post(endpoint, headers=headers, files=file) |
| 26 | + response.raise_for_status() |
| 27 | + pprint(response.json()) |
| 28 | +except Exception as ex: |
| 29 | + raise ex |
37 | 30 |
|
38 | | -# Main execution |
39 | | -if __name__ == '__main__': |
40 | | - main() |
0 commit comments