Detecting Faces With The Azure Face API Utilizing Python

On this article, I’ll present you how one can construct an software in Python that may detect and examine faces utilizing the Microsoft Azure Face API. The Microsoft Face API is part of the bigger Azure Cognitive Service hosted on Microsoft Azure. Consequently, you’ll need to have an Azure account if you need to attempt the code offered.


The answer makes use of Python programming language to make a name to the Azure Face API. The decision in itself is reasonably easy; you simply must ship an HTTP request to the service. Within the code, the service I exploit is hosted within the SouthWest area, so the URI to my Face API service is – ensure that to make use of the precise service API URI.

One other vital element concerning the strategy of this demo is that the code depends on an preliminary image taken with the digicam, and saved to disk in a selected location. This was executed to simplify the code. Consequently, you’ll need to first take an image of the face you need to acknowledge earlier than working the code. In case you run the code on a Raspbian working system, use this command to take an image.

raspistill -v -o check.jpg

The baseline image will likely be saved in a file referred to as check.jpg. By default the code expects this file to be situated within the /dwelling/pi/ subdirectory; merely change the base_face_file variable in case you are storing the file elsewhere.

Final, however not least, ensure that the baseline image you’re taking has correct lighting and is right-side up. Most picture recognition failures are as a consequence of improper alignment of the digicam or poor lighting situations.


Let’s do that. The primary methodology of the code is named capturePicture(). The aim of this methodology is straightforward: take an image via the digicam and save to disk.

The subsequent methodology, getFaceId() calls the Azure Face API to retrieve a novel identifier for the final image taken. This can be a crucial preliminary step; the Azure Face API retains a listing of current photos and indexes them for as much as 24 hours. If no face is detected, the tactic returns an empty string. To make the HTTP name, two headers are required,

Ocp-Apim-Subscription-Key and Content material-Kind. The primary one is your Cognitive Service API key, and the second needs to be “software/octet-stream”. The physique of the request is just the content material of the picture as binary.

The third methodology, compareFaces(), sends two FaceId values to the identical Face API service and returns whether or not or not they’re an identical. As this system begins, it mechanically requests the FaceId of the image initially taken, saved within the check.jpg file. The opposite FaceId is the one from the final image taken. The HTTP headers are related for this name, besides that the Content material-Kind header needs to be set to “software/json”. The decision returns a JSON payload; the Python code merely reads the worth of the isIdentical property.

Final however not least, the principle routine merely retrieves the FaceId for the baseline image, after which enters an infinite loop, working the code image that compares faces each 2 seconds. Any errors will likely be printed out. It’s best to be aware that since a FaceId is just legitimate for twenty-four hours, this code will fail after 24 hours; that’s as a result of the baseline FaceId will turn into invalid. A minor enhancement to this code could possibly be made to acquire a brand new FaceId for the baseline day by day.

import http.shopper, json
from picamera import PiCamera
from time import sleep
import sys 
# Cognitive settings 
subscription_key = 'ENTER_THE_AZURE_COGNITIVE_KEY'
analyze_uri = "/imaginative and prescient/v1.0/analyze?%s"
face_detect_uri = "/face/v1.0/detect?returnFaceId=true"
face_verify_uri = "/face/v1.0/confirm"
base_face_id = ""
base_face_file="/dwelling/pi/check.jpg"  # this file was created from the digicam check
# different settings 
fileName = "/dwelling/pi/enzo/picture.jpg"  # this file is created each few seconds 
headers = dict() 
headers['Ocp-Apim-Subscription-Key'] = subscription_key 
headers['Content-Type'] = "software/octet-stream"
headers_appjson = dict() 
headers_appjson['Ocp-Apim-Subscription-Key'] = subscription_key 
headers_appjson['Content-Type'] = "software/json"
lastValue = False   
digicam = PiCamera()   
def capturePicture(fipathToFileInDiskle):   
def getFaceId(pathToFileInDisk, headers):   
    with open( pathToFileInDisk, "rb" ) as f:   
        inputdata = f.learn()   
    physique = inputdata   
    faceId = ""   
        conn = http.shopper.HTTPSConnection(uri_base)   
        conn.request("POST", face_detect_uri, physique, headers)   
        response = conn.getresponse()   
        knowledge = response.learn().decode('utf-8')                  
        parsed = json.masses(knowledge)   
        if (len(parsed) > 0):   
            print (parsed)   
            faceId = parsed[0]['faceId']   
    besides Exception as e:   
    return faceId   
def compareFaces(faceId1, faceId2):   
    an identical = False   
        physique = '{ "faceId1": "' + faceId1 + '", "faceId2": "' + faceId2 + '" }'   
        conn = http.shopper.HTTPSConnection(uri_base)   
        conn.request("POST", face_verify_uri, physique, headers_appjson)   
        response = conn.getresponse()   
        knowledge = response.learn().decode('utf-8')   
        parsed = json.masses(knowledge)   
        an identical = parsed['isIdentical']   
    besides Exception as e:   
    return an identical   
# Predominant code begins right here 
# Get the face id of the bottom picture - this faceId is legitimate for twenty-four hours 
faceId1 = getFaceId(base_face_file, headers)   
whereas True:   
        print("calling digicam...")   
        print("calling Azure Cognitive service...")   
        faceId2 = getFaceId(fileName, headers)   
        if (len(faceId2) > 0):   
            isSame = compareFaces(faceId1, faceId2)   
            if isSame:   
                # Similar face detected... ship the message   
                print("SAME FACE DETECTED")   
        print("Error:", sys.exc_info()[0])   

Word. The pattern code offered was constructed and examined on a RaspberryPi; nevertheless, this code ought to run on any platform that has a related digicam. The code is a component of a bigger lab, with full directions, that was created and posted right here.

Know extra about our firm at Skrots. Know extra about our companies at Skrots Companies, Additionally checkout all different blogs at Weblog at Skrots

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button