Basler.cs 10.7 KB
using System;
using Basler.Pylon;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;

namespace CodeLibrary
{
    partial class Basler : ClsCamera
    {
        /// <summary>
        /// 当前相机
        /// </summary>
        private global::Basler.Pylon.Camera[] cameraCurr;
        /// <summary>
        /// 所有相机列表
        /// </summary>
        private List<ICameraInfo> cameraAll;
        ///// <summary>
        ///// 所有相机的名称
        ///// </summary>
        //private List<string> cameraName;
        /// <summary>
        /// 连续抓图事件
        /// </summary>
        public event Continuous Continuous_Event;




        public override void Close(string name)
        {
            int index = Array.FindIndex(_name, s => s == name);
            if (index == -1)
                return  ;
            if (cameraCurr[index] != null)
            {
                _isOpen[index] = false;
                cameraCurr[index].Close();
                cameraCurr[index].Dispose();
                cameraCurr[index] = null;
            }
        }


        public override void Close(int index)
        {
            if (cameraCurr[index] != null)
            {
                _isOpen[index] = false;
                cameraCurr[index].Close();
                cameraCurr[index].Dispose();
                cameraCurr[index] = null;
            }
        }

        public override void CloseAll()
        {
            for (int i = 0; i < cameraCurr.Length; i++)
            {
                if (cameraCurr[i] != null)
                {
                    _isOpen[i] = false;
                    cameraCurr[i].Close();
                    cameraCurr[i].Dispose();
                    cameraCurr[i] = null;
                }
            }
        }

        //public override bool GrabContinuous(int   index)
        //{
        //    try
        //    {
        //        cameraCurr[index].Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
        //        cameraCurr[index].StreamGrabber.Start(GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
        //        _errInfo = "OK";
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        _errInfo = ex.Message;
        //        return false;
        //    }
        //}

        //public override bool GrabOne()
        //{
        //    try
        //    {
        //        cameraCurr[_index].Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);

        //        //cameraCur.StreamGrabber.Start();
        //        //IGrabResult grabResult = cameraCur.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
        //        IGrabResult grabResult = cameraCurr[_index].StreamGrabber.GrabOne(5000);

        //        if (!grabResult.IsValid)
        //        {
        //            _errInfo = grabResult.ErrorDescription;
        //            return false;
        //        }
        //        _image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format24bppRgb);
        //        BitmapData bmpData = _image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
        //        IntPtr ptrBmp = bmpData.Scan0;
        //        int picSize = bmpData.Stride * grabResult.Height;

        //        PixelDataConverter conv = new PixelDataConverter();
        //        conv.OutputPixelFormat = PixelType.BGR8packed;
        //        conv.Convert(ptrBmp, picSize, grabResult);
        //        _buffer = new byte[picSize];
        //        System.Runtime.InteropServices.Marshal.Copy(ptrBmp, _buffer, 0, picSize);
        //        _image.UnlockBits(bmpData);

        //        _errInfo = "OK";
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        _errInfo = ex.Message;
        //        return false;
        //    }
        //}

