wpf 人脸识别 mvvm
1.人脸识别 M
public class ListBoxImage : NotificationObject
{
private BitmapImage imageSoure;
/// <summary>
/// 图片文件源
/// </summary>
public BitmapImage ImageSoure
{
get { return imageSoure; }
set
{
if (imageSoure != value)
{
imageSoure = value;
this.RaisePropertyChanged("ImageSoure");
}
}
}
private string fullPath;
/// <summary>
/// 文件全路径
/// </summary>
public string FullPath
{
get { return fullPath; }
set
{
if (fullPath != value)
{
fullPath = value;
this.RaisePropertyChanged("FullPath");
}
}
}
private Visibility deleteButtonVisibility;
/// <summary>
/// 是否显示删除按钮
/// </summary>
public Visibility DeleteButtonVisibility
{
get { return deleteButtonVisibility; }
set
{
if (deleteButtonVisibility != value)
{
deleteButtonVisibility = value;
this.RaisePropertyChanged("DeleteButtonVisibility");
}
}
}
private string deleteImageButtonTag;
/// <summary>
/// 删除图片按钮的标记,用来删除对应图片
/// </summary>
public string DeleteImageButtonTag
{
get { return deleteImageButtonTag; }
set
{
if (deleteImageButtonTag != value)
{
deleteImageButtonTag = value;
this.RaisePropertyChanged("DeleteImageButtonTag");
}
}
}
}
2. 人脸识别V
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="WindowsDictionary.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OpenCameraButtonClickCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<Border>
<wfi:WindowsFormsHost x:Name="LgnFaceRecVideoForm" Margin="0 0" >
<aforge:VideoSourcePlayer x:Name="LgnFaceRecVideoPlayer" BorderColor="Transparent"/>
</wfi:WindowsFormsHost>
</Border>
</Grid>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Button x:Name="WinClose" Style="{StaticResource btn_close}" />
</Grid>
<StackPanel Grid.Row="1" Orientation="Vertical">
<ListBox x:Name="lstImgs" Grid.IsSharedSizeScope="True" ItemsSource="{Binding ImageListBoxSource}" Margin="5,5,5,5" ItemTemplate="{StaticResource ListBoxItemTemplate}" SnapsToDevicePixels="True" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate >
<VirtualizingStackPanel Orientation="Horizontal" IsItemsHost="True">
</VirtualizingStackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</StackPanel>
<Grid Grid.Row="2">
<Button Style="{StaticResource DefaultButton}" FontSize="18" Content=" 添加图片 " HorizontalAlignment="Center">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding AddImageCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>
</Grid>
</Grid>
3. 人脸识别VM
public class MainWindowsViewModel : NotificationObject
{
VideoSourcePlayer _lgnFaceRecVideoPlayer;
public Window View { set; get; }
#region 构造函数
public MainWindowsViewModel(MainWindow win)
{
View = win;
_lgnFaceRecVideoPlayer = win.LgnFaceRecVideoPlayer;
CtlVpService.RunService();//启动视频控制服务
}
#endregion
#region 配置文件
private static string ConUserDefinedImageFolderName = ConfigurationManager.AppSettings["UserDefinedImageFolderName"].ToString();
#endregion
private DelegateCommand<object> openCameraButtonClickCommand;
/// <summary>
/// 开启视频按钮
/// </summary>
public DelegateCommand<object> OpenCameraButtonClickCommand
{
get
{
if (openCameraButtonClickCommand == null)
{
openCameraButtonClickCommand = new DelegateCommand<object>((obj) =>
{
try
{
CtlVpService.ChangePlayer(_lgnFaceRecVideoPlayer);
_lgnFaceRecVideoPlayer.Start();
//加载背景图数据
RefreshBgSegmentImages();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Failed to open camera.");
LogModel.WriteLog(ex.ToString());
}
});
}
return openCameraButtonClickCommand;
}
set { openCameraButtonClickCommand = value; }
}
private List<ListBoxImage> _imageListBoxSource;
/// <summary>
/// 所有背景图片数据源
/// </summary>
public List<ListBoxImage> ImageListBoxSource
{
set
{
if (_imageListBoxSource != value)
{
_imageListBoxSource = value;
this.RaisePropertyChanged("ImageListBoxSource");
}
}
get
{
return _imageListBoxSource;
}
}
private DelegateCommand<object> deleteImageCommand;
/// <summary>
/// 删除图片按钮
/// </summary>
public DelegateCommand<object> DeleteImageCommand
{
get
{
if (deleteImageCommand == null)
{
deleteImageCommand = new DelegateCommand<object>((obj) =>
{
try
{
ListBoxImage listBoxImage = obj as ListBoxImage;
List<ListBoxImage> newList = new List<ListBoxImage>();
foreach (ListBoxImage bfs in ImageListBoxSource)
{
if (bfs != listBoxImage)
{
newList.Add(bfs);
}
}
if (ImageListBoxSource != null)
{
ImageListBoxSource.Clear();
}
ImageListBoxSource = newList;
Thread c_thread = new Thread(DeleteImage);
c_thread.IsBackground = true;
c_thread.Start(listBoxImage.FullPath);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Restore default failed!");
LogModel.WriteLog(ex.ToString());
}
});
}
return deleteImageCommand;
}
set { deleteImageCommand = value; }
}
private DelegateCommand<object> addImageCommand;
/// <summary>
/// 添加/切换要遮挡的背景图
/// </summary>
public DelegateCommand<object> AddImageCommand
{
get
{
if (addImageCommand == null)
{
addImageCommand = new DelegateCommand<object>((obj) =>
{
try
{
//添加
//if (bgSegmentImage.DeleteImageButtonTag.Equals(ConDefaulAddImageName))
if (obj == null)
{
OpenFileDialog dialog = new OpenFileDialog();
// DirectoryInfo dirDomainFolder = new DirectoryInfo(InitialDirectory);
dialog.InitialDirectory = @"C:\\Users/Pactera/Pictures";
dialog.Title = "请选择图片";
dialog.Filter = "图片|*.jpg;*.png;*.gif;*.jpeg;*.bmp";
DialogResult D = dialog.ShowDialog();
if (D == DialogResult.OK)
{
string m_fileName = dialog.FileName.Trim();
string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
string pSaveFilePath = path + ConUserDefinedImageFolderName + "/";//指定存储的路径
string needCopyImageFileName = dialog.SafeFileName;
string needCopyImageFilePath = string.Empty;
BitmapImage tempBitmap = GetImageByFilePath(dialog.FileName.Trim()); ;
bool isExistsSameImage = false;
needCopyImageFilePath = pSaveFilePath + needCopyImageFileName;
if (File.Exists(needCopyImageFilePath))
{
isExistsSameImage = true;
}
if (ImageListBoxSource != null)
{
//找到相同文件
foreach (ListBoxImage item in ImageListBoxSource)
{
string targetImageString = GetImageBase64String(item.FullPath);
string sourceImageString = GetImageBase64String(dialog.FileName.Trim());
if (targetImageString.Equals(sourceImageString))
{
isExistsSameImage = true;
needCopyImageFilePath = item.FullPath;
}
}
}
if (isExistsSameImage)
{
if (System.Windows.MessageBox.Show("The same picture file already exists. Do you want to replace it?", "Warning⚠", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
{
if (File.Exists(dialog.FileName.Trim()))//必须判断要复制的文件是否存在
{
File.Copy(dialog.FileName.Trim(), needCopyImageFilePath, true);//三个参数分别是源文件路径,存储路径,若存储路径有相同文件是否替换
}
RefreshBgSegmentImages();
}
}
else
{
File.Copy(dialog.FileName.Trim(), needCopyImageFilePath, true);//三个参数分别是源文件路径,存储路径,若存储路径有相同文件是否替换
RefreshBgSegmentImages();
}
}
}
//切换背景图
else
{
ListBoxImage bgSegmentImage = obj as ListBoxImage;
string ImageFilePath = bgSegmentImage.FullPath;
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Page loading failed.");
LogModel.WriteLog(ex.ToString());
}
});
}
return addImageCommand;
}
set { addImageCommand = value; }
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="o"></param>
void DeleteImage(object o)
{
try
{
Thread.Sleep(100);
string fullPath = o.ToString();
if (File.Exists(fullPath))
{
File.Delete(fullPath);
}
}
catch (Exception ex)
{
}
}
/// <summary>
/// 读取图片
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private BitmapImage GetImageByFilePath(string path)
{
// 读取图片源文件到byte[]中
BinaryReader binReader = new BinaryReader(File.Open(path, FileMode.Open));
FileInfo fileInfo = new FileInfo(path);
byte[] bytes = binReader.ReadBytes((int)fileInfo.Length);
binReader.Close();
// 将图片字节赋值给BitmapImage
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = new MemoryStream(bytes);
bitmap.EndInit();
// 最后给Image控件赋值
return bitmap;
}
/// <summary>
/// 刷新listbox 数据源
/// </summary>
private void RefreshBgSegmentImages()
{
List<ListBoxImage> imageSource = new List<ListBoxImage>();
string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
path += ConUserDefinedImageFolderName;
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles("*.*", SearchOption.AllDirectories);
if (files != null && files.Length > 0)
{
foreach (var file in files)
{
if (file.Extension == (".jpg") || file.Extension == (".JPG") || file.Extension == (".png") || file.Extension == (".PNG") || file.Extension == (".jpeg") || file.Extension == (".JPEG") || file.Extension == (".bmp") || file.Extension == (".BMP") || file.Extension == (".gif") || file.Extension == (".GIF"))
{
ListBoxImage tempobj = new ListBoxImage();
tempobj.DeleteButtonVisibility = Visibility.Visible;
tempobj.DeleteImageButtonTag = file.Name;
tempobj.FullPath = file.FullName;
tempobj.ImageSoure = GetImageByFilePath(file.FullName);
imageSource.Add(tempobj);
}
}
}
//赋值
ImageListBoxSource = null;
ImageListBoxSource = imageSource;
}
/// <summary>
/// 获取图片的ase64 数字编码
/// </summary>
/// <param name="imagePath">图片地址</param>
/// <returns></returns>
private string GetImageBase64String(string imagePath)
{
string imageString = string.Empty;
using (MemoryStream memoryStream = new MemoryStream())
{
using (Image image = Image.FromFile(imagePath))
{
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
imageString = Convert.ToBase64String(memoryStream.ToArray());
}
}
return imageString;
}
}