当前位置: 首页 > news >正文

C#(Winform)通过添加AForge添加并使用系统摄像机

先展示效果 

AForge介绍

AForge是一个专门为开发者研究者基于C#框架设计的, 也是NET平台下的开源计算机视觉和人工智能库
它提供了许多常用的图像处理视频处理算法、机器学习和神经网络模型,并且具有高效、易用、稳定等特点。

 AForge主要包括:

计算机视觉与人工智能,图像处理,神经网络,遗传算法,机器学习,模糊系统,机器人控制等

  • AForge.Imaging ——日常的图像处理和过滤器
  • AForge.Vision —— 计算机视觉应用类库
  • AForge.Neuro —— 神经网络计算库AForge.Genetic -进化算法编程库
  • AForge. MachineLearning —— 机械学习类库
  • AForge. Robotics —— 提供一些机器学习的工具类库
  • AForge.Video —— 一系列的视频处理类库
  • AForge.Fuzzy —— 模糊推理系统类库
  • AForge.Controls —— 图像, 三维, 图表显示控件

AForge的使用方向 

1. 基于符号识别的3D显示增强技术

2. 基于模糊系统的自动导航

3. 运动检测

4. 2D增强技术

5. 计算机视觉与人工智能

6. 模拟识别

7. 神经网络

8. 图像处理

9. 遗传算法

10. 机器学习

11. 机器人控制等等

 AForge的安装方法

1.右键项目名

2.打开 "管理 NuGet程序包"

3.点击浏览 在浏览上输入 "AForge",并下载

注意:作者一般都是 aforge.net

4.全部下载之后,他会在你的winfrom的左边框会自动显示 

一、下面是我做的一个相机拍摄小项目

 

1.我们先把页面搭好, 上面的字都是lable弄的不是textbox

控件: label  button  comboBox  picture  timer   VideoSourcePlayer

注意:  VideoSourcePlayer 是 我们下载的那个控件里的(AForge.NET)

 2. 拉一个label , 右下角属性  

label 的 属性

  • Auto ==>False     
  • BorderStyle ==> Fixed3D   
  • TextAlign==>MiddleCenter  
  • ForeColor==>Red   
  • BackGround==>Black

3.最上面时间的显示

注意:这里是timer的控件一个点击事件

timer的Enable  属性  修改成  True

 #region 显示实时时间
 private void timer1_Tick(object sender, EventArgs e)
 {
     DateTime dt=DateTime.Now;
     this.txtYear.Text = dt.Year.ToString();
     this.txtMonth.Text = dt.Month.ToString();
     this.txtDay.Text = dt.Day.ToString();
     this.txtTime.Text=dt.ToLongTimeString();
     string week = "";
     switch(dt.DayOfWeek)
     {
         case DayOfWeek.Sunday:
             week = "日";
             break;
         case DayOfWeek.Monday:
             week = "一";
             break;
         case DayOfWeek.Tuesday:
             week = "二";
             break;
         case DayOfWeek.Wednesday:
             week = "三";
             break;
         case DayOfWeek.Thursday:
             week = "四";
             break;
         case DayOfWeek.Friday:
             week = "五";
             break;
         case DayOfWeek.Saturday:
             week = "六";
             break;
         default:
             break;
     }
     this.txtWeek.Text = week;
 }
 #endregion

4.我们要把最基本的 给完善了,把该定义的全部完成,窗体加载我们要提前实例化相机

  private FilterInfoCollection filterInfoCollection;  //摄像头设备集合
  private VideoCaptureDevice videoCapture;//捕捉设备源
  private Bitmap image=null; //设置图片接收的
  int Isopen = 0;  


    private void Form1_Load(object sender, EventArgs e)
  {
      filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
      //MessageBox.Show($"检测到了{filterInfoCollection.Count.ToString()}个摄像头");

      //这下面的for循环是为了检测电脑连接几个相机 ,来吧相机数量写在combobox控件下

      for(int i = 0; i < filterInfoCollection.Count; i++)
      {
          comboBox1.Items.Add($"摄像头{i}");
      }
  }

5.下拉框(ComboBox)索引选择改变

 CloseCamera(); //这个先提前关闭相机, 下面有介绍
 if (comboBox1.SelectedIndex == 0 && filterInfoCollection.Count > 0)
 {
     videoCapture = new VideoCaptureDevice(filterInfoCollection[0].MonikerString);
 }
 else if (comboBox1.SelectedIndex == 1 && filterInfoCollection.Count > 1)
 {
     videoCapture = new VideoCaptureDevice(filterInfoCollection[0].MonikerString);
 }
 else
 {
     MessageBox.Show("摄像头选择有误", "错误提示");
     return;
 }
 videoSourcePlayer1.VideoSource=videoCapture;
 videoSourcePlayer1.Start();

二、简化封装:相机关闭,相机连接(实时显示),保存图片