        public override bool GrabOne(int index)
        {
            if (cameraCurr[index] != null)
            {
                try
                {
                    cameraCurr[index].Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);

                    //cameraCur.StreamGrabber.Start();
                    //IGrabResult grabResult = cameraCur.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
                    IGrabResult grabResult = cameraCurr[index].StreamGrabber.GrabOne(5000);

                    if (!grabResult.IsValid)
                    {
                        _errInfo = grabResult.ErrorDescription;
                        return false;
                    }
                    _image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format24bppRgb);
                    BitmapData bmpData = _image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                    IntPtr ptrBmp = bmpData.Scan0;
                    int picSize = bmpData.Stride * grabResult.Height;

                    PixelDataConverter conv = new PixelDataConverter();
                    conv.OutputPixelFormat = PixelType.BGR8packed;
                    conv.Convert(ptrBmp, picSize, grabResult);
                    _buffer = new byte[picSize];
                    System.Runtime.InteropServices.Marshal.Copy(ptrBmp, _buffer, 0, picSize);
                    _image.UnlockBits(bmpData);

                    _errInfo = "OK";
                    return true;
                }
                catch (Exception ex)
                {
                    _errInfo = ex.Message;
                    return false;
                }
            }return false;
        }

        public override bool GrabOne(string name)
        {
            int idx = Array.FindIndex(_name, s => s == name);
            if (idx == -1)
                return false;
            else
                return GrabOne(idx);
        }

        public override void GrabStop(int index)
        {
            if (cameraCurr[index] != null)
                cameraCurr[index].StreamGrabber.Stop();
        }

        public override bool Load()
        {
            try
            {
                cameraAll = CameraFinder.Enumerate();
                cameraName = new List<string>();
                foreach (ICameraInfo info in cameraAll)
                    cameraName.Add(info[CameraInfoKey.ModelName].ToString() + " (" + info[CameraInfoKey.SerialNumber].ToString() + ")");

                _name = cameraName.ToArray();
                _count = cameraName.Count;
                _isOpen = new bool[_count];
                _width = new int[_count];
                _height = new int[_count];
                cameraCurr = new global::Basler.Pylon.Camera[_count];
                _errInfo = "OK";
                return true;
            }
            catch (Exception ex)
            {
                _errInfo = ex.Message;
                return false;
            }
        }

        public override bool Open(int index)
        {
          //  _index = index;
            if (index < 0 || index >= _count)
            {
                _errInfo = "Not find";
                return false;
            }
            if (cameraCurr[index] != null) Close(index);

            try
            {
                cameraCurr[index] = new global::Basler.Pylon.Camera(cameraAll[index]);
                //cameraCur.ConnectionLost += OnConnectionLost;
                //cameraCur.CameraOpened += OnCameraOpened;
                //cameraCur.CameraClosed += OnCameraClosed;
                //cameraCur.StreamGrabber.GrabStarted += OnGrabStarted;
                cameraCurr[index].StreamGrabber.ImageGrabbed += OnImageGrabbed;
                //cameraCur.StreamGrabber.GrabStopped += OnGrabStopped;
                cameraCurr[index].Open();
                _width[index] = Convert.ToInt32(cameraCurr[index].Parameters[PLCamera.Width].GetValue());
                _height[index] = Convert.ToInt32(cameraCurr[index].Parameters[PLCamera.Height].GetValue());
                cameraCurr[index].Parameters[PLCamera.UserSetSelector].SetValue(PLCamera.UserSetSelector.UserSet1);  //加载用户设置1
                bool bln = cameraCurr[index].Parameters[PLCamera.UserSetLoad].TryExecute();  //执行设置


                _isOpen[index] = true;
                _errInfo = "OK";
                return true;
            }
            catch (Exception ex)
            {
                _errInfo = ex.Message;
                return false;
            }
        }

        public override bool Open(string name)
        {
            int n = cameraName.FindIndex(s => s == name);
            if (n == -1)
            {
                _errInfo = "Not find";
                return false;
            }
            else
                return Open(n);
        }

        public override bool OpenAll()
        {
            bool rtn = true;
            for (int i = 0; i < cameraName.Count; i++)
            {
                rtn = Open(i);
                if (!rtn) break;
            }
            return rtn;
        }




        private void OnImageGrabbed(object sender, ImageGrabbedEventArgs e)
        {
            try
            {
                IGrabResult grabResult = e.GrabResult;
                if (!grabResult.IsValid) return;

                _image= new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format24bppRgb);
                BitmapData bmpData = _image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                IntPtr ptrBmp = bmpData.Scan0;
                int picSize = bmpData.Stride * grabResult.Height;

                PixelDataConverter conv = new PixelDataConverter();
                conv.OutputPixelFormat = PixelType.BGR8packed;
                conv.Convert(ptrBmp, picSize, grabResult);
                _buffer = new byte[picSize];
                System.Runtime.InteropServices.Marshal.Copy(ptrBmp, Buffer, 0, picSize);
                _image.UnlockBits(bmpData);

                Continuous_Event?.Invoke();
            }
            catch (Exception ex)
            {
                _errInfo = ex.Message;
            }
            finally
            {
                e.DisposeGrabResultIfClone();
            }
        }

        public override Bitmap GrabOneImage(string name)
        {
            int n = cameraName.FindIndex(s => s == name);
            if (n == -1)
            {
                _errInfo = "Not find";
                return null;
            }
            if (cameraCurr[n] != null)
            {
                GrabOne(name);
                return Image;
            }
            return null;
        }
    }


}