话说现在检测人脸的技术有很多。有在线AI服务,比如Megvii Face++,Microsoft Cognitive Services,Tencent AI等等。还有本地的库实现的,比如OpenCV。

但是这些这篇文章都不讨论,微软在 .NETCore里面也提供了一种本地检测人脸的API,那就是Windows.Media.FaceAnalysis

.NetCore在你新建通用UWP应用的时候,Nuget自动添加了。

那么接下来,我们在设计Xaml代码的时候,加两个按钮,一个是选择图片,一个是检测人脸。

再建一个Canvas控件,用来显示图片。

之所以用Canvas画布,不用Image,是因为我们还需要在图片上画出一个矩形框,框出识别的人脸位置和大小呢。

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions> <Button Content="Choose Picture" Click="ChoosePicture"/>
<Button Grid.Column="1" Content="Detect Face" Click="DetectFace"/> <Canvas x:Name="canvasDetected" Grid.ColumnSpan="2" Grid.Row="1"  VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
</Grid>

然后开始写代码,选择图片的逻辑很简单,只需要选择一个图片,显示到Canvas中即可。

private async void ChoosePicture(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".bmp");
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".jpg");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
using (IRandomAccessStream strm = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(strm);
BitmapTransform transform = new BitmapTransform();
source = await decoder.GetSoftwareBitmapAsync(); WriteableBitmap displaySource = new WriteableBitmap(source.PixelWidth, source.PixelHeight);
source.CopyToBuffer(displaySource.PixelBuffer); ImageBrush brush = new ImageBrush();
brush.ImageSource = displaySource;
brush.Stretch = Stretch.Uniform;
canvasDetected.Background = brush;
canvasDetected.Children.Clear();
}
}
}

遇到红色波浪线提示的,用VS自动修复功能,自动添加引用即可。

还有一个source没有定义,不慌,反正下一步就要检测人脸了,我们来看一看FaceDetector的定义

namespace Windows.Media.FaceAnalysis
{
//
// 摘要:
// 在 SoftwareBitmap 中检测人脸。
[ContractVersion(typeof(UniversalApiContract), )]
[MarshalingBehavior(MarshalingType.Agile)]
[Static(typeof(IFaceDetectorStatics), , "Windows.Foundation.UniversalApiContract")]
[Threading(ThreadingModel.Both)]
public sealed class FaceDetector : IFaceDetector
{
//
// 摘要:
// 异步检测提供的 SoftwareBitmap 中的人脸。
//
// 参数:
// image:
// 要进行人脸检测处理的图像数据。
//
// 返回结果:
// 一个异步操作,在成功完成时返回 DetectedFace 对象的列表。
[Overload("DetectFacesAsync")]
[RemoteAsync]
public IAsyncOperation<IList<DetectedFace>> DetectFacesAsync(SoftwareBitmap image);
}
}

看到没,使用FaceDetector需要一个SoftwareBitmap,那么好了,我们定义一个私有变量SoftwareBitmap source即可。

然后写检测的代码,

private async void DetectFace(object sender, RoutedEventArgs e)
{
const BitmapPixelFormat faceDetectionPixelFormat = BitmapPixelFormat.Gray8;
SoftwareBitmap converted;
if (source.BitmapPixelFormat != faceDetectionPixelFormat)
{
converted = SoftwareBitmap.Convert(source, faceDetectionPixelFormat);
}
else
{
converted = source;
} FaceDetector faceDetector = await FaceDetector.CreateAsync();
IList<DetectedFace> detectedFaces = await faceDetector.DetectFacesAsync(converted);
DrawBoxes(detectedFaces);  //这个功能在实际场景中使用不多,在这可以写你的实际业务场景
}

画人脸矩形:


        //这个功能在实际场景中使用不多
        private void DrawBoxes(IList<DetectedFace> detectedFaces)
{
if (detectedFaces != null)
{
//get the scaling factor
double scaleWidth = source.PixelWidth / this.canvasDetected.ActualWidth;
double scaleHeight = source.PixelHeight / this.canvasDetected.ActualHeight;
double scalingFactor = scaleHeight > scaleWidth ? scaleHeight : scaleWidth; //get the display width of the image.
double displayWidth = source.PixelWidth / scalingFactor;
double displayHeight = source.PixelHeight / scalingFactor; //get the delta width/height between canvas actual width and the image display width
double deltaWidth = this.canvasDetected.ActualWidth - displayWidth;
double deltaHeight = this.canvasDetected.ActualHeight - displayHeight; SolidColorBrush lineBrush = new SolidColorBrush(Windows.UI.Colors.White);
double lineThickness = 2.0;
SolidColorBrush fillBrush = new SolidColorBrush(Windows.UI.Colors.Transparent); foreach (DetectedFace face in detectedFaces)
{
Rectangle box = new Rectangle();
box.Tag = face.FaceBox;
//scale the box with the scaling factor
box.Width = face.FaceBox.Width / scalingFactor;
box.Height = face.FaceBox.Height / scalingFactor;
box.Fill = fillBrush;
box.Stroke = lineBrush;
box.StrokeThickness = lineThickness;
//set coordinate of the box in the canvas
box.Margin = new Thickness((uint)(face.FaceBox.X / scalingFactor + deltaWidth / ), (uint)(face.FaceBox.Y / scalingFactor + deltaHeight / ), , );
this.canvasDetected.Children.Add(box);
}
}
}

其实,像上面的DrawBoxes注释那样,一般用的还不算多。

我的项目都是判断如果detectedFaces不是null的话,接下来就可以调用云API来实现人脸搜索了,毕竟这个本地微软的api还做不到。

