话说现在检测人脸的技术有很多。有在线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. java 后台封装json数据学习总结(一)

    一.数据封装 1. List集合转换成json代码 List list = new ArrayList(); list.add( "first" ); list.add( &quo ...

  2. Eclipse去除网上复制下来的来代码带有的行号

    一.正则表达式去除代码行号 作为开发人员,我们经常从网上复制一些代码,有些时候复制的代码前面是带有行号,如: MyEclipse本身自带有查找替换功能,并且支持正则表达式替换,使用正则替换就可以很容易 ...

  3. java基础之二分法查找

    package p1; import java.util.*; public class Sortdob { public static void BubbleSort(int[] arr) {    ...

  4. JQuery实现点击按钮切换图片(附源码)--JQuery基础

    JQuery实现切换图片相对比较简单,直接贴代码了哈,有注释噢!疑问请追加评论哈,不足之处还请大佬们指出! 1.案例代码: demo.html: <!DOCTYPE html><ht ...

  5. 浏览器之window对象--javascript

    window对象代表打开的浏览器窗口,是Web浏览器所有内容的主容器.window对象是整个对象链条结构的最高层,是其他对象的父对象,在调用window对象的方法和属性时,可以省略window对象的引 ...

  6. 第三篇:爬虫框架 - Scrapy

    前言 Python提供了一个比较实用的爬虫框架 - Scrapy.在这个框架下只要定制好指定的几个模块,就能实现一个爬虫. 本文将讲解Scrapy框架的基本体系结构,以及使用这个框架定制爬虫的具体步骤 ...

  7. 洛谷P4003 无限之环(infinityloop)(网络流,费用流)

    洛谷题目传送门 题目 题目描述 曾经有一款流行的游戏,叫做 Infinity Loop,先来简单的介绍一下这个游戏: 游戏在一个 n ∗ m 的网格状棋盘上进行,其中有些小方格中会有水管,水管可能在格 ...

  8. linux开机启动流程及需要开机启动服务讲解和修改及防火墙

    linux系统从开机到登陆的启动流程. 1.开机BIOS自检 2.MBR引导 3.grub引导菜单 4.加载内核kernel 5.启动init进程 6.读取inittab文件,执行rc.sysinit ...

  9. iOS开发中常见bug!(内附解答方法)

    序言 你是否曾经修复了一个 bug ,随后又发现了一个跟刚修复 bug 有关的 bug ,又或是修复 bug 的方式引起了另一个 bug ? 然而这些问题是绝佳的学习机会.所以我们怎样尽可能多地从修复 ...

  10. CentOS7.4安装MySQL踩坑记录

    CentOS7.4安装MySQL踩坑记录 time: 2018.3.19 CentOS7.4安装MySQL时网上的文档虽然多但是不靠谱的也多, 可能因为版本与时间的问题, 所以记录下自己踩坑的过程, ...