C# Azure Face API 与本地图像。错误请求异常

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

昨天我编辑了以下代码:Microsoft Azure Face API Quickstart 我可以识别本地图像中的人。

当我用多个图像训练一个组时,我得到了一个错误的请求例外,我在检查图像之前收到了一个错误的请求

 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);
            }
        }

这是训练 Bad Exeption 的第一个代码示例,此代码有效,但当我处理多个图像时,它不起作用。

            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)
            {

            }

这是我在这一行中得到异常的第二个代码示例:

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

有人知道解决方案吗? 您可以在 github

上找到孔代码

[更新]

我用多个图像修复了第一个异常。图片太大了。

Exeption

我找到了所有问题的解决方案。我可以使用 verify 而不是 identify 它的代码多一点但更容易

public static async Task Verify(IFaceClient client, string recognitonModel)
    {
        Console.WriteLine("====VERIFY====\n");

        List<string> targetImageFileNames = new List<string> { "jonasTrain5.jpg" };
        string sourceImageFileName1 = "identification1.jpg";

        List<Guid> targetFaceIds = new List<Guid>();
        foreach (var imageFileName in targetImageFileNames)
        {
            List<DetectedFace> detectedFaces = await DetectFaceRecognize(client, trainingPath + imageFileName, recognitonModel);
            targetFaceIds.Add(detectedFaces[0].FaceId.Value);
        }

        List<DetectedFace> detectedFaces1 = await DetectFaceRecognize(client, testingPath + sourceImageFileName1, recognitonModel);
        Guid sourceFaceId1 = detectedFaces1[0].FaceId.Value;
        foreach (var detectedFace in detectedFaces1)
        {
            VerifyResult verifyResult1 = await client.Face.VerifyFaceToFaceAsync((Guid)detectedFace.FaceId, targetFaceIds[0]);
            Console.WriteLine(
                verifyResult1.IsIdentical
                    ? $"Faces from {sourceImageFileName1} & {targetImageFileNames[0]} are of the same (Positive) person, similarity confidence: {verifyResult1.Confidence}."
                    : $"Faces from {sourceImageFileName1} & {targetImageFileNames[0]} are of different (Negative) persons, similarity confidence: {verifyResult1.Confidence}.");
        }

我无法重现原始问题,但重要的是要认识到 API return 响应正文中包含丰富的信息。下面的 try-catch 块演示了如何解析异常:

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);
}

当我 运行 使用无效参数时,它会捕获以下消息:

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

您提到您确定问题是文件大小,嵌入的错误消息会包含此信息。

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.

使用 MS 库存图像后,我收到了一个 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

对于可能出现的问题,请确保您的图像符合此处列出的操作要求:https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236

人脸 - 识别

一对多识别,从一个人组或一个大的人组中找到与特定查询人脸最接近的匹配。

对于faceIds数组中的每张人脸,Face Identify会计算查询人脸与人组(由personGroupId给定)或大人物组(由largePersonGroupId给定)中的所有人脸之间的相似度,并且return 那张脸的候选人物 运行 由相似性置信度决定。 person group/large person group 应该被训练以使其为识别做好准备。在 PersonGroup - Train 和 LargePersonGroup - Train 中查看更多信息。

备注:

  • 该算法允许在同一请求下独立识别一张以上的人脸,但不超过 10 张。
  • 人group/large人组中的每个人可以有一张以上的脸,但不能超过248张脸。
  • 人脸画质越高,识别精度越高。请考虑高质量的人脸:正面,清晰,面部大小为 200x200 像素(双眼之间 100 像素)或更大。
  • 考生人数 returned 受 maxNumOfCandidatesReturned 和 confidenceThreshold 的限制。如果没有人被识别,returned 候选人将是一个空数组。
  • 尝试面孔 - 当您需要从面孔 list/large 面孔列表而不是人 group/large 人员组中查找相似面孔时,请尝试查找相似面孔。
  • 查询人脸faceIds关联的'recognitionModel'应与目标人群或大人群使用的'recognitionModel'相同
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.