利用AForge.NET 调用电脑摄像头进行拍照

当然了,你需要去官网下载类库,http://www.aforgenet.com/

调用本机摄像头常用的组件:

AForge

AForge.Controls

AForge.Imaging

AForge.Video

AForge.Video.DirectShow

图片展示方面,你可以使用PictureBox,也可以使用类库提供的控件videPlayer。

因为我这个还集成了 条码识别、电子秤称重,所以代码有点多,多多见谅。

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 == 0)
                    throw new ApplicationException();
                ComboName.Items.Clear();
                foreach (FilterInfo device in videoDevices)
                {
                    ComboName.Items.Add(device.Name);
                }
                ComboName.SelectedIndex = 0;
                videoSource = new VideoCaptureDevice(videoDevices[ComboName.SelectedIndex].MonikerString);
                for (int i = 0; i < videoSource.VideoCapabilities.Length; i++)
                {
                    ComboReso.Items.Add(videoSource.VideoCapabilities[i].FrameSize.Width + "*" + videoSource.VideoCapabilities[i].FrameSize.Height);
                }
                ComboReso.SelectedIndex = 0;
                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(100);
            ShowIdentification = false;
            videoSource.Stop();
            videoSource = null;
            //videPlayer.SignalToStop();
            //videPlayer.WaitForStop();
            ComboReso.Items.Clear();
            videoSource = new VideoCaptureDevice(videoDevices[ComboName.SelectedIndex].MonikerString);
            for (int i = 0; i < videoSource.VideoCapabilities.Length; i++)
            {
                ComboReso.Items.Add(videoSource.VideoCapabilities[i].FrameSize.Width + "*" + videoSource.VideoCapabilities[i].FrameSize.Height);
            }
            ComboReso.SelectedIndex = 0;
            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(100);
            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 = 0;
                    string CodeValue = "";

                    if (barcodes.Length > 1)
                    {
                        label1.Text = "Existence Multiple BarCode";
                        Thread.Sleep(100);
                    }
                    else
                    {
                        foreach (Barcode bc in barcodes)
                        {
                            cnt++;
                            CodeValue = bc.Text;
                        }
                        if (cnt == 0)
                        {//解码不成功,继续抓取图像并解码
                            // tempImagePath = "";
                            tempLableValue = "NO BARCODES";
                            MethodInvoker invoke = new MethodInvoker(SetLableText);
                            BeginInvoke(invoke);

                            label1.Text = "NO BARCODES";
                            Thread.Sleep(100);
                        }
                        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(100);
                        }
                    }
                    File.Delete(@imagePath + "\\Images\\" + rNumber + ".jpg");
                }
            }
            catch (Exception ex)
            {
                Thread.Sleep(100);
                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 = 1;
                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(50);
                    int i = Sp.BytesToRead;
                    if (i > 0)
                    {
                        try
                        {
                            strTemp = Sp.ReadExisting();
                        }
                        catch
                        {
                        }
                        if (strTemp.ToLower().IndexOf("=") < 0)
                        {
                            i = 0;
                        }
                        else
                        {
                            string[] sd = strTemp.Split(‘=‘);
                            this.Invoke(interfaceUpdataHandle, sd[1]);
                        }
                    }

                }
            }
            catch
            {
                ElectronicScale = false;
                return;
            }
        }

        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <returns></returns>
        public int RandomNumber()
        {
            Random random = new Random();
            int num = random.Next(100000, 1000000);
            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(1000);
            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(100);
            ElectronicScale = false;
            StartCameraA = false;
            if (videoSource.IsRunning)
            {
                videoSource.SignalToStop();
            }
            //videoSource.Stop();
            videoSource = null;
            Thread.Sleep(1000);
            Sp.Close();
            Thread.Sleep(1000);
            this.Dispose();
            Thread.Sleep(1000);
            Application.Exit();
            Thread.Sleep(1000);
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }
     }
}
时间: 2024-12-23 18:06:59

利用AForge.NET 调用电脑摄像头进行拍照的相关文章

利用html5调用本地摄像头拍照上传图片[转]

利用html5调用本地摄像头拍照上传图片 html5概念啥的就不废话了,不知道的 百度, 谷歌一堆..今天学了学html5中的Canvas结合新增的<video>标签来获取本地摄像头,在html5之前,要在浏览器获取本地摄像头只有通过插件(ActiveX,但是这种只有IE支持)或者是flash来获取(或许你没学过flash那就很坑爹了),在之后微软的silvertlight中也可以获取,但这些都比较麻烦,在html5的世界里,要获取本地摄像头,只要配合js就可以轻松获取.. 目前支持html5

c# 利用AForge和百度AI开发实时人脸识别

baiduAIFaceIdentify项目是C#语言,集成百度AI的SDK利用AForge开发的实时人脸识别的小demo,里边包含了人脸检测识别,人脸注册,人脸登录等功能 人脸实时检测识别功能 思路是利用AForge打开摄像头,通过摄像头获取到的图像显示在winform窗体中AForge的控件中,利用AForge控件中的NewFrame事件获取要显示的每一帧的图像,获取图像传输到百度AI平台进行人脸检测,并且将检测结果反馈到界面显示的图像中.在这个过程中有两个问题,获取图像上传到百度AI平台进行

Android6.0机型上调用系统相机拍照返回的resultCode值始终等于0的问题

版权声明:本文为博主原创文章,未经博主允许不得转载. 正常情况下调用系统相机拍照: 如果拍照后点击的是“确定”图标,返回的resultCode = -1(Activity.RESULT_OK): 如果点击的是底部的“返回”键,返回的resultCode = 0(Activity.RESULT_CANCELED). 简单的调用系统相机的写法: //调用系统拍照 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); String p

Android 调用系统相机拍照保存以及调用系统相册的方法

系统已经有的东西,如果我们没有新的需求的话,直接调用是最直接的.下面讲讲调用系统相机拍照并保存图片和如何调用系统相册的方法. 首先看看调用系统相机的核心方法: Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(camera, CAMERA); 相机返回的数据通过下面的回调方法取得,并处理: public static final int CAMERA  = 0x01; @Over

手机调用系统的拍照和裁剪功能,如果界面有输入框EditText,在一些手机会出现点击EditText会弹出输入法,却不能输入的情况。

code如下: //Longest common sequence, dynamic programming method void FindLCS(char *str1, char *str2) { if(str1 == NULL || str2 == NULL) return; int length1 = strlen(str1)+1; int length2 = strlen(str2)+1; int **csLength,**direction;//two arrays to recor

调用 android 系统拍照结合 android-crop 裁剪图片

在一个应用中更换用户的头像,一般有拍照和从图库中选择照片两种方法,现在网上也有很多开源的,但是很多都太复杂.而 Android-crop 这个库比较小,代码不复杂,比较适合,但是它没有拍照这个功能,需要我们自己整合进去. 调用系统相机拍照 返回略缩图的拍照 // 调用系统的拍照 private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTU

html5调用摄像头实现拍照

技术时刻都在前进着.我们的需求也是时刻在改变着.最近在开发中遇到了用户进行账号注册时需要个人图像,网站提供自动拍照功能.还有在登录了PC之后,手机端进行登录时只需要扫描一下PC上的二维码就可以登录.这对一个网络来说难度是极大的. 技术的进步使我们遇到了html5.下面这个简单粗暴的demo就是来完成这些功能的.直接看代码: <!DOCTYPE html> <html> <head> <title>html5调用摄像头实现拍照</title> &l

javascript 调用电脑摄像头

<video id="video" width="640" height="480" autoplay></video><button id="snap">Snap Photo</button><canvas id="canvas" width="640" height="480"></canvas&g

android调用系统相机拍照并保存在本地

import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Locale; import android.annotation.SuppressLint; import android.app.Activity; import an