【问题标题】:MS Cognitive Face API: Unable to detect facesMS 认知人脸 API:无法检测人脸
【发布时间】:2018-06-19 19:13:51
【问题描述】:

我是第一次尝试使用 Microsoft Cognitive Face API。文档提供了一种从内存流中检测人脸的非常简单的方法。我正在尝试从位于文件夹内的图像中检测人脸。现在文件夹内只有一张图片。问题是每当控件到达以下行时:

var faces = await faceServiceClient.DetectAsync(memStream, true, true);

它在没有任何异常或错误的情况下终止。这是我写的完整代码。

using Microsoft.ProjectOxford.Face;
using Microsoft.ProjectOxford.Common;
using Microsoft.ProjectOxford.Face.Contract;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace FaceDetection.FaceDetect
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Face Detect";
            Start();
        }
        static async Task Stop()
        {
            await Close();
        }
        private static Task Close()
        {
            return Task.Run(() =>
            {
                Environment.Exit(0);
            });
        }

        static async Task ReStart(string _reason = "")
        {
            Console.WriteLine(_reason + "To restart the process press 'R'. To exit press 'X'");
            var _response = Console.ReadLine();
            if (_response == "r" || _response == "R")
                await Start();
            else
                await Stop();
        }
        static async Task Start()
        {
            Console.Clear();
            Console.WriteLine("Enter Folder Path");
            string imageFolderPath = Console.ReadLine();
            if (!Directory.Exists(imageFolderPath))
            {
                await ReStart("Folder does not exist! ");
            }
            else
            {
                await SaveFiles(imageFolderPath);
            }
        }
        static async Task SaveFiles(string imageFolderPath)
        {
            try
            {
                DirectoryInfo dInfo = new DirectoryInfo(imageFolderPath);
                string[] extensions = new[] { ".jpg", ".jpeg" };
                FileInfo[] files = dInfo.GetFiles()
                .Where(f => extensions.Contains(f.Extension.ToLower()))
                .ToArray();
                if (files.Length == 0)
                    await ReStart("No files found in the specified folder! ");
                else
                {
                    string subscriptionKey = "ADSFASDFASDFASDFASDFASDFASDF";
                    if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["subscriptionKey"]))
                        subscriptionKey = ConfigurationManager.AppSettings["subscriptionKey"].ToString();

                    //var stringFaceAttributeType = new List<FaceAttributeType> { FaceAttributeType.Smile, FaceAttributeType.Glasses, FaceAttributeType.Gender, FaceAttributeType.Age };
                    //IEnumerable<FaceAttributeType> returnFaceAttributes = stringFaceAttributeType;

                    IFaceServiceClient faceServiceClient = new FaceServiceClient(subscriptionKey);
                    foreach (FileInfo file in files)
                    {
                        try
                        {
                            using (FileStream fileStream = File.OpenRead(imageFolderPath + "\\" + file.Name))
                            {
                                MemoryStream memStream = new MemoryStream();
                                memStream.SetLength(fileStream.Length);
                                fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);

                                //Used following commented code to make sure MemoryStream is not corrupted.
                                //FileStream _file = new FileStream(imageFolderPath + "\\test.jpg", FileMode.Create, FileAccess.Write);
                                //memStream.WriteTo(_file);
                                //_file.Close();
                                //memStream.Close();

                                try
                                {
                                    //This line never returns a result. The execution terminates without any exception/error.
                                    var faces = await faceServiceClient.DetectAsync(memStream, true, true);

                                    if (faces != null)
                                    {
                                        foreach (var face in faces)
                                        {
                                            var rect = face.FaceRectangle;
                                            var landmarks = face.FaceLandmarks;
                                        }
                                    }
                                    else
                                        Console.WriteLine("No face found in image: " + file.FullName);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("Error");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("There was an error!");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("There was an error!");
            }
            await ReStart();
        }
    }
}

谁能指出我错过了什么。为什么这段代码不起作用?

【问题讨论】:

    标签: c# face-detection memorystream microsoft-cognitive


    【解决方案1】:

    当您将文件读入 MemoryStream 时,您的读取指针会提前到末尾。所以传递给DetectAsync()memStream 显示为空。事实上,您不需要将文件复制到内存中。打开后直接传入FileStream即可。

    using (FileStream fileStream = File.OpenRead(imageFolderPath + "\\" + file.Name))
    {
       try
       {
          var faces = await faceServiceClient.DetectAsync(fileStream, true, true);
    
          if (faces != null)
          {
             foreach (var face in faces)
             {
                var rect = face.FaceRectangle;
                var landmarks = face.FaceLandmarks;
             }
          }
          else
          {
             Console.WriteLine("No face found in image: " + file.FullName);
          }
       catch (Exception ex)
       {
          Console.WriteLine("Error");
       }
    }
    

    或者,您可以通过在调用 DetectAsync 之前设置 memStream.Position = 0 来回退内存流。

    【讨论】:

      猜你喜欢
      • 2018-12-31
      • 1970-01-01
      • 2016-11-05
      • 2017-12-29
      • 2019-11-18
      • 1970-01-01
      • 2013-09-24
      • 2020-10-24
      • 2013-07-03
      相关资源
      最近更新 更多