Last active
August 17, 2023 23:06
-
-
Save chenxizhang/a8e9434f57e82306e69aa89fbbb2b4af to your computer and use it in GitHub Desktop.
This is a python app to predict animal and healthy status with azure custom vision service
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
import requests | |
from dotenv import load_dotenv | |
import os | |
def classify_image(image: str, local: bool = False): | |
load_dotenv() | |
if local: | |
endpoint = "https://japaneast.api.cognitive.microsoft.com/customvision/v3.0/Prediction/44bd0c2b-20c3-43d9-9805-2f5de1476c3b/classify/iterations/Iteration2/image" | |
headers = { | |
"Prediction-Key": os.getenv("PredictionKey"), | |
"Content-Type": "application/octet-stream", | |
} | |
# read the image file and send it in the request body | |
with open(image, "rb") as f: | |
image_data = f.read() | |
response = requests.post(endpoint, headers=headers, data=image_data) | |
return response.json() | |
else: | |
endpoint = "https://japaneast.api.cognitive.microsoft.com/customvision/v3.0/Prediction/44bd0c2b-20c3-43d9-9805-2f5de1476c3b/classify/iterations/Iteration2/url" | |
headers = { | |
"Prediction-Key": os.getenv("PredictionKey"), | |
"Content-Type": "application/json", | |
} | |
body = {"Url": image} | |
response = requests.post(endpoint, headers=headers, json=body) | |
return response.json() | |
if __name__ == "__main__": | |
# predict tags for an image URL | |
# url = "https://cf.ltkcdn.net/dogs/images/std/204812-800x410-Sick-dog.jpg" | |
# result = classify_image(url) | |
# predict tags for a local image | |
image = "test.jpg" | |
result = classify_image(image, local=True) | |
# display the results on the console with top 2 tags | |
print( | |
[f"{x['tagName']}: {x['probability']:.2%}" for x in result["predictions"][:2]] | |
) |
Please also install below dependencies by pip.
pip install requests python-dotenv
The app was tested in python 3.10.9 64bit.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To run the app, you need to create a .env file in the same folder, and the content should like below.
PredictionKey=yourkey