1.连接相机

  #region 连接相机
  private void ConnCamera()
  {
      if(filterInfoCollection.Count>0)
      { 
          videoCapture = new VideoCaptureDevice(filterInfoCollection[0].MonikerString);
          videoSourcePlayer1.VideoSource= videoCapture;
          videoSourcePlayer1.Start();
      }
  }
  #endregion

2.关闭相机

 #region 关闭相机
 private void CloseCamera()
 {
     if(videoSourcePlayer1.VideoSource!=null)
     {
         videoSourcePlayer1.SignalToStop();
         videoSourcePlayer1.VideoSource.Stop();
         videoSourcePlayer1.VideoSource = null;
     }
 }
 #endregion

3.保存图片

 #region 保存图片
 private void SaveImage()
 {
     var date = DateTime.Now.ToString("yyyy-MM-dd");
     date += "-" + DateTime.Now.TimeOfDay.ToString("hhmmss");
     if(!Directory.Exists("D:\\Saved_Pictures"))
     {
         Directory.CreateDirectory("D:\\Saved_Pictures");
     }
     image.Save(string.Format("D:\\Saved_Pictures\\" + date + ".jpg", date), System.Drawing.Imaging.ImageFormat.Png);
 }
 #endregion

三、实现相机拍照,相机实时显示(打开),图片保存功能,窗体关闭

1.打开相机(实时显示)

 private void takeCamera_Click(object sender, EventArgs e)
 {
     if(((uint)filterInfoCollection.Count)==0)
     {
         MessageBox.Show("检测不到你的摄像头", "错误提示");
     }
     else
     {
         Isopen++;
         if(Isopen%2!=0)
         {
             takeCamera.Text = "关闭摄像头";
             ConnCamera();
         }
         else if(Isopen%2==0)
         {
             takeCamera.Text = "打开摄像头";
             CloseCamera();
         }
     }
 }

2.相机拍照

 private void takephoto_Click(object sender, EventArgs e)
 {
     image=videoSourcePlayer1.GetCurrentVideoFrame();
     pictureBox1.SizeMode=PictureBoxSizeMode.Zoom;
     pictureBox1.Image= image;
 }

3.图片保存

   private void SavePicture_Click(object sender, EventArgs e)
   {
       if(pictureBox1.Image!=null)
       {
           SaveImage();
       }
       else
       {
           MessageBox.Show("请先进行拍照", "相机拍照");
       }
   }

4.窗体关闭

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if(MessageBox.Show("将要关闭窗口,是否继续?", "询问", MessageBoxButtons.YesNo) == DialogResult.Yes)
        {
            e.Cancel=false;
            CloseCamera();
            Application.Exit();
        }
        else
        {
            e.Cancel = true;
        }
    }
}

补充: 窗体的关闭方法;窗体跳转文件夹

1.关闭窗体的多种方法

1. this.Close() ;

只是关闭当前窗口,如果不是主窗体的话,它后台还会再运行,是无法推出主程序的。

2.Application.Exit();

强制所有消息中止,退出所有的窗口,但是有托管线程,也无法干净退出

3.Applicat.ExitThread();

强制中止调用线程上的所有消息,同样面临其他线程无法正确退出问题

4.System.Environment.Exit(0);

这是彻底的强制退出,能把程序结束很干净

2.跳转功能

由于一般程序保存图片后都会有个跳转功能,这个我感觉保存后跳转,他就不是一个功能了,这里给大家写一下怎么去跳转。

 System.Diagnostics.Process.Start("D:\\Saved_Pictures");

注意: 括号里面是路径 

四、完结:代码展示和结果

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using AForge.Video.DirectShow;

