Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MS认知人脸API:无法检测人脸_C#_Face Detection_Memorystream_Microsoft Cognitive - Fatal编程技术网

C# MS认知人脸API:无法检测人脸

C# MS认知人脸API:无法检测人脸,c#,face-detection,memorystream,microsoft-cognitive,C#,Face Detection,Memorystream,Microsoft Cognitive,我第一次尝试使用MicrosoftCognitiveFaceAPI。文档提供了一种从内存流中检测人脸的简单方法。我试图从文件夹中的图像中检测人脸。现在文件夹中只有一个图像。每当控件到达以下行时,就会出现问题: var faces = await faceServiceClient.DetectAsync(memStream, true, true); 它终止时没有任何异常或错误。这是我写的完整代码 using Microsoft.ProjectOxford.Face; using Micros

我第一次尝试使用MicrosoftCognitiveFaceAPI。文档提供了一种从内存流中检测人脸的简单方法。我试图从文件夹中的图像中检测人脸。现在文件夹中只有一个图像。每当控件到达以下行时,就会出现问题:

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();
        }
    }
}
使用Microsoft.ProjectOxford.Face;
使用Microsoft.ProjectOxford.Common;
使用Microsoft.ProjectOxford.Face.Contract;
使用制度;
使用System.Collections.Generic;
使用系统配置;
使用System.IO;
使用System.Linq;
使用System.Threading.Tasks;
命名空间FaceDetection.FaceDetect
{
班级计划
{
静态void Main(字符串[]参数)
{
Console.Title=“面部检测”;
Start();
}
静态异步任务停止()
{
等待关闭();
}
私有静态任务关闭()
{
返回任务。运行(()=>
{
环境。退出(0);
});
}
静态异步任务重启(字符串_reason=”“)
{
Console.WriteLine(_reason+”要重新启动进程,请按“R”。要退出,请按“X”);
var_response=Console.ReadLine();
如果(_-response==“r”| | u-response==“r”)
等待开始();
其他的
等待停止();
}
静态异步任务启动()
{
Console.Clear();
Console.WriteLine(“输入文件夹路径”);
字符串imageFolderPath=Console.ReadLine();
如果(!Directory.Exists(imageFolderPath))
{
等待重新启动(“文件夹不存在!”);
}
其他的
{
等待保存文件(imageFolderPath);
}
}
静态异步任务保存文件(字符串imageFolderPath)
{
尝试
{
DirectoryInfo dInfo=新的DirectoryInfo(imageFolderPath);
string[]extensions=new[]{.jpg',.jpeg};
FileInfo[]files=dInfo.GetFiles()
.Where(f=>extensions.Contains(f.Extension.ToLower()))
.ToArray();
如果(files.Length==0)
等待重新启动(“在指定文件夹中找不到文件!”);
其他的
{
string subscriptionKey=“ADSFASDFASDFASDFASDFASDFASDF”;
如果(!String.IsNullOrEmpty(ConfigurationManager.AppSettings[“subscriptionKey”]))
subscriptionKey=ConfigurationManager.AppSettings[“subscriptionKey”].ToString();
//var stringFaceAttributeType=新列表{FaceAttributeType.Smile,FaceAttributeType.Glass,FaceAttributeType.Gender,FaceAttributeType.Age};
//IEnumerable returnFaceAttributes=stringFaceAttributeType;
IFaceServiceClient faceServiceClient=新的faceServiceClient(subscriptionKey);
foreach(文件中的文件信息文件)
{
尝试
{
使用(FileStream FileStream=File.OpenRead(imageFolderPath+“\\”+File.Name))
{
MemoryStream memStream=新的MemoryStream();
SetLength(fileStream.Length);
读取(memStream.GetBuffer(),0,(int)fileStream.Length);
//使用以下注释代码确保MemoryStream未损坏。
//FileStream\u file=newfilestream(imageFolderPath+“\\test.jpg”,FileMode.Create,FileAccess.Write);
//memStream.WriteTo(_文件);
//_file.Close();
//memStream.Close();
尝试
{
//此行从不返回结果。执行将在没有任何异常/错误的情况下终止。
var faces=wait faceServiceClient.DetectAsync(memStream,true,true);
如果(面!=null)
{
foreach(面中的面变量)
{
var rect=face.FaceRectangle;
var landmarks=face.FaceLandmarks;
}
}
其他的
Console.WriteLine(“图像中未找到面:“+file.FullName”);
}
捕获(例外情况除外)
{
控制台写入线(“错误”);
}
}
}
捕获(例外情况除外)
{
WriteLine(“发生错误!”);
}
}
}
}
捕获(例外情况除外)
{
WriteLine(“发生错误!”);
}
等待重新启动();
}
}
}

有人能指出我遗漏了什么吗。为什么此代码不起作用?

当您将文件读入MemoryStream时,您的读取指针将前进到末尾。因此传递到
DetectAsync()
memStream
显示为空。事实上,您不需要将文件复制到内存中。打开后只需传入
文件流

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");
   }
}
或者,你可以重新布线