您的位置:首页 > 编程语言 > C#

C#简单的Aforge调用摄像头

2015-11-15 09:50 639 查看
突然了解到了Aforge这个类能实现许多人工智能、图像视频处理、神经算法等等功能, 就想接触一下这个类,网络上使用它的程序也挺多, 看了一些相关类的使用之后, 便写了个C#调用摄像头的小程序 



using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using Size = System.Drawing.Size;
using System.Media;
using System.Drawing.Imaging;
using System.Windows.Media.Imaging;
using System.IO;
using System.Windows;
using System.Threading;


首先,需要下载Aforge类, 然后引用它 ,上面是我的using ,Threading线程那个没什么大用,做了个信息提示而已

控件里面添加Aforge.Controls.dll 里面的一个控件VideoSourcePlayer,然后拖拽就行

下面po出代码:

首先声明一个

FilterInfoCollection videoDevices;
//下面是fromload方法体内, 主要是检测本机摄像头,然后添加到combobox里面供选择
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
int i = 0;
foreach (FilterInfo device in videoDevices)
{
toolStripComboBox1.Items.Add(videoDevices[i].Name.ToString());
i++;
}
toolStripStatusLabel2.Text = "关闭   ";
toolStripStatusLabel4.Text = "未选择  ";
toolStripStatusLabel5.Text = "";

下面是连接按键和 关闭按键的方法  ,主要就是实现连接和关闭摄像头 

<span style="white-space:pre">	</span>//连接摄像头

FilterInfo info;
//  info = (FilterInfo)toolStripComboBox1.SelectedItem;
info = videoDevices[toolStripComboBox1.SelectedIndex];
VideoCaptureDevice videoSource = new VideoCaptureDevice(info.MonikerString);
videoSource.DesiredFrameRate = 1;
videoSourcePlayer1.VideoSource = videoSource;
videoSourcePlayer1.Start();
toolStripStatusLabel2.Text = "开启中  ";

//关闭摄像头

videoSourcePlayer1.SignalToStop();
videoSourcePlayer1.WaitForStop();
toolStripStatusLabel2.Text = "关闭   ";


保存按键的方法如下,主要是对目录选择和文件起名,以及对图片的保存:

if (videoSourcePlayer1.IsRunning)
{

string path = DiagtextBox.Text.ToString()+"\\";
BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
videoSourcePlayer1.GetCurrentVideoFrame().GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
PngBitmapEncoder pE = new PngBitmapEncoder();
pE.Frames.Add(BitmapFrame.Create(bitmapSource));
//path.Replace("\\","//");
string picName = path + FileNametextBox.Text.ToString()+ ".jpg";

if (File.Exists(picName))
{
UsingThread("             当前文件夹已有重名文件,保存失败!!!!!!");
//File.Delete(picName);
}

else
{
try {
using (Stream stream = File.Create(picName))
{
pE.Save(stream);
while (File.Exists(picName)==false) ;
UsingThread("              保存图片成功  保存时间:" + DateTime.Now.ToString() + "!");
}
}
catch
{
UsingThread("              图片保存失败 ,请检查路径");
}
}
}
else
{
UsingThread("                    保存失败,请先开启摄像!!!!!!");
}


一些label发生改变的我就不po出来了,把线程那个加上,主要还是改变下面状态栏里面 label  内容做个提示用的:

void UsingThread(string str1)
{
Thread th2 = new Thread(() =>
{

toolStripStatusLabel5.Text =str1;
Thread.Sleep(3000);
toolStripStatusLabel5.Text = "";

});
th2.Start();

}


最后 FromClosed事件要关闭摄像头:

videoSourcePlayer1.SignalToStop();
videoSourcePlayer1.WaitForStop();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  视频 摄像头 简单