前言:
C#调用摄像头是为了完成一个项目( 工厂物资管理系统. )中的人脸识别功能。
对人脸识别感兴趣的小伙伴可以移步至:https://blog.csdn.net/qq_41971768/article/details/103823308
在 C # 调用摄像头的实现过程中,我曾在博客上借鉴其他人的做法。在这里给出相应的博客地址如下:
- C#打开摄像头抓取照片然后退出 : 该作者转载的其他人的方法,帮助不大
- .net中捕获摄像头视频的方式及对比 : 该作者介绍了几种不同的实现方式,并对其作了对比。
- C#通过引用AForge获取摄像头数据 : 该作者提供了AForge的下载和如何加入到VS中,但未给出代码实现。
- Aforge.net类库调用摄像头拍照(C#) : 该作者提供了AForge的下载以及加载,并附有代码。
本文也是借鉴于第四篇博客。
正文:
1. 下载 AForge 库
进入AForge官网:http://www.aforgenet.com/framework/downloads.html下载AForge库:
2. 通过VS添加引用
AForge.Imaging ——图像处理和过滤器
AForge.Video ——视频处理类库
AForge.Controls—— 图像显示控件
进入引用管理器如下图:
点击浏览:找到AForge.NET Framework-2.2.5-(libs only)\Release该目录,添加以下文件【“AForge.Video.dll” “AForge.Controls.dll” “AForge.dll” “AForge.Imaging.dll” “AForge.Video.DirectShow.dll” 】:
添加结果如下:
3. 工具箱添加AForge的组件
- 打开工具箱>>右键>>添加选项卡>>输入名称AForge
- 选中AForge>>右键>>选择项>>浏览进入AForge.NET Framework-2.2.5-(libs only)\Release目录>>选中 “AForge.Controls.dll”>>打开确认
4. 添加组件
创建窗体>>添加图中组件;
其中的videoSorcePlayer位于刚添加的工具集AForge中。
以下为我的设计效果
5. 代码:
可以同时参考前言中第四位作者的代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//using System.Drawing;
using AForge.Video.DirectShow;
using 工厂物资管理.Face;
using Newtonsoft.Json;
using System.Data.SqlClient;
namespace 工厂物资管理
{
public partial class FaceLoginForm : Form
{
private FilterInfoCollection videoDevices = null;
private VideoCaptureDevice videoSource = null;
private string EmployeeID = null;
private int Indexof = 0;
private SqlConnection sqlConnection = null;
private SqlCommand sqlCommand = null;
public FaceLoginForm()
{
InitializeComponent();
//连接数据库部分
this.sqlConnection = new SqlConnection(DB.DBConnStr.ConnStr);
this.sqlCommand = new SqlCommand();
this.sqlCommand.Connection = this.sqlConnection;
}
//检索摄像头事件
private void Checkcam_Click(object sender, EventArgs e)
{
Camlist(); //调用相应方法
}
//检索摄像头
private void Camlist()
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
Cameralist.Items.Clear(); //清楚之前检索的内容
if (videoDevices.Count == 0)
{
MessageBox.Show("未找到摄像头设备");
}
else
{
foreach (FilterInfo device in videoDevices)
{
Cameralist.Items.Add(device.Name);
}
if (Cameralist.Items.Count >= 1)
{
Cameralist.SelectedIndex = 0; //设置一个默认选项
}
}
}
//打开摄像头按钮
private void Select_button_Click(object sender, EventArgs e)
{
Indexof = Cameralist.SelectedIndex;
if (Indexof < 0)
{
MessageBox.Show("请选择一个摄像头");
return;
}
//添加try抛出异常,防止程序中断
try
{
//在1个或以上摄像头进行切换时执行
videoSourcePlayer1.SignalToStop();
videoSourcePlayer1.WaitForStop();
this.pictureBox1.Visible = false;
this.videoSourcePlayer1.Visible = true;
//videoDevices[Indexof]确定出用哪个摄像头了。
videoSource = new VideoCaptureDevice(videoDevices[Indexof].MonikerString);
//设置下像素,这句话不写也可以正常运行:
//videoSource.VideoResolution = videoSource.VideoCapabilities[Indexof];
//在videoSourcePlayer1里显示
videoSourcePlayer1.VideoSource = videoSource;
videoSourcePlayer1.Start();
}
catch (Exception ex)
{
MessageBox.Show("请选择一个有效的摄像头");
}
}
//抓拍登录按钮
private void TiJiao_button_Click(object sender, EventArgs e)
{
if (videoSource == null)
{
MessageBox.Show("请先打开摄像头");
return;
}
//videoSourcePlayer继承Control父类,定义 GetCurrentVideoFrame能输出bitmap
Bitmap bitmap = videoSourcePlayer1.GetCurrentVideoFrame();
//此处就得到了Bitmap格式的图像数据
pictureBox1.Image = bitmap; //将图像加载到pictureBox组件
this.videoSourcePlayer1.Visible = false;
this.pictureBox1.Visible = true;
//这里停止摄像头继续工作 当然videoSourcePlayer里也定义了 Stop();用哪个都行
// string imagestr = this.pictureBox1.Image.ToString();
//
bitmap = videoSourcePlayer1.GetCurrentVideoFrame();
String imagestr=Util.ImgToBase64String(bitmap);
// MessageBox.Show("01",imagestr.Substring(1,10));
videoSourcePlayer1.Stop();
//#############################
//至此图像抓取工作结束,下面内容是人脸识别的相关内容。
//############################
checkFace(imagestr);
if (this.EmployeeID != null)
{
login();
}
// videoSourcePlayer1.SignalToStop(); videoSourcePlayer1.WaitForStop();
//原文链接:https://blog.csdn.net/u013667895/article/details/78426649
}
private void login()
{
try
{
if (sqlConnection.State != ConnectionState.Open)
{
sqlConnection.Open();
}
string sql = string.Format("select EmployeeID,EmployeePwd,EmployeeName,Employee.EmployeeTitle " +
"from Employee " +
"where Employee.EmployeeID = '{0}'", this.EmployeeID);
sqlCommand.CommandText = sql;
SqlDataReader sdr = sqlCommand.ExecuteReader();
if (sdr.HasRows)
{
//有返回行
sdr.Read();
if (sdr[0].ToString() == this.EmployeeID)
{//输入用户名和密码等于查询结果中用户名和密码
MainForm mform = new MainForm(sdr[3].ToString(), sdr[0].ToString(), sdr[2].ToString());
sdr.Close();
this.Hide();
mform.ShowDialog();
this.Close();
//this.Show();
}
else
{
sdr.Close();
MessageBox.Show("登陆失败,请重新尝试!", "SQL注入攻击无效,提示信息");
}
}
else
{
//无返回行
MessageBox.Show("登陆失败,请重新尝试!", "提示信息");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "数据库操作问题提示");
//throw;
}
finally
{
sqlConnection.Close();
}
}
private void checkFace(string image)
{
//识别
SearchResult searchResult = FaceSearch.faceSearch(image);
if (searchResult.error_msg.Equals("SUCCESS"))
{
string score=searchResult.result.user_list[0].score;
// MessageBox.Show(score);
if (Double.Parse(score)>85.0)
{
this.EmployeeID = searchResult.result.user_list[0].user_id;
MessageBox.Show("验证成功");
}
else
{
MessageBox.Show("未成功,请确认已采集人脸后再试!","验证失败");
}
}
else
{
MessageBox.Show("未成功,请确认已采集人脸后再试!", "验证失败");
}
}
private void FaceLoginForm_Load(object sender, EventArgs e)
{
// String str=AuthService.getAccessToken();
// Token token = JsonConvert.DeserializeObject<Token>(str);
// MessageBox.Show(token.access_token);
}
private void FaceLoginForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (videoSource != null)
{
videoSourcePlayer1.Stop();
}
}
}
}
6. 效果展示
谢谢浏览,希望能够帮到大家。
欢迎大家留言,提出问题和意见。
作者:卢松林
许昌学院计算机科学与技术专业