DEV Community

Muhammad Habib Jawady
Muhammad Habib Jawady

Posted on

Multiple face recognition & data exploitation with Py and Azure FaceAPI

Howdy Azure users again,

Today I will be showing you how to exploit the powerful Azure FaceAPI n order to extract data about people in images.I assume that you already read the previous article as there are some fundamentals you need to know about Azure in order to follow along .

https://s3curi7y.tn/2017/12/02/azure-face-api-hands-using-python-basic-version/

Also, you can find the code I’m about to explain in my repository .

What does this code do exactly?

Actually, this is a Python code which allows the detection and identification of human faces using Azure’s API .It is composed of two main functions paraMade and recogn each requiring a key and a URL .

How does it work?

The code is composed of two functions, both get their arguments from the sys.argv array .

  • paraMade: 

This function is responsible for sending a request with the URL of the image and receiving details about detected faces in JSON format (JS Object Notation)

def paraMade(key, url): # defining the function

subscription_key = key # getting API token

uri_base = ‘https://eastus.api.cognitive.microsoft.com’ # setting endpoint URL

headers = {

‘Content-Type’: ‘application/json’,

‘Ocp-Apim-Subscription-Key’: subscription_key,

} # setting the headers of the request

params = {

‘returnFaceId’: ‘true’,

‘returnFaceLandmarks’: ‘false’,

‘returnFaceAttributes’: ‘age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise’,

} # setting the parameters of the request

body = {‘url’: url} #assigning the url of the image from the func argument

try:

response = requests.request(‘POST’, uri_base + ‘/face/v1.0/detect’, json=body, data=None, headers=headers, params=params) # sending POST request to the endpoint and collecting response

parsed = json.loads(response.text) # parsing the response

print(“\tIn this picture : %s\nWe found that:\n” % url)

print (json.dumps(parsed, sort_keys=True, indent=2)) # printing the list of detected faces

print(“\tThere are %i people” % parsed.len())# counting number of detected faces

for person in parsed: # looping through the list of faces

print(“\t> Person %i:\n\tThis is a %i-year old %s” %(parsed.index(person)+1, person[“faceAttributes”][“age”],person[“faceAttributes”][“gender”]))                              #

if int(person[“faceAttributes”][“hair”][“bald”]) == 0:                    # PARSING JSON OBJECTS

if is_male(person[“faceAttributes”][“gender”]):                          #

print(“\tHis face, has the id %s” % (person[‘faceId’]))                # and using data to make a paragraph

else:

print(“\tHer face, has the id %s”% (person[‘faceId’]))                 #

except Exception as e:

print(‘Error:’)

print(e)

  • recogn:

def recogn(KEY, img_url):                                   # defining the function

CF.Key.set(KEY)                                                 # setting the API key

BASE_URL = ‘https://eastus.api.cognitive.microsoft.com/face/v1.0/’   # endpoint URL

CF.BaseUrl.set(BASE_URL)                               # setting the endpoint URL

detected = CF.face.detect(img_url)

print(detected)                                                     # printing the list of detected faces

def getRectangle(faceDictionary):                       # defining rectangle coordinates-related function

rect = faceDictionary[‘faceRectangle’]

left = rect[‘left’]

top = rect[‘top’]

bottom = left + rect[‘height’]

right = top + rect[‘width’]

return ((left, top), (bottom, right))                          # returning coordinates

response = requests.get(img_url)                        # downloading image

img = Image.open(BytesIO(response.content))   # opening image using BytesIO

draw = ImageDraw.Draw(img)                             # setting the image for drawing using ImageDraw from Pillow

for face in detected:                                             # looping in list of detected faces

draw.rectangle(getRectangle(face), outline=’blue’) # drawing rectangles

img.show()                                                            # outputting results

USGAE?

Command : python FaceAPI.py {key} {Image URL}

Top comments (0)