Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Import the Face API SDK
- import cognitive_face as Face_API
- import requests
- from io import BytesIO
- from PIL import Image, ImageDraw, ImageFont
- # Set the key which are you generated in the Azure service in the previous steps
- Face_API.Key.set("INSERT_YOUR_KEY_HERE")
- # Set the service url which defined in the Azure service.
- # Because we created the service in the "West Central US" region the link
- # will be the next "https://westcentralus.api.cognitive.microsoft.com/face/v1.0"
- # Your correct url you can find in the section two http://joxi.ru/ZrJNPlkSwngkJr.png
- Face_API.BaseUrl.set("https://westcentralus.api.cognitive.microsoft.com/face/v1.0")
- # Sending the image to the Face API.
- # The image can be the URL, file path or a file-like object represents an image.
- # The attributes must be the comma-separated string like "age,emotion".
- # Supported face attributes include age, gender, headPose, smile, facialHair,
- # glasses, emotion, makeup, accessories, occlusion, blur, exposure, noise.
- img_url = "http://joxi.ru/BA0MXPGSMpzY1r.png"
- response = Face_API.face.detect(image=img_url, attributes="emotion")
- # Printing the response.
- print(response)
- # Get the best mutch emotion and convert
- # to the string like "emotion_name: score".
- def get_best_emotion(resp):
- emotions = resp["faceAttributes"]["emotion"]
- b_key, b_value = "", 0
- for key, value in emotions.items():
- if value > b_value:
- b_key, b_value = key, value
- return b_key + ": " + str(b_value)
- # Get the face area from the response "faceRectangle".
- def get_face_box(resp):
- values = resp["faceRectangle"]
- left = values["left"]
- top = values["top"]
- bottom = left + values["height"]
- right = top + values["width"]
- return ((left, top), (bottom, right))
- # Download the image by the url
- image_data = requests.get(img_url)
- # Opens and identifies the given image file.
- image = Image.open(BytesIO(image_data.content))
- # Creates an object that can be used to draw in the given image.
- draw = ImageDraw.Draw(image)
- # Load a TrueType or OpenType font from a file or file-like object,
- # and create a font object.
- fnt = ImageFont.truetype("Ubuntu-B.ttf", size=13)
- # Iterate through all responses and draw box and text.
- for resp in response:
- # Get the best emotion.
- emotion = get_best_emotion(resp)
- # Get the face box.
- face_box = get_face_box(resp)
- # Draw the text on the image.
- draw.text((face_box[0][0], face_box[0][1] - 12), emotion, fill="purple", font=fnt)
- # Draw box on the image
- draw.rectangle(face_box, outline="purple")
- # Now you can display the final image.
- image.show()
- # Or save it.
- image.save("output.png", "PNG")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement