C# AForge的简单使用
Posted beiger
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# AForge的简单使用相关的知识,希望对你有一定的参考价值。
AForge.NET专为计算机视觉和人工智能应用而设计,这种C#框架适用于图像处理、神经网络、遗传算法、模糊逻辑、机器学习和机器人等。
该库是一个开源项目,包括:
AForge.Imaging —— 一些日常的图像处理和过滤器
AForge.Vision —— 计算机视觉应用类库
AForge.Neuro —— 神经网络计算库AForge.Genetic -进化算法编程库
AForge.MachineLearning —— 机器学习类库
AForge.Robotics —— 提供一些机器人的工具类库
AForge.Video —— 一系列的视频处理类库
AForge.Fuzzy —— 模糊推理系统类库
AForge.Controls—— 图像,三维,图表显示控件
具体见官网:http://www.aforgenet.com/
简单用法如下:
1、安装包:VS→工具→包管理器→输入关键字“AForge”→安装
2、获取本机摄像头、声卡设备列表
List<string> VideoList = GetVideoInDevicesList();
VideolistBox.DataSource = VideoList;
List<string> AudioList = GetAudioInDevicesList();
AudiolistBox.DataSource = AudioList;
/// <summary>
/// 获取摄像头列表
/// </summary>
/// <returns></returns>
public static List<string> GetVideoInDevicesList()
List<string> devicesList = new List<string>();
try
var videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo device in videoDevices)
devicesList.Add(device.Name);
catch (Exception ex)
Console.WriteLine(ex.Message);
return devicesList;
/// <summary>
/// 获取音频设备列表
/// </summary>
/// <returns></returns>
public static List<string> GetAudioInDevicesList()
List<string> devicesList = new List<string>();
try
var videoDevices = new FilterInfoCollection(FilterCategory.AudioInputDevice);//输入设备
foreach (FilterInfo device in videoDevices)
devicesList.Add(device.Name);
catch (ApplicationException)
Console.WriteLine("No local capture devices");
return devicesList;
运行结果:
3、打开摄像头显示内容:
var videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
FilterInfo info = videoDevices[VideolistBox.SelectedIndex];
var videoSource = new VideoCaptureDevice(info.MonikerString);
AForge.Controls.VideoSourcePlayer videoSourcePlayer1 = new AForge.Controls.VideoSourcePlayer();
videoSourcePlayer1.VideoSource = videoSource;
videoSourcePlayer1.Width = 1600;
videoSourcePlayer1.Height = 900;
this.Controls.Add(videoSourcePlayer1);
videoSourcePlayer1.Start();
4、调整分辨率
private void SetResolution()
//分辨率调整至最高
try
var videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
FilterInfo info = videoDevices[VideolistBox.SelectedIndex];
var videoSource = new VideoCaptureDevice(info.MonikerString);
var formats = videoSource.VideoCapabilities;
if (formats.Length > 1)
videoSource.VideoResolution = formats[0];//默认第一个就是最高分辨率
catch
5、调用摄像头参数面板
//摄像头参数设置
private void CamSetup()
var videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
FilterInfo info = videoDevices[VideolistBox.SelectedIndex];
VideoCaptureDevice videoCaptureDevice = new VideoCaptureDevice(info.MonikerString);
try
videoCaptureDevice.DisplayPropertyPage(this.Handle);
catch
MessageBox.Show("所选视频设备不支持设置页面","出错",MessageBoxButtons.OK,MessageBoxIcon.Error,MessageBoxDefaultButton.Button1);
6、画面的放大、平移
方法:
详见:http://www.aforgenet.com/framework/docs/html/077a7afb-c9bd-91b6-6870-61440e2f4060.htm
public bool SetCameraProperty( CameraControlProperty property, int value, CameraControlFlags controlFlags )
其中:property
Pan | 水平移动(放大后)-16 至 +16 |
Tilt | 垂直移动(放大后)-16 至 +16 |
Roll | 旋转 0 至 3 |
Zoom | 缩放 100 至 400 |
Exposure | 曝光 -12 至 -3 |
Iris | 红外灯 |
Focus | 聚焦 |
value:Int32数字
controlFlags:
None(No control flag.)
Auto (自动)
Manual (手工)
实例:
var videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
FilterInfo info = videoDevices[VideolistBox.SelectedIndex];
VideoCaptureDevice videoCaptureDevice = new VideoCaptureDevice(info.MonikerString);
try
videoCaptureDevice.SetCameraProperty(CameraControlProperty.Zoom, 400, CameraControlFlags.Manual);
catch
MessageBox.Show("所选视频设备不支持","出错",MessageBoxButtons.OK,MessageBoxIcon.Error,MessageBoxDefaultButton.Button1);
参考:
C#调用摄像头(AForge)实现扫描条码解析(Zxing)功能
网上找了很多代码,都比较零散,下面是我测试过的,可以直接使用。DLL及源码可以通过链接下载。
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 AForge; using AForge.Controls; using AForge.Imaging; using AForge.Video; using AForge.Video.DirectShow; using System.Drawing.Imaging; using ZXing; using ZXing.Common; using ZXing.QrCode; using ZXing.QrCode.Internal; /// <summary> /// 20190515 by hanfre /// 关于原理: /// C#调用摄像头+存储图片+Zxing/Zbar图片识别.当开启摄像头的时候利用Timer对当前图片进行解析处理,识别条码; /// 关于条码解析: /// 这个DEMO含两个条码解析组件,分别是Zxing和Zbar,使用哪个可以自己切换; /// 关于作者: /// Hanfre /// </summary> namespace WindowsFormsApplication1 { /// <summary> /// 20190515 by hanfre /// </summary> public partial class Form1 : Form { #region 全局变量定义 FilterInfoCollection videoDevices; VideoCaptureDevice videoSource; public int selectedDeviceIndex = 0; #endregion public Form1() { InitializeComponent(); InitializeView(); } #region 事件 /// <summary> /// 启动 /// 20190515 by hanfre /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnStart_Click(object sender, EventArgs e) { PbxScanner.Image = null; videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); selectedDeviceIndex = 0; videoSource = new VideoCaptureDevice(videoDevices[selectedDeviceIndex].MonikerString);//连接摄像头 videoSource.NewFrame += new NewFrameEventHandler(VspContainerClone);//捕获画面事件 videoSource.VideoResolution = videoSource.VideoCapabilities[selectedDeviceIndex]; VspContainer.VideoSource = videoSource; VspContainer.Start(); StartVideoSource(); } /// <summary> /// 停止 /// 20190515 by hanfre /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnStop_Click(object sender, EventArgs e) { CloseVideoSource(); } /// <summary> /// 保存 /// 20190515 by hanfre /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnScanner_Click(object sender, EventArgs e) { if (videoSource == null) return; Bitmap bitmap = VspContainer.GetCurrentVideoFrame(); string fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ff") + ".jpg"; bitmap.Save(Application.StartupPath + "\\" + fileName, ImageFormat.Jpeg); bitmap.Dispose(); } /// <summary> /// 同步事件 /// 20190515 by hanfre /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> private void VspContainerClone(object sender, NewFrameEventArgs eventArgs) { PbxScanner.Image = (Bitmap)eventArgs.Frame.Clone(); } /// <summary> /// Timer定时器 /// 20190515 by hanfre /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TmScanner_Tick(object sender, EventArgs e) { if (PbxScanner.Image != null) { TmScanner.Enabled = false; Bitmap img = (Bitmap)PbxScanner.Image.Clone(); if (DecodeByZxing(img)) ///if (DecodeByZbar(img)) { CloseVideoSource(); } else { TmScanner.Enabled = true; } } } #endregion #region 方法 /// <summary> /// 初始化 /// 20190515 by hanfre /// </summary> private void InitializeView() { BtnScanner.Enabled = false; BtnStop.Enabled = false; } /// <summary> /// 启动 /// 20190515 by hanfre /// </summary> private void StartVideoSource() { TmScanner.Enabled = true; BtnStart.Enabled = false; BtnStop.Enabled = true; BtnScanner.Enabled = true; } /// <summary> /// 关闭 /// 20190515 by hanfre /// </summary> private void CloseVideoSource() { if (!(videoSource == null)) { if (videoSource.IsRunning) { videoSource.SignalToStop(); videoSource = null; } } VspContainer.SignalToStop(); //videoSourcePlayer1.Stop(); //videoSourcePlayer1.Dispose(); TmScanner.Enabled = false; BtnScanner.Enabled = false; BtnStart.Enabled = true; BtnStop.Enabled = false; } #endregion #region 方法/Zxing&Zbar /// <summary> /// 解码 /// 20190515 by hanfre /// </summary> /// <param name="b"></param> /// <returns></returns> private bool DecodeByZxing(Bitmap b) { try { BarcodeReader reader = new BarcodeReader(); reader.AutoRotate = true; Result result = reader.Decode(b); TxtScannerCode.Text = result.Text; } catch (Exception e) { System.Console.WriteLine(e.Message); TxtScannerCode.Text = ""; return false; } return true; } private bool DecodeByZbar(Bitmap b) { DateTime now = DateTime.Now; Bitmap pImg = ZbarMakeGrayscale3(b); using (ZBar.ImageScanner scanner = new ZBar.ImageScanner()) { scanner.SetConfiguration(ZBar.SymbolType.None, ZBar.Config.Enable, 0); scanner.SetConfiguration(ZBar.SymbolType.CODE39, ZBar.Config.Enable, 1); scanner.SetConfiguration(ZBar.SymbolType.CODE128, ZBar.Config.Enable, 1); List<ZBar.Symbol> symbols = new List<ZBar.Symbol>(); symbols = scanner.Scan((System.Drawing.Image)pImg); if (symbols != null && symbols.Count > 0) { string result = string.Empty; symbols.ForEach(s => result += "条码内容:" + s.Data + " 条码质量:" + s.Quality + Environment.NewLine); MessageBox.Show(result); return true; } else { return false; } } } /// <summary> /// 处理图片灰度 /// </summary> /// <param name="original"></param> /// <returns></returns> public static Bitmap ZbarMakeGrayscale3(Bitmap original) { //create a blank bitmap the same size as original Bitmap newBitmap = new Bitmap(original.Width, original.Height); //get a graphics object from the new image Graphics g = Graphics.FromImage(newBitmap); //create the grayscale ColorMatrix System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix( new float[][] { new float[] {.3f, .3f, .3f, 0, 0}, new float[] {.59f, .59f, .59f, 0, 0}, new float[] {.11f, .11f, .11f, 0, 0}, new float[] {0, 0, 0, 1, 0}, new float[] {0, 0, 0, 0, 1} }); //create some image attributes ImageAttributes attributes = new ImageAttributes(); //set the color matrix attribute attributes.SetColorMatrix(colorMatrix); //draw the original image on the new image //using the grayscale color matrix g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); //dispose the Graphics object g.Dispose(); return newBitmap; } #endregion } }
以上是关于C# AForge的简单使用的主要内容,如果未能解决你的问题,请参考以下文章
c#屏幕录制(经典)(含源码和AForge.Video.FFMPEG.DLL)及填坑办法