Commit 0d42f339 by 何阳

添加项目文件。

parent 5b36fdec

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34330.188
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FaceApp", "FaceApp\FaceApp.csproj", "{269111C4-EDB6-485D-B47E-C62AE703021C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FaceServer", "FaceServer\FaceServer.csproj", "{1A20E2DE-F5FD-4555-93CE-AC9CEE9E8FA2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{269111C4-EDB6-485D-B47E-C62AE703021C}.Debug|x64.ActiveCfg = Debug|x64
{269111C4-EDB6-485D-B47E-C62AE703021C}.Debug|x64.Build.0 = Debug|x64
{269111C4-EDB6-485D-B47E-C62AE703021C}.Release|x64.ActiveCfg = Release|x64
{269111C4-EDB6-485D-B47E-C62AE703021C}.Release|x64.Build.0 = Release|x64
{1A20E2DE-F5FD-4555-93CE-AC9CEE9E8FA2}.Debug|x64.ActiveCfg = Debug|x64
{1A20E2DE-F5FD-4555-93CE-AC9CEE9E8FA2}.Debug|x64.Build.0 = Debug|x64
{1A20E2DE-F5FD-4555-93CE-AC9CEE9E8FA2}.Release|x64.ActiveCfg = Release|x64
{1A20E2DE-F5FD-4555-93CE-AC9CEE9E8FA2}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {16C61966-A32F-4045-870E-C507FA5249DE}
EndGlobalSection
EndGlobal
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\OpenCvSharp4.runtime.win.4.9.0.20240103\build\net48\OpenCvSharp4.runtime.win.props" Condition="Exists('..\packages\OpenCvSharp4.runtime.win.4.9.0.20240103\build\net48\OpenCvSharp4.runtime.win.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{269111C4-EDB6-485D-B47E-C62AE703021C}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>FaceApp</RootNamespace>
<AssemblyName>FaceApp</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="MessagePack, Version=2.5.0.0, Culture=neutral, PublicKeyToken=b4a0369545f0a1be, processorArchitecture=MSIL">
<HintPath>..\packages\MessagePack.2.5.140\lib\netstandard2.0\MessagePack.dll</HintPath>
</Reference>
<Reference Include="MessagePack.Annotations, Version=2.5.0.0, Culture=neutral, PublicKeyToken=b4a0369545f0a1be, processorArchitecture=MSIL">
<HintPath>..\packages\MessagePack.Annotations.2.5.140\lib\netstandard2.0\MessagePack.Annotations.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.6.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
<Reference Include="Microsoft.NET.StringTools, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.NET.StringTools.17.6.3\lib\net472\Microsoft.NET.StringTools.dll</HintPath>
</Reference>
<Reference Include="OpenCvSharp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6adad1e807fea099, processorArchitecture=MSIL">
<HintPath>..\packages\OpenCvSharp4.4.9.0.20240103\lib\net48\OpenCvSharp.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Collections.Immutable, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Collections.Immutable.6.0.0\lib\net461\System.Collections.Immutable.dll</HintPath>
</Reference>
<Reference Include="System.Core" />
<Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Security" />
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\OpenCvSharp4.runtime.win.4.9.0.20240103\build\net48\OpenCvSharp4.runtime.win.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\OpenCvSharp4.runtime.win.4.9.0.20240103\build\net48\OpenCvSharp4.runtime.win.props'))" />
</Target>
</Project>
\ No newline at end of file
namespace FaceApp
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 24F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
}
}
using MessagePack;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FaceApp
{
public partial class Form1 : Form
{
private VideoCapture videoSource;
private bool isCapturing;
private Stopwatch stopwatch;
private float smoothingFactor = 0.9f; // FPS平滑因子
private double averageFps = 0.0f; // 平均FPS
private int cameraIndex;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thread = new Thread(() =>
{
stopwatch = new Stopwatch();
stopwatch.Start();
isCapturing = true;
videoSource = new VideoCapture(cameraIndex);
if (!videoSource.IsOpened())
throw new Exception("No video devices found or camera index is out of bounds.");
// 设置摄像头参数(可选)
videoSource.Set(VideoCaptureProperties.FrameWidth, 1024);
videoSource.Set(VideoCaptureProperties.FrameHeight, 768);
var pipeServer = new NamedPipeServerStream("FACE", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
pipeServer.WaitForConnection();
while (true)
{
CalculateFPS();
var mat = new Mat();
if (!videoSource.Read(mat)) // 读取每一帧
continue;
// 将 Mat 转换为 JPEG 字节数组
byte[] jpegBytes;
Cv2.ImEncode(".jpg", mat, out jpegBytes);
pipeServer.Write(BitConverter.GetBytes(jpegBytes.Length),0, sizeof(int));
pipeServer.Write(jpegBytes,0, jpegBytes.Length);
if (pipeServer.IsMessageComplete)
{
byte[] head = new byte[4];
pipeServer.Read(head,0, 4);
var len = BitConverter.ToInt32(head,0);
var data = new byte[len];
pipeServer.Read(data, 0, len);
var list = MessagePackSerializer.Deserialize<List<FaceData>>(data);
}
}
});
thread.Start();
}
public double CalculateFPS()
{
var currentFps = 1.0f / (stopwatch.ElapsedMilliseconds / 1000.0f);
averageFps = (averageFps * smoothingFactor) + ((averageFps - currentFps) * (1.0f - smoothingFactor));
stopwatch.Restart();
return averageFps;
}
}
[MessagePackObject]
public struct FaceData
{
[Key(0)]
public Rectangle FaceRect;
[Key(1)]
public string Name;
[Key(2)]
public bool IsIdentified;
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FaceApp
{
internal static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("FaceApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FaceApp")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("269111c4-edb6-485d-b47e-c62ae703021c")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace FaceApp.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FaceApp.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性,对
/// 使用此强类型资源类的所有资源查找执行重写。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FaceApp.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MessagePack" version="2.5.140" targetFramework="net48" />
<package id="MessagePack.Annotations" version="2.5.140" targetFramework="net48" />
<package id="Microsoft.Bcl.AsyncInterfaces" version="6.0.0" targetFramework="net48" />
<package id="Microsoft.NET.StringTools" version="17.6.3" targetFramework="net48" />
<package id="OpenCvSharp4" version="4.9.0.20240103" targetFramework="net48" />
<package id="OpenCvSharp4.runtime.win" version="4.9.0.20240103" targetFramework="net48" />
<package id="System.Buffers" version="4.5.1" targetFramework="net48" />
<package id="System.Collections.Immutable" version="6.0.0" targetFramework="net48" />
<package id="System.Memory" version="4.5.5" targetFramework="net48" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
<package id="System.Reflection.Emit" version="4.7.0" targetFramework="net48" />
<package id="System.Reflection.Emit.Lightweight" version="4.7.0" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="6.0.0" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net48" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net48" />
</packages>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Drawing.Common" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
\ No newline at end of file
using Serilog;
using Serilog.Core;
using Serilog.Enrichers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FaceServer
{
public static class Logging
{
private static ILogger _logger;
public static void Init(TextBox textBox)
{
// 配置 Serilog
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.With(new ThreadIdEnricher()) // 丰富器,包括线程号
.WriteTo.File(
path: "log/log-.log",
rollingInterval: RollingInterval.Day,
fileSizeLimitBytes: 1_000_000,
rollOnFileSizeLimit: true,
outputTemplate: "[{Timestamp:HH:mm:ss.fff}] [{Level}] [{Thread}] [{SourceContext}] {Message:lj}{NewLine}{Code} {Exception}") // 文件日志,每天滚动
.WriteTo.Trace(outputTemplate: "[{Timestamp:HH:mm:ss.fff}] [{Level}] [{Thread}] [{SourceContext}] {Message:lj}{NewLine}{Code} {Exception}")
.WriteTo.Sink(new TextBoxSink(textBox, "[{Timestamp:HH:mm:ss.fff}] [{Level}] [{ThreadId}] [{SourceContext}] {Message:lj}{NewLine}{Exception}")) // 自定义 TextBox Sink
.CreateLogger();
_logger = Log.Logger;
Serilog.Debugging.SelfLog.Enable(Console.Error);
}
}
}
namespace FaceServer
{
partial class Main
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.tbLog = new System.Windows.Forms.TextBox();
this.cbPowerOn = new System.Windows.Forms.CheckBox();
this.tbROI = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// tbLog
//
this.tbLog.Location = new System.Drawing.Point(12, 12);
this.tbLog.Multiline = true;
this.tbLog.Name = "tbLog";
this.tbLog.Size = new System.Drawing.Size(776, 377);
this.tbLog.TabIndex = 0;
//
// cbPowerOn
//
this.cbPowerOn.AutoSize = true;
this.cbPowerOn.Location = new System.Drawing.Point(12, 422);
this.cbPowerOn.Name = "cbPowerOn";
this.cbPowerOn.Size = new System.Drawing.Size(72, 16);
this.cbPowerOn.TabIndex = 1;
this.cbPowerOn.Text = "开机启动";
this.cbPowerOn.UseVisualStyleBackColor = true;
this.cbPowerOn.CheckedChanged += new System.EventHandler(this.cbPowerOn_CheckedChanged);
//
// tbROI
//
this.tbROI.Location = new System.Drawing.Point(65, 395);
this.tbROI.Name = "tbROI";
this.tbROI.Size = new System.Drawing.Size(100, 21);
this.tbROI.TabIndex = 2;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 404);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(47, 12);
this.label1.TabIndex = 3;
this.label1.Text = "ROI大小";
//
// Main
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.label1);
this.Controls.Add(this.tbROI);
this.Controls.Add(this.cbPowerOn);
this.Controls.Add(this.tbLog);
this.Name = "Main";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Main_Load);
this.Shown += new System.EventHandler(this.Main_Shown);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox tbLog;
private System.Windows.Forms.CheckBox cbPowerOn;
private System.Windows.Forms.TextBox tbROI;
private System.Windows.Forms.Label label1;
}
}
using MessagePack;
using Microsoft.Win32;
using Serilog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FaceServer
{
public partial class Main : Form
{
private NotifyIcon trayIcon;
private ContextMenu trayMenu;
private FaceRecognitionServer Server;
private NamedPipeServerStream pipeServer;
public Main()
{
InitializeComponent();
InitializeTrayIcon();
trayIcon.MouseDoubleClick += TrayIcon_MouseDoubleClick;
this.ShowInTaskbar = false;//任务栏中显示标志
}
private void TrayIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
this.ShowInTaskbar = true;//任务栏中显示标志
}
private void InitializeTrayIcon()
{
// 创建右键菜单项
trayMenu = new ContextMenu();
trayMenu.MenuItems.Add("打开", OnTrayIconOpenClicked);
trayMenu.MenuItems.Add("退出", OnTrayIconExitClicked);
// 创建系统托盘图标
trayIcon = new NotifyIcon();
trayIcon.Text = "人脸服务";
trayIcon.Icon = ConvertImageToIcon("App.png"); // 选择合适的图标
// 关联右键菜单
trayIcon.ContextMenu = trayMenu;
// 显示图标
trayIcon.Visible = true;
}
private Icon ConvertImageToIcon(string imagePath)
{
using (Image image = Image.FromFile(imagePath))
{
using (Bitmap bitmap = new Bitmap(image))
{
IntPtr hIcon = bitmap.GetHicon();
using (Icon icon = Icon.FromHandle(hIcon))
{
// 创建一个不会被自动销毁的图标的副本
return Icon.FromHandle(icon.Handle);
}
}
}
}
private void OnTrayIconOpenClicked(object sender, EventArgs e)
{
// 显示窗体
this.Show();
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = true;//任务栏中显示标志
}
private void OnTrayIconExitClicked(object sender, EventArgs e)
{
// 退出应用程序
Application.Exit();
}
protected override void OnLoad(EventArgs e)
{
// 在应用程序启动时隐藏主窗体
base.OnLoad(e);
this.Hide();
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
// 当用户试图关闭窗口时
if (e.CloseReason == CloseReason.UserClosing)
{
var result = MessageBox.Show("您要关闭程序还是隐藏到系统托盘?", "关闭程序", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
// 清理资源
if (trayIcon != null)
{
trayIcon.Dispose();
}
pipeServer.Dispose();
base.OnFormClosing(e);
// 用户选择关闭程序
Application.Exit();
}
else if (result == DialogResult.No)
{
// 用户选择隐藏窗口
e.Cancel = true; // 取消关闭操作
this.Hide(); // 隐藏窗口
this.ShowInTaskbar = false;//任务栏中显示标志
}
else
{
// 用户选择取消操作
e.Cancel = true; // 取消关闭操作
}
}
}
private async Task FaceServerAsync()
{
try
{
// 处理当前连接的所有数据
while (pipeServer.IsConnected)
{
// 读取所有数据帧,然后直接选取最后一个,其他丢弃
var jpegData = pipeServer.ReadAllAvailableFrameData()?.Last();
if (jpegData == null){
continue;
}
// 对jpeg图片做人脸识别
var result = Server.Recognition(jpegData);
// 没数据,进下一轮
if (result.Count <= 0)
{
continue;
}
result.ForEach(f => Log.Information($"识别到人脸:{f.Name} 位置:{f.FaceRect}"));
// 序列化要发送的数据
var send = MessagePackSerializer.Serialize(result);
// 发送包头,标记后面数据长度
await pipeServer.WriteAsync(BitConverter.GetBytes(send.Length), 0, 4);
// 发送正式数据
await pipeServer.WriteAsync(send, 0, send.Length);
}
}
catch (Exception ex)
{
Log.Error(ex, "处理管道数据时发生错误");
// 处理异常
}
finally
{
// 检查连接状态并断开(如果客户端还未断开)
if (pipeServer.IsConnected)
{
pipeServer.Close();
}
}
}
private void Main_Load(object sender, EventArgs e)
{
Logging.Init(tbLog);
Log.Information("加载人脸服务");
var _initCompletionSource = new TaskCompletionSource<bool>();
Task.Factory.StartNew(() =>
{
Log.Information("开始初始化人脸服务");
Server = new FaceRecognitionServer("Face", "Model");
Server.RoiSize = 480;
Log.Information("人脸服务初始化成功");
_initCompletionSource.SetResult(true);
});
Task.Factory.StartNew(async () =>
{
await _initCompletionSource.Task;
pipeServer = new NamedPipeServerStream("FACE", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
Log.Information("开始运行命名管道");
while (true)
{
await pipeServer.WaitForConnectionAsync();
Log.Information("客户端已连接");
await FaceServerAsync();
Log.Information("客户端已断开连接");
}
}, TaskCreationOptions.LongRunning);
Log.Information("软件启动成功");
}
private void Main_Shown(object sender, EventArgs e)
{
this.Hide();
}
private void cbPowerOn_CheckedChanged(object sender, EventArgs e)
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true))
{
if (cbPowerOn.Checked)
{
Log.Debug("添加到开机启动");
// 添加注册表项
key.SetValue("FaceServer", Application.ExecutablePath.ToString());
}
else
{
Log.Debug("移除开机启动");
// 移除注册表项
key.DeleteValue("FaceServer", false);
}
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file
The file could not be displayed because it is too large.
The file could not be displayed because it is too large.
using MessagePack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
namespace FaceServer
{
public static class ObejctEx
{
public static T ToObejct<T>(this byte[] @this)
{
T data = MessagePackSerializer.Deserialize<T>(@this);
return data;
}
}
}
using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Serilog;
using MessagePack;
namespace FaceServer
{
public static class PipeEx
{
public static void Write(this PipeStream @this, byte[] data)
{
@this.Write(BitConverter.GetBytes(data.Length), 0, sizeof(int));
@this.Write(data, 0, data.Length);
}
public static async Task<byte[]> GetBytes(this PipeStream @this)
{
var len = await GetDataLengthAsync(@this);
var data = await GetData(@this, len);
return data;
}
public static async void WriteAsync(this PipeStream @this, byte[] data)
{
await @this.WriteAsync(BitConverter.GetBytes(data.Length), 0, sizeof(int));
await @this.WriteAsync(data, 0, data.Length);
}
public static List<byte[]> ReadAllAvailableFrameData(this PipeStream @this)
{
var allFrameData = new List<byte[]>();
// 如果管道里有数据可以取
while (@this.InBufferSize != 0)
{
try
{
var messageData = new List<byte>();
do
{
byte[] buffer = new byte[256];
int bytesRead = @this.Read(buffer, 0, buffer.Length);
messageData.AddRange(buffer.Take(bytesRead));
}
while (!@this.IsMessageComplete);
allFrameData.Add(messageData.ToArray());
}
catch (EndOfStreamException)
{
break; // 到达流的末尾
}
catch (IOException ex)
{
Log.Error(ex, "读取管道数据时发生 I/O 异常");
throw;
}
catch (Exception ex)
{
Log.Error(ex, "反序列化 FrameData 时发生异常");
throw;
}
}
return allFrameData;
}
private static bool TryReadDataLength(PipeStream pipeStream, out int dataLength)
{
byte[] lengthBuffer = new byte[4];
int bytesRead = pipeStream.Read(lengthBuffer, 0, 4);
if (bytesRead == 4)
{
dataLength = BitConverter.ToInt32(lengthBuffer, 0);
return true;
}
dataLength = 0;
return false;
}
public static async Task<int> GetDataLengthAsync(this PipeStream @this)
{
byte[] lengthBuffer = new byte[4];
await @this.ReadAsync(lengthBuffer, 0, 4);
var dataLength = BitConverter.ToInt32(lengthBuffer, 0);
return dataLength;
}
public static async Task<byte[]> GetData(this PipeStream @this, int dataLength)
{
// 然后读取相应长度的数据
byte[] buffer = new byte[dataLength];
int totalRead = 0;
while (totalRead < dataLength)
{
int read = await @this.ReadAsync(buffer, totalRead, dataLength - totalRead);
if (read == 0)
{
throw new IOException("客户端断开连接");
}
totalRead += read;
}
return buffer;
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FaceServer
{
internal static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Process[] proccess = Process.GetProcesses();//获取所有进程
string strCaCuProcessName = "FaceServer";//当前程序名
foreach (var pr in proccess)
{
if (pr.ProcessName == strCaCuProcessName && pr.Id != Process.GetCurrentProcess().Id)
{
//当前程序名相等且进程ID不一致,不加进程ID程序起不来(这时候程序已经运行着)
Environment.Exit(0);
}
}
Application.Run(new Main());
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("FaceServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FaceServer")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("1a20e2de-f5fd-4555-93ce-ac9cee9e8fa2")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace FaceServer.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FaceServer.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性,对
/// 使用此强类型资源类的所有资源查找执行重写。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FaceServer.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting.Display;
using Serilog.Formatting;
using System;
using System.IO;
using System.Windows.Forms;
public class TextBoxSink : ILogEventSink
{
private readonly ITextFormatter _textFormatter;
private readonly TextBox _textBox;
public TextBoxSink(TextBox textBox, string outputTemplate)
{
_textBox = textBox ?? throw new ArgumentNullException(nameof(textBox));
_textFormatter = new MessageTemplateTextFormatter(outputTemplate, null);
}
public void Emit(LogEvent logEvent)
{
if (_textBox.InvokeRequired)
{
_textBox.Invoke(new Action(() => Emit(logEvent)));
return;
}
StringWriter stringWriter = new StringWriter();
_textFormatter.Format(logEvent, stringWriter);
_textBox.AppendText(stringWriter.ToString() + Environment.NewLine);
}
}
using System;
using System.IO;
using System.Collections.Generic;
using FaceRecognitionDotNet;
using OpenCvSharp;
using System.Threading;
using System.Linq;
using System.Drawing;
using System.Windows;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
public class FaceRecognitionServer
{
private static FaceRecognition FaceRecognition = null;
private static Dictionary<string, FaceEncoding> KnownFaceEncodings = null;
public Rectangle Roi { set; get; } = default;
public int RoiSize { set; get; } = default;
public FaceRecognitionServer(string faceDataPath, string modelPath)
{
FaceRecognition = FaceRecognition ?? FaceRecognition.Create(modelPath);
KnownFaceEncodings = KnownFaceEncodings ?? LoadKnownFaces(FaceRecognition, faceDataPath);
}
public Rectangle GetROI(Mat frame)
{
// 计算中央ROI位置
int x = (frame.Cols - RoiSize) / 2; // 修改为PixelWidth
int y = (frame.Rows - RoiSize) / 2; // 修改为PixelHeight
return new Rectangle(x, y, RoiSize, RoiSize); // 使用Int32Rect
}
// 人脸识别线程方法
public List<FaceData> Recognition(byte[] jpegData)
{
// 将 JPEG 字节数据转换为 Bitmap
Mat originalMat;
using (var ms = new MemoryStream(jpegData))
{
originalMat = Mat.FromStream(ms, ImreadModes.Color);
}
if (Roi == default)
{
Roi = GetROI(originalMat);
}
// 提取 ROI
var roiRectangle = new OpenCvSharp.Rect(Roi.X, Roi.Y, Roi.Width, Roi.Height);
Mat roiMat = new Mat(originalMat, roiRectangle);
originalMat.Dispose();
// 转换为灰度图
//Mat grayMat = new Mat();
//Cv2.CvtColor(roiMat, grayMat, ColorConversionCodes.BGR2GRAY);
//roiMat.Dispose();
var bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(roiMat);
// 使用 LoadImage 加载图像
using (var image = FaceRecognition.LoadImage(bitmap))
{
bitmap.Dispose();
// Detect faces
var faceLocations = FaceRecognition.FaceLocations(image);
if (faceLocations.Count() == 0)
{
image.Dispose();
return new List<FaceData>();
}
var faceEncodings = FaceRecognition.FaceEncodings(image, faceLocations);
List<FaceData> faces = new List<FaceData>();
for (int i = 0; i < faceEncodings.Count(); i++)
{
var encoding = faceEncodings.ElementAt(i);
// Find match for known faces
var bestMatch = FindBestMatch(encoding, KnownFaceEncodings);
var location = faceLocations.ElementAt(i);
// 映射回整个图像的坐标空间
var faceRect = new Rectangle
(
location.Left + Roi.X, // 加上ROI的X偏移
location.Top + Roi.Y, // 加上ROI的Y偏移
location.Right - location.Left,
location.Bottom - location.Top
);
faces.Add(new FaceData
{
FaceRect = faceRect,
Name = bestMatch,
IsIdentified = bestMatch != "Unknown"
});
}
return faces;
}
}
// Helper method to load known faces
Dictionary<string, FaceEncoding> LoadKnownFaces(FaceRecognition faceRecognition, string faceDataPath)
{
var knownFaceEncodings = new Dictionary<string, FaceEncoding>();
foreach (var imagePath in Directory.GetFiles(faceDataPath, "*.jpg"))
{
var name = Path.GetFileNameWithoutExtension(imagePath);
var image = FaceRecognition.LoadImageFile(imagePath);
var faceEncoding = faceRecognition.FaceEncodings(image).FirstOrDefault();
if (faceEncoding != null)
{
knownFaceEncodings.Add(name, faceEncoding);
}
}
return knownFaceEncodings;
}
// Helper method to find best match for a face
string FindBestMatch(FaceEncoding encoding, Dictionary<string, FaceEncoding> knownFaceEncodings)
{
double tolerance = 0.4; // Tolerance level for matching, may need adjustment
string bestMatchName = "Unknown";
double bestMatchDistance = double.MaxValue;
foreach (var knownFace in knownFaceEncodings)
{
var distance = FaceRecognition.FaceDistance(encoding, knownFace.Value);
if (distance < bestMatchDistance && distance < tolerance)
{
bestMatchDistance = distance;
bestMatchName = knownFace.Key;
}
}
return bestMatchName;
}
}
using MessagePack;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows;
using System.Windows.Media.Imaging;
public struct FaceRecognitionResult
{
public DateTime Timestamp;
public List<FaceData> Faces;
}
[MessagePackObject]
public struct FaceData
{
[Key(0)]
public Rectangle FaceRect;
[Key(1)]
public string Name;
[Key(2)]
public bool IsIdentified;
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="DlibDotNet" version="19.21.0.20220724" targetFramework="net48" />
<package id="FaceRecognitionDotNet" version="1.3.0.7" targetFramework="net48" />
<package id="MessagePack" version="2.5.140" targetFramework="net48" />
<package id="MessagePack.Annotations" version="2.5.140" targetFramework="net48" />
<package id="Microsoft.Bcl.AsyncInterfaces" version="6.0.0" targetFramework="net48" />
<package id="Microsoft.NET.StringTools" version="17.6.3" targetFramework="net48" />
<package id="OpenCvSharp4" version="4.9.0.20240103" targetFramework="net48" />
<package id="OpenCvSharp4.Extensions" version="4.9.0.20240103" targetFramework="net48" />
<package id="OpenCvSharp4.runtime.win" version="4.9.0.20240103" targetFramework="net48" />
<package id="OpenCvSharp4.Windows" version="4.9.0.20240103" targetFramework="net48" />
<package id="OpenCvSharp4.WpfExtensions" version="4.9.0.20240103" targetFramework="net48" />
<package id="Serilog" version="2.10.0" targetFramework="net48" />
<package id="Serilog.Enrichers.Thread" version="3.1.0" targetFramework="net48" />
<package id="Serilog.Sinks.File" version="5.0.0" targetFramework="net48" />
<package id="Serilog.Sinks.Trace" version="3.0.0" targetFramework="net48" />
<package id="System.Buffers" version="4.5.1" targetFramework="net48" />
<package id="System.Collections.Immutable" version="6.0.0" targetFramework="net48" />
<package id="System.Drawing.Common" version="7.0.0" targetFramework="net48" />
<package id="System.Memory" version="4.5.5" targetFramework="net48" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
<package id="System.Reflection.Emit" version="4.7.0" targetFramework="net48" />
<package id="System.Reflection.Emit.Lightweight" version="4.7.0" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="6.0.0" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net48" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net48" />
</packages>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment