Breaking News

Detect face using Azure Cognitive Services in Python

Azure Cognitive services are used widely to achieve solutions for different problems. Azure Cognitvie Services provides Machine learnign and deep learning solutions for problems. They are easy to use and provides fast and better results.

Azure Face services

Azure faces services are used to detect face in image. It performs other different operations like facial landmarks detection such as eyes, lips, nose. These features are then used to match different faces in images.

To use this service an API key is required. We can be obtained from this URL. It offers a 7 day trail for free and then an Free Azure account is required to use this service. https://azure.microsoft.com/en-us/try/cognitive-services/?api=face-vision

After obtaining the API key we can write a script to pass an image and get different insights from that image. Here is complete python code for this purpose.
Azure has provided Cognitive Face to easily perform operations related to faces. We will use this to perform different operations. First install cognitive face package from pip using...

pip install cognitive_face

Now we will process an image and draw a box around face using results returned from azure for that image and also crop that image.

import cognitive_face as CF

KEY = 'your_subscription_key'  # Replace with a valid Subscription Key here.
CF.Key.set(KEY)

BASE_URL = 'https://westus.api.cognitive.microsoft.com/face/v1.0/'  # Replace with your regional Base URL
CF.BaseUrl.set(BASE_URL)

img_path = 'images/markzuckerber.jpg'
result = CF.face.detect(img_path)
print(result)

The result will be as follows. It remains on azure for 24hours. You can get this result using this id

[{'faceId': '8f13b551-4819-470a-8797-6eb191e5eba8', 'faceRectangle': {'top': 124, 'left': 459, 'width': 227, 'height': 227}}]

Now to draw a rectangle, we will use opencv. OpenCV is highly used for image processing and performing different operations on images and is highly useful

import cv2
img = cv2.imread(img_path)
faceRect = result[0]["faceRectangle"]
cv2.rectangle(img, (faceRect["left"], faceRect["top"]), (faceRect["left"] + faceRect["width"], faceRect["top"] + faceRect["height"]), (255,255,0), 2)
cv2.imshow("image", img)
cv2.waitKey(0)

No comments