Basler.cs 9.7 KB
using System;
using Basler.Pylon;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using HalconDotNet;
using System.Runtime.InteropServices;

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 Bitmap 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 null;
                    }
                    Bitmap _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 _image;
                }
                catch (Exception ex)
                {
                    _errInfo = ex.Message;
                    return null;
                }
            }
            return null;
        }

        public override Bitmap GrabOne(string name)
        {
            int idx = Array.FindIndex(_name, s => s == name);
            if (idx == -1)
                return null;
            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;
        }


        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)
            {
                return GrabOne(name);

            }
            return null;
        }
        public override HObject CaptureOnImage(string name)
        {
            return CaptureOnImage(name, out _);
        }
        public override HObject CaptureOnImage(string name,out Bitmap bmp)
        {
            HObject hoImage = null;
            bmp = null;
            int index = cameraName.FindIndex(s => s == name);
            if (index == -1)
            {
                _errInfo = name + "Not find";
                return hoImage;
            }
            if (cameraCurr[index] != null)
            {
            }
            else
            {
                Open(index);
            }

            try
            {
                if (cameraCurr[index] != null)
                {
                    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 || !grabResult.GrabSucceeded)
                    {
                        _errInfo = grabResult.ErrorDescription;
                        return hoImage;
                    }

                    //相机像素数据
                    byte[] buffer = grabResult.PixelData as byte[];
                    //锁定像素数据
                    GCHandle hand = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                    //获取像素数据的指针
                    IntPtr pr = hand.AddrOfPinnedObject();
                    //HalconDotNet.HObject image;
                    //转成灰度图HOjbect
                    HalconDotNet.HOperatorSet.GenImage1(out hoImage, new HalconDotNet.HTuple("byte"), grabResult.Width, grabResult.Height, pr);
                    //释放内存
                    if (hand.IsAllocated) hand.Free();
                     
                    _errInfo = "OK";
                    return hoImage; 
                }
            }
            catch (Exception ex)
            {
                _errInfo = ex.Message;
                return hoImage;
            }
            finally
            {
                // cameraCurr[index].MV_CC_StopGrabbing_NET();
            }
            return hoImage;
        }
    }


}