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

await faceClient.Face.DetectWithStreamAsync returning null


I am trying to run Microsoft's 'Create a WPF app to display face data in an image' (https://learn.microsoft.com/en-us/azure/cognitive-services/face/tutorials/faceapiincsharptutorial) but everything I try to use an image to detect faces it will return a Null error (No faces found).

I have downloaded the Windows tutorial project files from github as well as trying a simplified version here: https://carldesouza.com/building-an-azure-cognitive-services-face-app-part-1-face-recognition/, each with the same error. I have managed to create some ASP.Net Web applications that can detect faces as well as creating people groups using the same API key and Endpoint to detect specific people.

The program seems to fail to detect faces at this bit of code:

IList<DetectedFace> faceList =
                        await faceClient.Face.DetectWithStreamAsync(
                            imageFileStream, true, false, null);


[AsyncStateMachine(typeof(<DetectWithStreamAsync>d__6))]
        public static Task<IList<DetectedFace>> DetectWithStreamAsync(this IFaceOperations operations, Stream image, bool? returnFaceId = true, bool? returnFaceLandmarks = false, IList<FaceAttributeType> returnFaceAttributes = null, CancellationToken cancellationToken = default);

The only error that I get from debugging is that this bit of code always return null and therefor does not detect any faces.


Solution

  • Try the code below :

        static void Main(string[] args)
        {
    
    
            string persionPicPath = @"<image path>";
    
            string endpoint = @"https://<your face service name>.cognitiveservices.azure.com/";
            string subscriptionKey = "<your subscription key>";
    
            IFaceClient faceClient = new FaceClient(
            new ApiKeyServiceClientCredentials(subscriptionKey),
            new System.Net.Http.DelegatingHandler[] { });
    
            faceClient.Endpoint = endpoint;
    
            using (Stream s = File.OpenRead(persionPicPath))
            {
                var facesResults = faceClient.Face.DetectWithStreamAsync(s, true, false, null).GetAwaiter().GetResult();
                foreach (var faces in facesResults)
                {
                    Console.WriteLine(faces.FaceId);
                }
                Console.ReadKey();
    
            }
        }
    

    Result : enter image description here

    Hope it helps.