Search code examples
pythonpython-3.xazure-cognitive-servicesface-api

Compare faces using Microsoft's FaceApi in python


I'm new to python programming and was just wondering if we could use the Microsoft FaceApi in Python(3.6) to compare two faces, using their faceIds or facelandmarks? If yes, please give an example of how to use it. Thank you very much.


Solution

  • If you want to know if two images are of the same person, you can call detect for each and then call verify. You could use the cognitive_face package like this:

    import cognitive_face as CF
    
    key = 'YOUR_KEY_HERE'  # 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_urls = [
        'https://images-na.ssl-images-amazon.com/images/M/MV5BMTczNzE3Njk4MV5BMl5BanBnXkFtZTcwOTU1ODk5NQ@@._V1_UY317_CR7,0,214,317_AL_.jpg',
        'https://images-na.ssl-images-amazon.com/images/M/MV5BMzIwMDgzMTE5M15BMl5BanBnXkFtZTcwNTg4OTgwOA@@._V1_UY317_CR15,0,214,317_AL_.jpg' ]
    
    faces = [CF.face.detect(img_url) for img_url in img_urls]
    
    # Assume that each URL has at least one face, and that you're comparing the first face in each URL
    # If not, adjust the indices accordingly.
    similarity = CF.face.verify(faces[0][0]['faceId'], faces[1][0]['faceId'])
    print similarity