WinForm利用AForge.NET调用电脑摄像头进行拍照和视频
当然了,你需要去官网下载类库,http://www.aforgenet.com/
调用本机摄像头常用的组件:
AForge
AForge.Controls
AForge.Imaging
AForge.Video
AForge.Video.DirectShow
图片展示方面,你可以使用PictureBox,也可以使用类库提供的控件 AForge.Controls.VideoSourcePlayer
因为我这个还集成了 条码识别、电子秤称重,所以代码有点多,多多见谅。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Drawing.Imaging;
using com.google.zxing.client.j2se;
using com.google.zxing;
using System.IO;
using System.Threading;
using Urovo.ExternalIndustryLib;
using System.IO.Ports;
using AForge.Video.DirectShow;
using AForge.Video;
using Inlite.ClearImageNet; namespace SweepCode
{
public partial class FrmMain : Form
{
//关闭标识
private bool IsClose = false;
//识别标识
private bool StartCameraA = false;
//重量读取标识
private bool ElectronicScale = false;
private string OnlyCode = "";
private SerialPort Sp = new SerialPort();
IndustryConfigDAL industryConfigDAL = new IndustryConfigDAL();
private string strTemp = "";
private FilterInfoCollection videoDevices;
private bool ShowIdentification = false;
private VideoCaptureDevice videoSource; public FrmMain()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
} private void Form1_Load(object sender, EventArgs e)
{
FormLoad();
} public void FormLoad()
{
try
{
ShowIdentification = false;
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count == )
throw new ApplicationException();
ComboName.Items.Clear();
foreach (FilterInfo device in videoDevices)
{
ComboName.Items.Add(device.Name);
}
ComboName.SelectedIndex = ;
videoSource = new VideoCaptureDevice(videoDevices[ComboName.SelectedIndex].MonikerString);
for (int i = ; i < videoSource.VideoCapabilities.Length; i++)
{
ComboReso.Items.Add(videoSource.VideoCapabilities[i].FrameSize.Width + "*" + videoSource.VideoCapabilities[i].FrameSize.Height);
}
ComboReso.SelectedIndex = ;
videoSource.VideoResolution = videoSource.VideoCapabilities[ComboReso.SelectedIndex];
videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
videoSource.Start();
//类库提供的控件,也可以显示
//videPlayer.VideoSource = videoSource;
//videPlayer.Start();
ShowIdentification = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
} //选择不同视频
private void ComboName_SelectedIndexChanged(object sender, EventArgs e)
{
if (ShowIdentification == false)
return;
IsClose = true;
Thread.Sleep();
ShowIdentification = false;
videoSource.Stop();
videoSource = null;
//videPlayer.SignalToStop();
//videPlayer.WaitForStop();
ComboReso.Items.Clear();
videoSource = new VideoCaptureDevice(videoDevices[ComboName.SelectedIndex].MonikerString);
for (int i = ; i < videoSource.VideoCapabilities.Length; i++)
{
ComboReso.Items.Add(videoSource.VideoCapabilities[i].FrameSize.Width + "*" + videoSource.VideoCapabilities[i].FrameSize.Height);
}
ComboReso.SelectedIndex = ;
videoSource.VideoResolution = videoSource.VideoCapabilities[ComboReso.SelectedIndex];
videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
videoSource.Start();
IsClose = false;
//videPlayer.VideoSource = videoSource;
//videPlayer.Start();
ShowIdentification = true;
} //选择不同的分辨率
private void ComboReso_SelectedIndexChanged(object sender, EventArgs e)
{
if (ShowIdentification == false)
return;
ShowIdentification = false;
//videPlayer.SignalToStop();
//videPlayer.WaitForStop();
IsClose = true;
Thread.Sleep();
videoSource.Stop();
videoSource = null;
videoSource = new VideoCaptureDevice(videoDevices[ComboName.SelectedIndex].MonikerString);
videoSource.VideoResolution = videoSource.VideoCapabilities[ComboReso.SelectedIndex];
videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
videoSource.Start();
//videPlayer.VideoSource = videoSource;
//videPlayer.Start();
IsClose = false;
ShowIdentification = true;
} //释放
private void CloseVideoSource()
{
if (!(videoSource == null))
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
//加载图片到控件
private delegate void UpdateUI();
private void fun(Bitmap img)
{
if (this.pictureBox1.InvokeRequired)
{
UpdateUI update = delegate { this.pictureBox1.Image = img; };
this.pictureBox1.Invoke(update);
}
else
{
this.pictureBox1.Image = img;
} } //保存图片
private delegate void SaveImage();
private void SaveImageHH(string ImagePath)
{
if (this.pictureBox1.InvokeRequired)
{
SaveImage saveimage = delegate { this.pictureBox1.Image.Save(ImagePath); };
this.pictureBox1.Invoke(saveimage);
}
else
{
this.pictureBox1.Image.Save(ImagePath);
} } string tempImagePath = "";
/// <summary>
/// 拍照-识别-显示
/// </summary>
public void StartCamera()
{
try
{
while (StartCameraA)
{
// label1.Text = "";
List<BarcodeFormat> formats = new List<BarcodeFormat>();
formats.Add(BarcodeFormat.CODE128);
formats.Add(BarcodeFormat.CODE39);
int rNumber = RandomNumber();
string imagePath = System.Environment.CurrentDirectory;
if (!Directory.Exists(@imagePath + "\\Images"))
{
Directory.CreateDirectory(@imagePath + "\\Images");
}
StringBuilder p = new StringBuilder(@imagePath + "\\Images\\" + rNumber + ".jpg");
SaveImageHH(@imagePath + "\\Images\\" + rNumber + ".jpg");
BarcodeReader reader = new BarcodeReader();
reader.Horizontal = true; reader.Vertical = true; reader.Diagonal = true;
reader.Code39 = true;
reader.Code128 = true;
Barcode[] barcodes = reader.Read(@imagePath + "\\Images\\" + rNumber + ".jpg");
string s = ""; int cnt = ;
string CodeValue = ""; if (barcodes.Length > )
{
label1.Text = "Existence Multiple BarCode";
Thread.Sleep();
}
else
{
foreach (Barcode bc in barcodes)
{
cnt++;
CodeValue = bc.Text;
}
if (cnt == )
{//解码不成功,继续抓取图像并解码
// tempImagePath = "";
tempLableValue = "NO BARCODES";
MethodInvoker invoke = new MethodInvoker(SetLableText);
BeginInvoke(invoke); label1.Text = "NO BARCODES";
Thread.Sleep();
}
else
{
//解码成功
if (label1.Text != CodeValue)
{
label1.Text = CodeValue;
tempLableValue = CodeValue;
MethodInvoker invoke = new MethodInvoker(SetLableText);
BeginInvoke(invoke);
string applicationPath = Application.StartupPath;
System.Media.SoundPlayer sndPlayer = new System.Media.SoundPlayer(@applicationPath + "\\WAV\\success.wav");
sndPlayer.Play();
}
Thread.Sleep();
}
}
File.Delete(@imagePath + "\\Images\\" + rNumber + ".jpg");
}
}
catch (Exception ex)
{
Thread.Sleep();
label1.Text = ex.Message;
tempLableValue = ex.Message;
MethodInvoker invoke = new MethodInvoker(SetLableText);
BeginInvoke(invoke);
}
} string tempLableValue;
void SetLableText()
{
label1.Text = tempLableValue;
} void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
if (IsClose)
return;
try
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
fun(bitmap); }
catch (Exception ex)
{
label1.Text = "保存图像失败!";
}
} void videPlayer_NewFrame(object sender, ref Bitmap bitmapimage)
{
try
{
if (tempImagePath != "")
{
bitmapimage.Save(tempImagePath, System.Drawing.Imaging.ImageFormat.Bmp);
}
}
catch (Exception ex)
{
label1.Text = ex.Message;
} } /// <summary>
/// 测试用-记录调用步骤
/// </summary>
/// <param name="Value"></param>
public void ShowMessage(string Value)
{
listBox1.Items.Add(Value);
} public delegate void HandleInterfaceUpdataDelegate(string text); //委托,此为重点
private HandleInterfaceUpdataDelegate interfaceUpdataHandle; //拍照委托
/// <summary>
/// 打开串口
/// </summary>
/// <returns></returns>
public bool OpenElectronicScale()
{
try
{
industryConfigDAL.ReadConfig();
interfaceUpdataHandle = new HandleInterfaceUpdataDelegate(UpdateTextBox);//实例化委托对象
Sp.PortName = industryConfigDAL.Port;
Sp.BaudRate = Convert.ToInt32(industryConfigDAL.BaudRate);
Sp.Parity = Parity.None;
Sp.StopBits = StopBits.One;
// Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
Sp.ReceivedBytesThreshold = ;
Sp.Open();
}
catch (Exception ex)
{
//btnIdentify.Enabled = true;
//btnStopDistinguish.Enabled = false; label4.Text = "端口" + industryConfigDAL.Port + "打开失败!";
//MessageBox.Show("端口" + industryConfigDAL.Port + "打开失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
return true;
} /// <summary>
/// 更新值
/// </summary>
/// <param name="text"></param>
private void UpdateTextBox(string text)
{
char[] arr = text.ToCharArray();
Array.Reverse(arr);
label4.Text = new string(arr);
} /// <summary>
/// 识别
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnIdentify_Click(object sender, EventArgs e)
{
try
{
toolStripDropDownButton1.Enabled = false;
ComboName.Enabled = false;
ComboReso.Enabled = false;
btnIdentify.Enabled = false;
btnStopDistinguish.Enabled = true;
#region
//读取电子秤
if (OpenElectronicScale())
{
ElectronicScale = true;
Thread th = new Thread(Distinguish);
th.IsBackground = true;
th.Start();
} //条码识别
StartCameraA = true;
Thread thread = new Thread(StartCamera);
thread.IsBackground = true;
thread.Start();
#endregion
}
catch
{ }
} /// <summary>
/// 读取电子秤数据
/// </summary>
public void Distinguish()
{
try
{
while (ElectronicScale)
{
Thread.Sleep();
int i = Sp.BytesToRead;
if (i > )
{
try
{
strTemp = Sp.ReadExisting();
}
catch
{
}
if (strTemp.ToLower().IndexOf("=") < )
{
i = ;
}
else
{
string[] sd = strTemp.Split('=');
this.Invoke(interfaceUpdataHandle, sd[]);
}
} }
}
catch
{
ElectronicScale = false;
return;
}
} /// <summary>
/// 生成随机数
/// </summary>
/// <returns></returns>
public int RandomNumber()
{
Random random = new Random();
int num = random.Next(, );
return num;
} /// <summary>
/// 停止
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStopDistinguish_Click(object sender, EventArgs e)
{
toolStripDropDownButton1.Enabled = true;
ComboName.Enabled = true;
ComboReso.Enabled = true;
btnIdentify.Enabled = true;
btnStopDistinguish.Enabled = false;
StartCameraA = false;
ElectronicScale = false;
Thread.Sleep();
Sp.Close(); } /// <summary>
/// 设置电子秤参数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnElectronicScale_Click(object sender, EventArgs e)
{
FrmElectronicScale frmElectronicScale = new FrmElectronicScale();
frmElectronicScale.ShowDialog();
} /// <summary>
/// 关闭窗体
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
IsClose = true;
Thread.Sleep();
ElectronicScale = false;
StartCameraA = false;
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
}
//videoSource.Stop();
videoSource = null;
Thread.Sleep();
Sp.Close();
Thread.Sleep();
this.Dispose();
Thread.Sleep();
Application.Exit();
Thread.Sleep();
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
}
}
出处:https://www.cnblogs.com/qigao/p/6430169.html
==============================================
参考:
==============================================
测试代码文件:AForge.Camera.zip (下载请查看隐藏)
WinForm利用AForge.NET调用电脑摄像头进行拍照和视频的更多相关文章
- 利用AForge.NET 调用电脑摄像头进行拍照
当然了,你需要去官网下载类库,http://www.aforgenet.com/ 调用本机摄像头常用的组件: AForge AForge.Controls AForge.Imaging AForge. ...
- 利用html5调用本地摄像头拍照上传图片[转]
利用html5调用本地摄像头拍照上传图片 html5概念啥的就不废话了,不知道的 百度, 谷歌一堆..今天学了学html5中的Canvas结合新增的<video>标签来获取本地摄像头, ...
- c# 利用AForge和百度AI开发实时人脸识别
baiduAIFaceIdentify项目是C#语言,集成百度AI的SDK利用AForge开发的实时人脸识别的小demo,里边包含了人脸检测识别,人脸注册,人脸登录等功能 人脸实时检测识别功能 思路是 ...
- HTML之调用摄像头实现拍照和摄像功能
应该有很多人知道,我们的手机里面有个功能是“抓拍入侵者”,说白了就是在解锁应用时如果我们输错了密码手机就会调用这一功能实现自动拍照. 其实在手机上还有很多我们常用的软件都有类似于这样的功能,比如微信扫 ...
- 【踩坑速记】MIUI系统BUG,调用系统相机拍照可能会带给你的一系列坑,将拍照适配方案进行到底!
一.写在前面 前几天也是分享了一些学习必备干货(还没关注的,赶紧入坑:传送门),也好久没有与大家探讨技术方案了,心里也是挺痒痒的,这不,一有点闲暇之时,就迫不及待把最近测出来的坑分享给大家. 提起An ...
- C# 利用AForge进行摄像头信息采集
概述 AForge.NET是一个专门为开发者和研究者基于C#框架设计的,提供了不同的类库和关于类库的资源,还有很多应用程序例子,包括计算机视觉与人工智能,图像处理,神经网络,遗传算法,机器学习,机器人 ...
- Android下载图片/调用系统相机拍照、显示并保存到本地
package com.example.testhttpget; import java.io.BufferedReader; import java.io.FileNotFoundException ...
- Android 调用系统照相机拍照和录像
本文实现android系统照相机的调用来拍照 项目的布局相当简单,只有一个Button: <RelativeLayout xmlns:android="http://schemas.a ...
- 手机调用系统的拍照和裁剪功能,假设界面有输入框EditText,在一些手机会出现点击EditText会弹出输入法,却不能输入的情况。
1. 拍照裁剪后 点击EditText会弹出输入法,却不能输入.可是点击点一EdtiText就能够输入了,所以我就写了一个看不见的EdtiText,切换焦点,这样就攻克了这个奇怪的这问题,应该是and ...
随机推荐
- 【C/C++开发】C++11的模板类型判断——std::is_same和std::decay
C++11的模板类型判断--std::is_same和std::decay 问题提出:有一个模板函数,函数在处理int型和double型时需要进行特殊的处理,那么怎么在编译期知道传入的参数的数据类型是 ...
- [转]System Verilog的概念以及与verilog的对比
原文地址: http://blog.csdn.net/gtatcs/article/details/8970489 SystemVerilog语言简介 SystemVerilog是一种硬件描述和验证语 ...
- 以A表中的值快速更新B表中记录的方法
1.问题描述 有两张表,A表记录了某些实体的新属性,B表记录了每个实体的旧属性,现在打算用A中的属性值去更新B中相同实体的旧属性,如下图所示: 类似这样的需求,怎样做比较高效呢? 2.制作模拟数据 ...
- LeetCode 1071. 字符串的最大公因子(Greatest Common Divisor of Strings) 45
1071. 字符串的最大公因子 1071. Greatest Common Divisor of Strings 题目描述 对于字符串 S 和 T,只有在 S = T + ... + T(T 与自身连 ...
- DRF框架(一)——restful接口规范、基于规范下使用原生django接口查询和增加、原生Django CBV请求生命周期源码分析、drf请求生命周期源码分析、请求模块request、渲染模块render
DRF框架 全称:django-rest framework 知识点 1.接口:什么是接口.restful接口规范 2.CBV生命周期源码 - 基于restful规范下的CBV接口 3.请求组件 ...
- vscode 前端常用插件推荐
1. vscode 简介vscode是微软开发的的一款代码编辑器,就如官网上说的一样,vscode重新定义(redefined)了代码编辑器.当前市面上常用的轻型代码编辑器主要是:sublime,n ...
- Vue 公众号开发 (菜鸡前段的血泪史)
首先vue-cli就不说了 接下来要说我们需要注意什么 公众号的每个页面都有一个title 所以我们在开发过程中 需要插件 安装vue-wechat-title 安装vue-js-sdk
- Golang ---testing包
golang自带了testing测试包,使用该包可以进行自动化的单元测试,输出结果验证,并且可以测试性能. 建议安装gotests插件自动生成测试代码: go get -u -v github.com ...
- .net Dapper 实践系列(4) ---数据查询(Layui+Ajax+Dapper+MySQL)
写在前面 上一小节,总结了数据显示时,会出现的日期问题.以及如何处理格式化日期.这个小节,主要总结的是使用Dapper 中的QueryMultiple方法依次显示查询多表的数据. 实践步骤 1.在Bo ...
- 3.使用 Code First 迁移更新数据库
1.更新 SeedData 类,使它提供新列的值. 示例更改如下所示,但可能需要对每个 new Movie 块做出此更改. context.Movie.AddRange( new Movie { Ti ...