下面看一下效果

 总结

微软提供的FaceDetector还是挺实用的,毕竟可以节约我们一遍一遍像服务器发送请求检测人脸的开支了,虽然云API检测人脸并不贵,face++的10000次才一块钱。毕竟你上传图片,还不要带宽资源吧。万一碰到个网络不好,那不是还要再请求一次。。。哈哈,折腾点。

不过这个也随便了,看自己喜好吧。

UWP 使用Windows.Media.FaceAnalysis.FaceDetector检测人脸的更多相关文章

  1. iOS开发中使用CIDetector检测人脸

    在iOS5 系统中,苹果就已经有了检测人脸的api,能够检测人脸的位置,包括左右眼睛,以及嘴巴的位置,返回的信息是每个点位置.在 iOS7中,苹果又加入了检测是否微笑的功能.通过使用 CIDetect ...

  2. Windows Server 2003从入门到精通之Windows Media Server流媒体服务器架建[转]

    今天我们来做一个windows media server流媒体格式文件的流媒体服务器. 现在市面上能够买到的一些电影文件有 rm格式和wmv格式.还有一些是DivX技术的avi格式,要想让你的服务器对 ...

  3. System.Windows.Media.Imageing.BItmapImage 这么用才不会占用文件

    // Read byte[] from png file BinaryReader binReader = new BinaryReader(File.Open(filepath, FileMode. ...

  4. win7自带windows media player 已停止工作

    解决方法如下: 在计算机开始,菜单找到控制面板 ,然后打开程序和功能,选择打开或关闭window功能,媒体功能.再取消windows Media Center Windows MediaPlayer选 ...

  5. Windows Media Player安装了却不能播放网页上的视频

    前段时间遇到Windows Media Player安装了却不能播放网页上的视频的问题,在网上查找资料时,发现大部分资料都没能解决我这个问题.偶尔试了网上一牛人的方法,后来竟然解决了.现在再找那个网页 ...

  6. 如何在Windows中打开多个Windows Media Player

    博客搬到了fresky.github.io - Dawei XU,请各位看官挪步.最新的一篇是:如何在Windows中打开多个Windows Media Player.

  7. Windows Media Player axWindowsMediaPlayer1 分类: C# 2014-07-28 12:04 195人阅读 评论(0) 收藏

    属性/方法名: 说明: [基本属性] URL:String; 指定媒体位置,本机或网络地址 uiMode:String; 播放器界面模式,可为Full, Mini, None, Invisible p ...

  8. Windows Media Player Plus

    Windows Media Player Plus 是一款 Windows Media Player 的插件,提供很多实用功能,Mark 一下.

  9. windows media player 中播放pls的方法

    windows media player目前只能播放 wpl 和 asm格式的列表文件.而linux下mplayer和vlc支持的pls,很遗憾没法支持. 不过,老外写了个“open pls in w ...

随机推荐

  1. hibernate(二)主键生成策略

    hibernate主键生成策略主要指的是在实体类orm的配置 <id name=""> <generator class="native"&g ...

  2. 2017java文件操作(读写操作)

    java的读写操作是学java开发的必经之路,下面就来总结下java的读写操作. 从上图可以开出,java的读写操作(输入输出)可以用"流"这个概念来表示,总体而言,java的读写 ...

  3. .Net Core 1.0升级2.0(xproj项目迁移到.csproj )

    vs2015的创建的项目是以*.xproj的项目文件,迁移到vs2017需要如下准备: 1.安装好vs2017(废话) 2.下载最新的SDK和 .NET Core 2.0 Preview 1 Runt ...

  4. Android查缺补漏(线程篇)-- AsyncTask的使用及原理详细分析

    本文作者:CodingBlock 文章链接:http://www.cnblogs.com/codingblock/p/8515304.html 一.AsyncTask的使用 AsyncTask是一种轻 ...

  5. BUAA软工第0次作业

    第一部分:结缘计算机 1.你为什么选择计算机专业?你认为你的条件如何?和这些博主比呢?(必答) 我在大学之前甚至连一个萌新都算不上,根本没有任何一点计算机专业的基础. 因此在进入大学之前,计算机对于我 ...

  6. (python)剑指Offer(第二版)面试题14:剪绳子

    题目 给你一根长度为n的绳子,请把绳子剪成m段 (m和n都是整数,n>1并且m>1)每段绳子的长度记为k[0],k[1],…,k[m].请问k[0]k[1]…*k[m]可能的最大乘积是多少 ...

  7. MyEclipse 2014专业版的破解--Windows系统的软件安装

    一.破解前的准备 MyEclipse2014破解包: 您可以到计算机相关专业所用软件---百度云链接下载中找到链接地址进行下载. 二.破解步骤 1.打开破解文件资源包 2.执行run.bat 3.输入 ...

  8. centos svn 服务器间的数据迁移

    svnadmin dump erp > ~/erp.svn   当前目录下的erp 导出到根目录下名为erp.svn tar -zcvf backupSvn.tar.gz backupSvn   ...

  9. [BZOJ4517] [Sdoi2016] 排列计数 (数学)

    Description 求有多少种长度为 n 的序列 A,满足以下条件: 1 ~ n 这 n 个数在序列中各出现了一次 若第 i 个数 A[i] 的值为 i,则称 i 是稳定的.序列恰好有 m 个数是 ...

  10. up61博客模版版本v1.0.0

    经过两天的努力 终于把博客模板框架写出来了. 表示写模板累死了,很久没有写样式了,还是那么难搞.没有PHP写函数爽. 不管怎么样 第一版出来了.以下是部分截图.预览 当然在示例部署到项目上的时候 ,部 ...