How to use the Prediction API

If you have an image URL:

https://southcentralus.api.cognitive.microsoft.com/customvision/v1.0/Prediction/3cb86d65-c6ce-4d5e-a19c-058401e20252/url

  • Set Prediction-Key Header to : 587a2aff4b81410190bfa872ea17c34f
  • Set Content-Type Header to : application/json
  • Set Body to : {"Url": "< image url >"}

If you have an image file:

https://southcentralus.api.cognitive.microsoft.com/customvision/v1.0/Prediction/3cb86d65-c6ce-4d5e-a19c-058401e20252/image

  • Set Prediction-Key Header to : 587a2aff4b81410190bfa872ea17c34f
  • Set Content-Type Header to : application/octet-stream
  • Set Body to : < image file >

Importing required libraries and specify our custom vision service url and prediction key


In [67]:
import requests
import json

service_url = "https://southcentralus.api.cognitive.microsoft.com/customvision/v1.0/Prediction/3cb86d65-c6ce-4d5e-a19c-058401e20252/image"
prediction_key = "587a2aff4b81410190bfa872ea17c34f"

Here, we're specifying which image to use for prediction; open the local image file; posting to our custom vision service; and finally process the response as a JSON object. Finally, we use the Python "max" function to find the dictionary record with the highest probability


In [75]:
path_to_image = "/tmp/VuLeAMLExperimentation/VuLeAMLExpWorkspace/aml-deep-learning-mnist/mnist_png/testing/8/226.png"

image_file = open(path_to_image, 'rb').read()
response = requests.post(url=service_url,
                         headers={'Prediction-Key': prediction_key,
                                  'Content-Type': 'application/octet-stream'
                                 },
                         data=image_file)
predictions = json.loads(response.text)["Predictions"]

best_prediction = max(predictions, key=lambda p: p['Probability'])
print('I think this digit is a {0} with {1:.2%} confidence.'.format(best_prediction['Tag'], best_prediction['Probability']))


I think this digit is a 8 with 98.49% confidence.

In [ ]: