WPF开发者QQ群

此群已满340500857 ,请加新群458041663

由于微信群人数太多入群请添加小编微信号

 yanjinhuawechatW_Feng_aiQ 邀请入群

需备注WPF开发者

PS:有更好的方式欢迎推荐。

接着上一篇

利用已经训练好的数据文件,检测人脸 地址如下:

https://github.com/opencv/opencv/tree/master/data/haarcascades

使用NuGet如下:

01

代码如下

一、创建MainWindow.xaml代码如下。

<ws:Window x:Class="OpenCVSharpExample.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:ws="https://github.com/WPFDevelopersOrg.WPFDevelopers.Minimal"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:OpenCVSharpExample"Icon="OpenCV_Logo.png"mc:Ignorable="d" WindowStartupLocation="CenterScreen"Title="OpenCVSharpExample https://github.com/WPFDevelopersOrg" Height="450" Width="800"><Grid Margin="4"><Grid.ColumnDefinitions><ColumnDefinition MinWidth="500" Width="8*"/><ColumnDefinition Width="2*" MinWidth="200"/></Grid.ColumnDefinitions><Image Grid.Row="0" Name="imgViewport"/><GridSplitter Grid.Column="0" HorizontalAlignment="Right" Width="2"/><GroupBox Header="Operation" Grid.Column="1" Margin="0,0,4,0"><Grid><Grid.RowDefinitions><RowDefinition/><RowDefinition/><RowDefinition Height="Auto"/></Grid.RowDefinitions><StackPanel Grid.Row="0" HorizontalAlignment="Left"><CheckBox IsChecked="{Binding IsSave,RelativeSource={RelativeSource AncestorType=local:MainWindow}}"VerticalAlignment="Center" Content="Save" Margin="0,4"/><CheckBox IsChecked="{Binding IsFace,RelativeSource={RelativeSource AncestorType=local:MainWindow}}"VerticalAlignment="Center" Content="Face" Margin="0,4"/><ComboBox Name="ComboBoxCamera" ItemsSource="{Binding CameraArray,RelativeSource={RelativeSource AncestorType=local:MainWindow}}" SelectedIndex="{Binding CameraIndex,RelativeSource={RelativeSource AncestorType=local:MainWindow}}"SelectionChanged="ComboBoxCamera_SelectionChanged"/></StackPanel><StackPanel Orientation="Horizontal" Grid.Row="2" HorizontalAlignment="Center"><Button Name="btPlay" Content="Play" Style="{StaticResource PrimaryButton}" Click="btPlay_Click" IsEnabled="False"/><Button Name="btStop" Click="btStop_Click" Content="Stop" Margin="4,0"/></StackPanel></Grid></GroupBox></Grid>
</ws:Window>

二、MainWindow.xaml.cs代码如下。

using OpenCvSharp;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Management;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Threading;namespace OpenCVSharpExample
{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>public partial class MainWindow{private VideoCapture capCamera;private VideoWriter videoWriter;private Mat matImage = new Mat();private Thread cameraThread;private Thread writerThread;private CascadeClassifier haarCascade;private WriteableBitmap writeableBitmap;private Rectangle rectangle;private Mat gray;private Mat result;private OpenCvSharp.Rect[] faces;public List<string> CameraArray{get { return (List<string>)GetValue(CameraArrayProperty); }set { SetValue(CameraArrayProperty, value); }}public static readonly DependencyProperty CameraArrayProperty =DependencyProperty.Register("CameraArray", typeof(List<string>), typeof(MainWindow), new PropertyMetadata(null));public int CameraIndex{get { return (int)GetValue(CameraIndexProperty); }set { SetValue(CameraIndexProperty, value); }}public static readonly DependencyProperty CameraIndexProperty =DependencyProperty.Register("CameraIndex", typeof(int), typeof(MainWindow), new PropertyMetadata(0));public bool IsSave{get { return (bool)GetValue(IsSaveProperty); }set { SetValue(IsSaveProperty, value); }}public static readonly DependencyProperty IsSaveProperty =DependencyProperty.Register("IsSave", typeof(bool), typeof(MainWindow), new UIPropertyMetadata(IsSaveChanged));private static void IsSaveChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){var mainWindow = d as MainWindow;if (e.NewValue != null){var save = (bool) e.NewValue;if (save)mainWindow.StartRecording();elsemainWindow.StopRecording();}}public bool IsFace{get { return (bool)GetValue(IsFaceProperty); }set { SetValue(IsFaceProperty, value); }}public static readonly DependencyProperty IsFaceProperty =DependencyProperty.Register("IsFace", typeof(bool), typeof(MainWindow), new UIPropertyMetadata(IsFaceChanged));private static void IsFaceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){var mainWindow = d as MainWindow;if (e.NewValue != null){var save = (bool)e.NewValue;if (save)mainWindow.CreateFace();elsemainWindow.CloseFace();}}public MainWindow(){InitializeComponent();Width = SystemParameters.WorkArea.Width / 1.5;Height = SystemParameters.WorkArea.Height / 1.5;this.Loaded += MainWindow_Loaded;}private void MainWindow_Loaded(object sender, RoutedEventArgs e){InitializeCamera();}private void ComboBoxCamera_SelectionChanged(object sender, SelectionChangedEventArgs e){if (CameraArray.Count - 1 < CameraIndex)return;if (capCamera != null && cameraThread != null){cameraThread.Abort();StopDispose();}CreateCamera();writeableBitmap = new WriteableBitmap(capCamera.FrameWidth, capCamera.FrameHeight, 0, 0, System.Windows.Media.PixelFormats.Bgra32, null);imgViewport.Source = writeableBitmap;}private void btStop_Click(object sender, RoutedEventArgs e){StopDispose();btStop.IsEnabled = false;}protected override void OnClosing(CancelEventArgs e){if(WPFDevelopers.Minimal.Controls.MessageBox.Show("是否关闭系统?", "询问", MessageBoxButton.OKCancel, MessageBoxImage.Question) != MessageBoxResult.OK) {e.Cancel = true;return;}}protected override void OnClosed(EventArgs e){StopDispose();}private void btPlay_Click(object sender, RoutedEventArgs e){btPlay.IsEnabled = false;btStop.IsEnabled = true;CreateCamera();}#region 方法void CloseFace(){if (haarCascade != null){haarCascade.Dispose();haarCascade = null;gray.Dispose();gray = null;result.Dispose();result = null;faces = null;}}void CreateFace(){var facePath = System.IO.Path.Combine(System.Environment.CurrentDirectory, "Data/haarcascade_frontalface_default.xml");if (!System.IO.File.Exists(facePath)){WPFDevelopers.Minimal.Controls.MessageBox.Show("缺少人脸检测文件。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);return;}haarCascade = new CascadeClassifier(facePath);}private void InitializeCamera(){CameraArray = GetAllConnectedCameras();}List<string> GetAllConnectedCameras(){var cameraNames = new List<string>();using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')")){foreach (var device in searcher.Get()){cameraNames.Add(device["Caption"].ToString());}}return cameraNames;}void CreateCamera(){capCamera = new VideoCapture(CameraIndex);capCamera.Fps = 30;cameraThread = new Thread(PlayCamera);cameraThread.Start();}private void PlayCamera(){while (capCamera != null && !capCamera.IsDisposed){capCamera.Read(matImage);if (matImage.Empty()) break;Dispatcher.Invoke(new Action(() =>{if (IsFace){result = matImage.Clone();gray = new Mat();Cv2.CvtColor(result, gray, ColorConversionCodes.BGR2GRAY);faces = haarCascade.DetectMultiScale(gray, 1.3);if (faces.Length > 0){Cv2.Rectangle(matImage, faces[0], Scalar.Green, 2);}result.Dispose();}}));using (var img = BitmapConverter.ToBitmap(matImage)){var now = DateTime.Now;var g = Graphics.FromImage(img);var brush = new SolidBrush(System.Drawing.Color.Red);System.Globalization.CultureInfo cultureInfo = new CultureInfo("zh-CN");var week = cultureInfo.DateTimeFormat.GetAbbreviatedDayName(now.DayOfWeek);g.DrawString($"{week} { now.ToString("yyyy年MM月dd日 HH:mm:ss ")} ", new System.Drawing.Font(System.Drawing.SystemFonts.DefaultFont.Name, System.Drawing.SystemFonts.DefaultFont.Size), brush, new PointF(0, matImage.Rows - 20));brush.Dispose();g.Dispose();rectangle = new Rectangle(0, 0, img.Width, img.Height);Dispatcher.Invoke(new Action(() =>{WriteableBitmapHelper.BitmapCopyToWriteableBitmap(img, writeableBitmap, rectangle, 0, 0, System.Drawing.Imaging.PixelFormat.Format32bppArgb);}));img.Dispose();};Thread.Sleep(100);}}private void StartRecording(){if (capCamera == null){WPFDevelopers.Minimal.Controls.MessageBox.Show("未开启摄像机", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Error);return;}var videoFile = System.IO.Path.Combine(System.Environment.CurrentDirectory, "Video");if (!System.IO.Directory.Exists(videoFile))System.IO.Directory.CreateDirectory(videoFile);var currentTime = System.IO.Path.Combine(videoFile, $"{DateTime.Now.ToString("yyyyMMddHHmmsshh")}.avi");videoWriter = new VideoWriter(currentTime, FourCCValues.XVID, capCamera.Fps, new OpenCvSharp.Size(capCamera.FrameWidth, capCamera.FrameHeight));writerThread = new Thread(AddCameraFrameToRecording);writerThread.Start();}private void StopRecording(){if (videoWriter != null && !videoWriter.IsDisposed){videoWriter.Release();videoWriter.Dispose();videoWriter = null;}}private void AddCameraFrameToRecording(){var waitTimeBetweenFrames = 1_000 / capCamera.Fps;var lastWrite = DateTime.Now;while (!videoWriter.IsDisposed){if (DateTime.Now.Subtract(lastWrite).TotalMilliseconds < waitTimeBetweenFrames)continue;lastWrite = DateTime.Now;videoWriter.Write(matImage);}}void StopDispose(){if (capCamera != null && capCamera.IsOpened()){capCamera.Dispose();capCamera = null;}if (videoWriter != null && !videoWriter.IsDisposed){videoWriter.Release();videoWriter.Dispose();videoWriter = null;}CloseFace();btPlay.IsEnabled = true;GC.Collect();}void CreateRecord(){cameraThread = new Thread(PlayCamera);cameraThread.Start();}#endregion}
}

02

效果预览

鸣谢素材提供者OpenCVSharp

源码地址如下

Github:https://github.com/WPFDevelopersOrg

https://github.com/WPFDevelopersOrg/OpenCVSharpExample

Gitee:https://gitee.com/WPFDevelopersOrg

WPF开发者QQ群: 340500857 

Github:https://github.com/WPFDevelopersOrg

出处:https://www.cnblogs.com/yanjinhua

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

转载请著名作者 出处 https://github.com/WPFDevelopersOrg

扫一扫关注我们,

更多知识早知道!

点击阅读原文可跳转至源代码

WPF 实现人脸检测相关推荐

  1. Microsoft Azure和WPF实现人脸检测

    在本文中,详解如何使用Microsoft Azure和WPF技术的帮助下使用实现人脸API应用程序.该应用程序检测人脸图像,显示每张脸周围的红框,以及通过将光标移动到框来显示每张脸的描述的状态栏. 先 ...

  2. 使用UWP人脸检测API在WPF中进行人脸检测

    目录 介绍 先决条件 背景 人脸检测 标记人脸 查看模型 视图 结论 Download repository 介绍 通用Windows平台的Windows.Media.FaceAnalysis名称空间 ...

  3. OpenCV+python:人脸检测

    1,人脸检测简介 人脸检测的模型主要有两类,一类是知识模型,根据眼睛.嘴.鼻子的相对位置或面部不同部位的颜色深度差异来检测人脸,另一类是统计模型,把海量的人脸数据转换成二维像素矩阵,从统计的观点出发构 ...

  4. 使用Python,OpenCV和Haar级联进行人脸检测——轻量级的人脸检测器

    使用Python,OpenCV和Haar级联进行人脸检测--轻量级的人脸检测器 1. 效果图 2. 原理 2.1 项目结构 2.2 [haarcascade_frontalface_default.x ...

  5. opencvmediapipe 人脸检测+摄像头实时

    文章目录 单张人脸关键点检测 单张图像人脸检测 摄像头实时关键点检测 单张人脸关键点检测 定义可视化图像函数 导入三维人脸关键点检测模型 导入可视化函数和可视化样式 读取图像 将图像模型输入,获取预测 ...

  6. opencv算法+人脸检测

    文章目录 ORB算法 视频读写 图像人脸识别 摄像头实时人脸检测 ORB算法 orb算法结合了Fast和Brief算法,提出了构造金字塔,为Fast特征点添加了方向,从而使得关键点具有了尺度不变性和旋 ...

  7. 基于YOLO的密集人脸检测(课程设计)

    基于YOLO的密集人脸检测(课程设计) 数据集+代码下载地址:下载地址 实现的功能 添加关键点检测分支,使用wing loss Installation Clone and install 使用src ...

  8. Matlab人脸检测算法详解

    这是一个Matlab人脸检测算法详解 前言 人脸检测结果 算法详解 源代码解析 所调用函数解析 bwlabel(BW,n) regionprops rectangle 总结 前言 目前主流的人脸检测与 ...

  9. opencv c++ 寻找矩形框_基于Python的OpenCV人脸检测!OpenCV太强了!

    一.文章概述 本文将要讲述的是Python环境下如何用OpenCV检测人脸,本文的主要内容分为: 1.检测图片中的人脸 2.实时检测视频中出现的人脸 3.用运设备的摄像头实时检测人脸 二:准备工作 提 ...

最新文章

  1. [WARNING] unable to add QUERY_STRING=XXXX to uwsgi packet, consider increasing buffer size
  2. 第九课.Python文件操作
  3. 自居电路(升压电路)
  4. BZOJ5415:[NOI2018]归程(可持久化并查集,最短路)
  5. Python安装模块出错(ImportError: No module named setuptools)解决方法
  6. redis的info指令详解
  7. android10分区镜像,分区和映像  |  Android 开源项目  |  Android Open Source Project
  8. Oracle原理: 归档方式和日志文件
  9. 模型与logit_基础方法 | 如何用Logit回归模型写论文?
  10. SQL Server中的Union和Union All语句之间的差异及其性能
  11. Hibernate与数据库分表
  12. C++ union 公共体
  13. FunDA(9)- Stream Source:reactive data streams
  14. shell脚本eval
  15. 数万开发者在追的直播,进大咖群和大佬聊天,你只差这个机会!
  16. js中的数据转换、整数、小数保存、四舍五入
  17. jad反编译成java,Jad java反编译指令
  18. 腾讯云支付平台配置掌优云音响
  19. UICollectionViewCell复用时修改子页面属性出现混乱的解决方法
  20. Win10版本那么多怎么区别(2)

热门文章

  1. Python对文件的操作(转)
  2. RHEL5U8配置Centos yum源
  3. cs-Panination
  4. iptables配置详解
  5. 【转帖】Reporting Service rdl报表,在aspx页面显示一张完整的RDL报表
  6. Sql—表格的建立,删除,数据的建立与删除-总结篇
  7. 第4章 变量、作用域和内存问题
  8. MongoDB的安装与使用
  9. js实现排序去重计算字符次数
  10. 实训三(cocos2dx 3.x 打包apk)