Search code examples
c#azureazure-cognitive-servicesface-api

C# Azure Face API with local images. Bad Request exeption


Yesterday I edited the code from: Microsoft Azure Face API Quickstart that I can recognize people in local images.

I got a Bad Request exeption when I did train a group with multiple image and I got an Bad Request before checking the image

 Dictionary<string, string[]> personDictionary = new Dictionary<string, string[]>
         {
             { "Jonas", new[] {"jonasTrain2.jpg"}},
             {"Thomas", new [] {"thomasTrain1.jpg"}}
         };
        string sourceImageFilePath = @"C:\Users\jonas\Desktop\FAces\Test\jonasTest1.jpg";

        Console.WriteLine($"Create a person group ({personGroupId}).");
        await client.PersonGroup.CreateAsync(personGroupId, personGroupId, recognitionModel: recognitionModel);

        foreach (var groupedFace in personDictionary.Keys)
        {
            await Task.Delay(250);
            Person person = await client.PersonGroupPerson.CreateAsync(personGroupId: personGroupId, name: groupedFace);
            Console.WriteLine($"Create a person group person '{groupedFace}'");

            foreach (var similarImage in personDictionary[groupedFace])
            {
                Console.WriteLine($"Add face to the person group person ({groupedFace}) from image `{similarImage}`");
                FileStream fs = File.OpenRead(TRAIN_PATH + @"\" + similarImage);
                PersistedFace face = await client.PersonGroupPerson.AddFaceFromStreamAsync(personGroupId, person.PersonId,
                    fs, similarImage);
            }
        }

This is the first code sample with the training Bad Exeption this code works but when I do multiple images the it don't works.

            Console.WriteLine();
        List<Guid> sourceFaceIds = new List<Guid>();

        List<DetectedFace> detectedFaces = await DetectFaceRecognize(client, sourceImageFilePath, recognitionModel);

        foreach (var detectedFace in detectedFaces) sourceFaceIds.Add(detectedFace.FaceId.Value);

        var idntifyResuluts = await client.Face.IdentifyAsync(sourceFaceIds, personGroupId);

        foreach (var identifyResult in idntifyResuluts)
        {
            try
            {
                Person person = await client.PersonGroupPerson.GetAsync(personGroupId, identifyResult.Candidates[0].PersonId);
                Console.WriteLine($"Person '{person.Name}' is identified for face in: {Path.GetFileName(sourceImageFilePath)} - {identifyResult.FaceId}," +
                    $" confidence: {identifyResult.Candidates[0].Confidence}");
            }
            catch (Exception)
            {

            }

This is the second code sample I get the exeption in this line:

var idntifyResuluts = await client.Face.IdentifyAsync(sourceFaceIds, personGroupId);

Do someone know a solution? You can find the hole code on github

[Update]

I fixed the the first exeption with the muliple image. The image was to big.

The Exeption


Solution

  • I wasn't able to replicate the original issue, but it's important to recognise that the API returns rich information embedded within the body of the response. The following try-catch block demonstrates how to parse the exception:

    try
    {
        await DetectFaceRecognize(client, Path.Join(TRAIN_PATH, "jack.jpg"), RECOGNITION_MODEL4);
        await IdentifyPersonGroup(client, RECOGNITION_MODEL4);
    }
    catch(Microsoft.Azure.CognitiveServices.Vision.Face.Models.APIErrorException appX)
    {
        Console.WriteLine(appX.Message);
        Console.WriteLine(appX.Body.Error.Code);
        Console.WriteLine(appX.Body.Error.Message);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
    

    When I ran this with invalid parameters, it trapped the following message:

    Operation returned an invalid status code 'BadRequest'
    BadArgument
    Only face attributes 'headpose,mask' are supported by detection_03.
    

    You mentioned that you identified the issue was file size, the embedded error message would have included this information.

    After running through the code posted on GitHub, I could not replicate the error conditions with my own local images, which indicates that is probably where it issue lies, the code itself is a simple demonstration of the API usage.

    After using the MS stock images, I received the following output for a family of 4:

    Person 'dad' is identified for face in: family.jpg - 2f4a8d5b-416e-4985-9c94-cd2ae07dce91, confidence: 0.96725
    Person 'mum' is identified for face in: family.jpg - 11ccd00a-a1af-4dfb-a803-359b6bd1df8e, confidence: 0.96921
    Person 'daughter' is identified for face in: family.jpg - 62e6d513-4f8a-4634-a1d1-8dfd68b45c8c, confidence: 0.90712
    Person 'son' is identified for face in: family.jpg - 078abaae-501d-496c-85b9-3a6dc26d1a41, confidence: 0.92886
    

    For possible issues, make sure your images conform to the operation requirements listed here: https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236

    Face - Identify

    1-to-many identification to find the closest matches of the specific query person face from a person group or large person group.

    For each face in the faceIds array, Face Identify will compute similarities between the query face and all the faces in the person group (given by personGroupId) or large person group (given by largePersonGroupId), and return candidate person(s) for that face ranked by similarity confidence. The person group/large person group should be trained to make it ready for identification. See more in PersonGroup - Train and LargePersonGroup - Train.

    Remarks:

    • The algorithm allows more than one face to be identified independently at the same request, but no more than 10 faces.
    • Each person in the person group/large person group could have more than one face, but no more than 248 faces.
    • Higher face image quality means better identification precision. Please consider high-quality faces: frontal, clear, and face size is 200x200 pixels (100 pixels between eyes) or bigger.
    • Number of candidates returned is restricted by maxNumOfCandidatesReturned and confidenceThreshold. If no person is identified, the returned candidates will be an empty array.
    • Try Face - Find Similar when you need to find similar faces from a face list/large face list instead of a person group/large person group.
    • The 'recognitionModel' associated with the query faces' faceIds should be the same as the 'recognitionModel' used by the target person group or large person group
    Error Code Error Message Description
    BadArgument Invalid request body.
    BadArgument The argument maxNumOfCandidatesReturned is not valid. Range is [1,5]
    BadArgument The argument confidenceThreshold is not valid. Range is [0, 1]
    BadArgument Face ID is invalid.
    BadArgument Person group ID is invalid. Valid format should be a string composed by numbers, English letters in lower case, '-', '_', and no longer than 64 characters.
    BadArgument Large person group ID is invalid. Valid format should be a string composed by numbers, English letters in lower case, '-', '_', and no longer than 64 characters.
    BadArgument 'recognitionModel' is incompatible.
    PersonGroupIdAndLargePersonGroupIdBothNotNull Large person group ID and person group ID are both not null.
    PersonGroupIdAndLargePersonGroupIdBothNull Large person group ID and person group ID are both null.
    PersonGroupNotFound Person group is not found.
    LargePersonGroupNotFound Large person group is not found.
    FaceNotFound Face is not found.
    PersonGroupNotTrained Person group not trained.
    LargePersonGroupNotTrained Large person group not trained.
    PersonGroupTrainingNotFinished Person group is under training.
    LargePersonGroupTrainingNotFinished Large person group is under training.