namespace Camera
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private FilterInfoCollection filterInfoCollection;  //摄像头设备集合
        private VideoCaptureDevice videoCapture;//捕捉设备源
        private Bitmap image=null;
        int Isopen = 0;

        #region 显示实时时间
        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime dt=DateTime.Now;
            this.txtYear.Text = dt.Year.ToString();
            this.txtMonth.Text = dt.Month.ToString();
            this.txtDay.Text = dt.Day.ToString();
            this.txtTime.Text=dt.ToLongTimeString();
            string week = "";
            switch(dt.DayOfWeek)
            {
                case DayOfWeek.Sunday:
                    week = "日";
                    break;
                case DayOfWeek.Monday:
                    week = "一";
                    break;
                case DayOfWeek.Tuesday:
                    week = "二";
                    break;
                case DayOfWeek.Wednesday:
                    week = "三";
                    break;
                case DayOfWeek.Thursday:
                    week = "四";
                    break;
                case DayOfWeek.Friday:
                    week = "五";
                    break;
                case DayOfWeek.Saturday:
                    week = "六";
                    break;
                default:
                    break;
            }
            this.txtWeek.Text = week;
        }
        #endregion
        private void Form1_Load(object sender, EventArgs e)
        {
            filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            //MessageBox.Show($"检测到了{filterInfoCollection.Count.ToString()}个摄像头");
            for(int i = 0; i < filterInfoCollection.Count; i++)
            {
                comboBox1.Items.Add($"摄像头{i}");
            }

            System.Diagnostics.Process.Start("D:\\Saved_Pictures");
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            CloseCamera();
            if (comboBox1.SelectedIndex == 0 && filterInfoCollection.Count > 0)
            {
                videoCapture = new VideoCaptureDevice(filterInfoCollection[0].MonikerString);
            }
            else if (comboBox1.SelectedIndex == 1 && filterInfoCollection.Count > 1)
            {
                videoCapture = new VideoCaptureDevice(filterInfoCollection[0].MonikerString);
            }
            else
            {
                MessageBox.Show("摄像头选择有误", "错误提示");
                return;
            }
            videoSourcePlayer1.VideoSource=videoCapture;
            videoSourcePlayer1.Start();

        }
        #region 关闭相机
        private void CloseCamera()
        {
            if(videoSourcePlayer1.VideoSource!=null)
            {
                videoSourcePlayer1.SignalToStop();
                videoSourcePlayer1.VideoSource.Stop();
                videoSourcePlayer1.VideoSource = null;
            }
        }
        #endregion

        #region 连接相机
        private void ConnCamera()
        {
            if(filterInfoCollection.Count>0)
            { 
                videoCapture = new VideoCaptureDevice(filterInfoCollection[0].MonikerString);
                videoSourcePlayer1.VideoSource= videoCapture;
                videoSourcePlayer1.Start();
            }
        }
        #endregion

        #region 保存图片
        private void SaveImage()
        {
            var date = DateTime.Now.ToString("yyyy-MM-dd");
            date += "-" + DateTime.Now.TimeOfDay.ToString("hhmmss");
            if(!Directory.Exists("D:\\Saved_Pictures"))
            {
                Directory.CreateDirectory("D:\\Saved_Pictures");
            }
            image.Save(string.Format("D:\\Saved_Pictures\\" + date + ".jpg", date), System.Drawing.Imaging.ImageFormat.Png);
        }
        #endregion

        private void takeCamera_Click(object sender, EventArgs e)
        {
            if(((uint)filterInfoCollection.Count)==0)
            {
                MessageBox.Show("检测不到你的摄像头", "错误提示");
            }
            else
            {
                Isopen++;
                if(Isopen%2!=0)
                {
                    takeCamera.Text = "关闭摄像头";
                    ConnCamera();
                }
                else if(Isopen%2==0)
                {
                    takeCamera.Text = "打开摄像头";
                    CloseCamera();
                }
            }
        }

        private void takephoto_Click(object sender, EventArgs e)
        {
            image=videoSourcePlayer1.GetCurrentVideoFrame();
            pictureBox1.SizeMode=PictureBoxSizeMode.Zoom;
            pictureBox1.Image= image;
        }

        private void SavePicture_Click(object sender, EventArgs e)
        {
            if(pictureBox1.Image!=null)
            {
                SaveImage();
            }
            else
            {
                MessageBox.Show("请先进行拍照", "相机拍照");
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(MessageBox.Show("将要关闭窗口,是否继续?", "询问", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                e.Cancel=false;
                CloseCamera();
                Application.Exit();
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
}

相关文章:

  • Git学习使用笔记
  • JENKINS(全面)
  • 使用API有效率地管理Dynadot域名,清除某一文件夹中域名的默认DNS设置
  • 如何实现华为云+deepseek?
  • webshell通信流量分析
  • 玄机——第一章 应急响应-webshell排查
  • Android笔记【snippet】
  • Selenium WebDriver自动化测试(扩展篇)--Jenkins持续集成
  • 物联网智能语音控制灯光系统设计与实现
  • Feign接口调用-请求响应数据底层实现
  • 深挖vue3基本原理之六 —— 类型系统设计与运行时核心架构
  • 【MyBatis】_使用XML实现MyBatis
  • 【transformers.Trainer填坑】在自定义compute_metrics时logits和labels数据维度不一致问题
  • 通过沙箱技术测试识别潜在的威胁
  • 第一章:认识Tailwind CSS - 第三节 - Tailwind CSS 开发环境搭建和工具链配置
  • redis的哨兵模式和集群模式
  • 1.3 AI大模型应用浪潮解析:高校、硅谷与地缘政治的三角博弈
  • vscode调试和环境路径配置
  • 【微软- Entra ID】Microsoft Entra ID
  • 强化学习《初学者》--基础概念贝尔曼公式
  • 中国中古史集刊高质量发展论坛暨《唐史论丛》创刊四十周年纪念会召开
  • 深入贯彻中央八项规定精神学习教育中央第六指导组指导督导中国工商银行见面会召开
  • 菲护卫艇企图侵闯中国黄岩岛领海,南部战区:依法依规跟踪监视、警告驱离
  • 金融监管总局:做好2025年小微企业金融服务工作
  • 观察|印巴交火开始升级,是否会升级为第四次印巴战争?
  • 李云泽:对受关税影响较大、经营暂时困难的市场主体,一企一策提供精准服务