Created
November 5, 2019 05:22
-
-
Save jernejk/ffdd20c3b7719ea0017930a43d3a9f41 to your computer and use it in GitHub Desktop.
Example usage of the Microsoft.Azure.CognitiveServices.Vision.Face Nuget package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task Recognize(Stream imageStream) | |
{ | |
var faceClient = new FaceClient(new ApiKeyServiceClientCredentials(FaceSubscriptionKey)) | |
{ | |
Endpoint = "https://westus.api.cognitive.microsoft.com" | |
}; | |
try | |
{ | |
Console.WriteLine(DateTime.Now + ": Attempting to recognize faces..."); | |
var detectedFaces = await faceClient.Face.DetectWithStreamAsync(imageStream, true, true); | |
var faceIds = detectedFaces.Where(f => f.FaceId.HasValue).Select(f => f.FaceId.Value).ToList(); | |
if (faceIds.Any()) | |
{ | |
var potentialUsers = await faceClient.Face.IdentifyAsync(faceIds, FaceGroupId); | |
foreach (var candidate in potentialUsers.Select(u => u.Candidates.FirstOrDefault())) | |
{ | |
var candidateName = await GetCandidateName(candidate?.PersonId); | |
Console.WriteLine("{0}: {1} ({2})", DateTime.Now, candidateName, candidate?.PersonId); | |
} | |
} | |
} | |
catch (APIErrorException apiError) | |
{ | |
Console.WriteLine("Cognitive service error: " + apiError?.Body?.Error?.Message); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine("Getting identity failed: " + e.ToString()); | |
} | |
} | |
private static IList<Person> _cachedIdentities = null; | |
private async static Task<string> GetCandidateName(FaceClient faceClient, Guid? personId) | |
{ | |
if (!personId.HasValue) | |
{ | |
return "No Person ID"; | |
} | |
if (_cachedIdentities == null) | |
{ | |
_cachedIdentities = await faceClient.PersonGroupPerson.ListAsync(FaceGroupId); | |
} | |
return _cachedIdentities | |
?.Where(i => i.PersonId == personId) | |
.Select(i => i.Name) | |
.FirstOrDefault() | |
?? "Candidate not found"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment