海康相机大恒相机接口二次封装

包含海康相机与大恒相机二次封装
使用示例:
MCamera_hk hk1;
private void Form1_Load(object sender, EventArgs e)
{

    hk1 = new MCamera_hk(_process, 1);
    hk1.OpenOneCameraByUserName("xxxx");
    hk1.SetTriggerMode(1);
    hk1.SetCallBack();
    hk1.StartGetStream();
}
public void _process(Bitmap image)
{
    pictureBox1.Image = image;
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

using MvCamCtrl.NET;
using MvCamCtrl.NET.CameraParams;

using GxIAPINET;

namespace Camera
{

    public class MCamera_hk
    {

        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="pData"></param>
        /// <param name="pFrameInfo"></param>
        /// <param name="pUser"></param>
        private void ImageCallbackFunc(IntPtr pData, ref MV_FRAME_OUT_INFO_EX pFrameInfo, IntPtr pUser)
        {
            Console.WriteLine("Get one frame: Width[" + Convert.ToString(pFrameInfo.nWidth) + "] , Height[" + Convert.ToString(pFrameInfo.nHeight)
                                 + "] , FrameNum[" + Convert.ToString(pFrameInfo.nFrameNum) + "]");

            int width = pFrameInfo.nWidth;
            int height = pFrameInfo.nHeight;
            byte[] SrcData = new byte[pFrameInfo.nHeight * pFrameInfo.nWidth * channel];//图像数据
            Marshal.Copy(pData, SrcData, 0, SrcData.Length);

            Bitmap b = getBitmapFromByteStream(SrcData, height, width, channel);
            process(b);


        }

        #region 变量
        public CCamera hik = new CCamera();
        private int nRet = CErrorDefine.MV_OK;
        bool m_bIsDeviceOpen = false;       // ch:设备打开状态 | en:Is device open
        public bool m_bGrabbing = false;           // ch:设备取图状态
        private cbOutputExdelegate ImageCallback;

        Action<Bitmap> process;
        int channel;
        #endregion

        #region 对外接口

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="pro">传入的处理函数</param>
        /// <param name="ch">通道数</param>
        public MCamera_hk(Action<Bitmap> pro, int ch)
        {
            process = pro;
            channel = ch;
        }

        /// <summary>
        /// 根据ip指定相机
        /// </summary>
        /// <param name="str">ip地址</param>
        /// <returns>是否操作成功</returns>
        public bool OpenOneCameraByIP(string str)
        {
            List<CCameraInfo> ltDeviceList = new List<CCameraInfo>();
            GetDeviceList(ref ltDeviceList);

            for (int i = 0; i < ltDeviceList.Count; i++)
            {
                int nDevIndex = i;

                CGigECameraInfo cGigEDeviceInfo = (CGigECameraInfo)ltDeviceList[i];

                uint nIp1 = ((cGigEDeviceInfo.nCurrentIp & 0xff000000) >> 24);
                uint nIp2 = ((cGigEDeviceInfo.nCurrentIp & 0x00ff0000) >> 16);
                uint nIp3 = ((cGigEDeviceInfo.nCurrentIp & 0x0000ff00) >> 8);
                uint nIp4 = (cGigEDeviceInfo.nCurrentIp & 0x000000ff);

                string ss = nIp1 + "." + nIp2 + "." + nIp3 + "." + nIp4;
                if (ss == str)
                {
                    CCameraInfo stDevice = ltDeviceList[nDevIndex];

                    // ch:创建设备 | en:Create device
                    nRet = hik.CreateHandle(ref stDevice);
                    if (CErrorDefine.MV_OK != nRet)
                    {
                        Console.WriteLine("Create device failed:{0:x8}", nRet);
                        return false;
                    }

                    // ch:打开设备 | en:Open device
                    nRet = hik.OpenDevice();
                    if (CErrorDefine.MV_OK != nRet)
                    {
                        Console.WriteLine("Open device failed:{0:x8}", nRet);
                        return false;
                    }
                    m_bIsDeviceOpen = true;

                    // ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
                    if (stDevice.nTLayerType == CSystem.MV_GIGE_DEVICE)
                    {
                        int nPacketSize = hik.GIGE_GetOptimalPacketSize();
                        if (nPacketSize > 0)
                        {
                            nRet = hik.SetIntValue("GevSCPSPacketSize", (uint)nPacketSize);
                            if (nRet != CErrorDefine.MV_OK)
                            {
                                Console.WriteLine("Set Packet Size failed!");
                            }
                        }
                    }


                }


            }

            return true;
        }

        /// <summary>
        /// 根据用户名指定相机
        /// </summary>
        /// <param name="str">用户名</param>
        /// <returns>是否操作成功</returns>
        public bool OpenOneCameraByUserName(string str)
        {
            List<CCameraInfo> ltDeviceList = new List<CCameraInfo>();
            GetDeviceList(ref ltDeviceList);

            for (int i = 0; i < ltDeviceList.Count; i++)
            {
                int nDevIndex = i;

                CGigECameraInfo cGigEDeviceInfo = (CGigECameraInfo)ltDeviceList[i];
                //  CUSBCameraInfo cGigEDeviceInfo = (CUSBCameraInfo)ltDeviceList[i];

                string ss = cGigEDeviceInfo.UserDefinedName;
                if (ss == str)
                {
                    CCameraInfo stDevice = ltDeviceList[nDevIndex];

                    // ch:创建设备 | en:Create device
                    nRet = hik.CreateHandle(ref stDevice);
                    if (CErrorDefine.MV_OK != nRet)
                    {
                        Console.WriteLine("Create device failed:{0:x8}", nRet);
                        return false;
                    }

                    // ch:打开设备 | en:Open device
                    nRet = hik.OpenDevice();
                    if (CErrorDefine.MV_OK != nRet)
                    {
                        Console.WriteLine("Open device failed:{0:x8}", nRet);
                        return false;
                    }
                    m_bIsDeviceOpen = true;
                }


            }

            return true;
        }

        /// <summary>
        /// 设置触发方式
        /// 0:关闭触发模式
        /// 1:软触发
        /// 2:硬触发
        /// </summary>
        /// <param name="index">触发模式序号</param>
        /// <returns></returns>
        public bool SetTriggerMode(int index)
        {
            if (index == 0)//触发模式关
            {
                nRet = hik.SetEnumValue("TriggerMode", (uint)MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_OFF);
                if (CErrorDefine.MV_OK != nRet)
                {
                    Console.WriteLine("Set TriggerMode failed:{0:x8}", nRet);
                    return false;
                }

            }
            else if (index == 1)//触发模式开  软触发
            {
                nRet = hik.SetEnumValue("TriggerMode", (uint)MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_ON);
                if (CErrorDefine.MV_OK != nRet)
                {
                    Console.WriteLine("Set TriggerMode failed:{0:x8}", nRet);
                    return false;
                }
                // ch:触发源设为软触发 | en:Set trigger source as Software
                hik.SetEnumValue("TriggerSource", (uint)MV_CAM_TRIGGER_SOURCE.MV_TRIGGER_SOURCE_SOFTWARE);

            }
            else if (index == 2)//触发模式开  硬触发
            {
                nRet = hik.SetEnumValue("TriggerMode", (uint)MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_ON);
                if (CErrorDefine.MV_OK != nRet)
                {
                    Console.WriteLine("Set TriggerMode failed:{0:x8}", nRet);
                    return false;
                }
                //设置触发方式
                hik.SetEnumValue("TriggerSource", (uint)MV_CAM_TRIGGER_SOURCE.MV_TRIGGER_SOURCE_LINE0);
            }

            return true;
        }

        /// <summary>
        /// 单次触发
        /// </summary>
        /// <returns></returns>
        public bool OneSoftTrigger()
        {
            // ch:触发命令 | en:Trigger command
            int nRet = hik.SetCommandValue("TriggerSoftware");
            if (CErrorDefine.MV_OK != nRet)
            {
                Console.WriteLine("Trigger Software Fail!");
                return false;
            }
            Console.WriteLine("Trigger One Time!");
            return true;
        }

        /// <summary>
        /// 设置回调函数
        /// </summary>
        /// <returns></returns>
        public bool SetCallBack()
        {
            // ch:注册回调函数 | en:Register image callback
            ImageCallback = new cbOutputExdelegate(ImageCallbackFunc);
            nRet = hik.RegisterImageCallBackEx(ImageCallback, IntPtr.Zero);
            if (CErrorDefine.MV_OK != nRet)
            {
                Console.WriteLine("Register image callback failed!");
                return false;
            }
            return true;
        }

        /// <summary>
        /// 开始取流
        /// </summary>
        /// <returns></returns>
        public bool StartGetStream()
        {
            // ch:前置配置 | en:pre-operation
            int nRet = NecessaryOperBeforeGrab();
            if (CErrorDefine.MV_OK != nRet)
            {
                return false;
            }

            nRet = hik.StartGrabbing();
            if (CErrorDefine.MV_OK != nRet)
            {
                Console.WriteLine("Start grabbing failed:{0:x8}", nRet);
                return false;
            }
            m_bGrabbing = true;
            return true;
        }

        /// <summary>
        /// 关闭相机  销毁设备
        /// </summary>
        /// <returns></returns>
        public bool CloseCamera()
        {
            // ch:关闭设备 | en:Close device
            if (true == m_bIsDeviceOpen)
            {
                nRet = hik.CloseDevice();
                if (CErrorDefine.MV_OK != nRet)
                {
                    Console.WriteLine("Close device failed:{0:x8}", nRet);
                    return false;
                }
            }
            m_bGrabbing = false;

            // ch:销毁设备 | en:Destroy device
            nRet = hik.DestroyHandle();
            if (CErrorDefine.MV_OK != nRet)
            {
                Console.WriteLine("Destroy device failed:{0:x8}", nRet);
                return false;
            }

            m_bIsDeviceOpen = false;
            Console.WriteLine("Camera offline!");
            return true;
        }


        #endregion

        #region 私有方法

        //获取设备列表
        private bool GetDeviceList(ref List<CCameraInfo> ltDeviceList)
        {

            // ch:枚举设备 | en:Enum device
            nRet = CSystem.EnumDevices(CSystem.MV_GIGE_DEVICE | CSystem.MV_USB_DEVICE, ref ltDeviceList);
            if (CErrorDefine.MV_OK != nRet)
            {
                Console.WriteLine("Enum device failed:{0:x8}", nRet);
                return false;
            }
            Console.WriteLine("Enum device count : " + Convert.ToString(ltDeviceList.Count));
            if (0 == ltDeviceList.Count)
            {
                return false;
            }
            return true;
        }

        PixelFormat m_enBitmapPixelFormat = PixelFormat.DontCare;
        public Bitmap m_pcBitmap = null;
        private Int32 NecessaryOperBeforeGrab()
        {
            // ch:取图像宽 | en:Get Iamge Width
            CIntValue pcWidth = new CIntValue();
            int nRet = hik.GetIntValue("Width", ref pcWidth);
            if (CErrorDefine.MV_OK != nRet)
            {
                Console.WriteLine("Get Width Info Fail!");
                return nRet;
            }

            // ch:取图像高 | en:Get Iamge Height
            CIntValue pcHeight = new CIntValue();
            nRet = hik.GetIntValue("Height", ref pcHeight);
            if (CErrorDefine.MV_OK != nRet)
            {
                Console.WriteLine("Get Height Info Fail!");
                return nRet;
            }

            // ch:取像素格式 | en:Get Pixel Format
            CEnumValue m_pcPixelFormat = new CEnumValue();
            nRet = hik.GetEnumValue("PixelFormat", ref m_pcPixelFormat);
            if (CErrorDefine.MV_OK != nRet)
            {
                Console.WriteLine("Get Pixel Format Fail!");
                return nRet;
            }

            // ch:设置bitmap像素格式
            if ((Int32)MvGvspPixelType.PixelType_Gvsp_Undefined == (Int32)m_pcPixelFormat.CurValue)
            {

                Console.WriteLine("Unknown Pixel Format!");
                return CErrorDefine.MV_E_UNKNOW;
            }
            else if (IsMonoData((MvGvspPixelType)m_pcPixelFormat.CurValue))
            {
                m_enBitmapPixelFormat = PixelFormat.Format8bppIndexed;
            }
            else
            {
                m_enBitmapPixelFormat = PixelFormat.Format24bppRgb;
            }

            if (null != m_pcBitmap)
            {
                m_pcBitmap.Dispose();
                m_pcBitmap = null;
            }
            m_pcBitmap = new Bitmap((Int32)pcWidth.CurValue, (Int32)pcHeight.CurValue, m_enBitmapPixelFormat);

            // ch:Mono8格式,设置为标准调色板 | en:Set Standard Palette in Mono8 Format
            if (PixelFormat.Format8bppIndexed == m_enBitmapPixelFormat)
            {
                ColorPalette palette = m_pcBitmap.Palette;
                for (int i = 0; i < palette.Entries.Length; i++)
                {
                    palette.Entries[i] = Color.FromArgb(i, i, i);
                }
                m_pcBitmap.Palette = palette;
            }

            return CErrorDefine.MV_OK;
        }
        private Boolean IsMonoData(MvGvspPixelType enGvspPixelType)
        {
            switch (enGvspPixelType)
            {
                case MvGvspPixelType.PixelType_Gvsp_Mono8:
                case MvGvspPixelType.PixelType_Gvsp_Mono10:
                case MvGvspPixelType.PixelType_Gvsp_Mono10_Packed:
                case MvGvspPixelType.PixelType_Gvsp_Mono12:
                case MvGvspPixelType.PixelType_Gvsp_Mono12_Packed:
                    return true;

                default:
                    return false;
            }
        }
        private Boolean IsColorData(MvGvspPixelType enGvspPixelType)
        {
            switch (enGvspPixelType)
            {
                case MvGvspPixelType.PixelType_Gvsp_BayerGR8:
                case MvGvspPixelType.PixelType_Gvsp_BayerRG8:
                case MvGvspPixelType.PixelType_Gvsp_BayerGB8:
                case MvGvspPixelType.PixelType_Gvsp_BayerBG8:
                case MvGvspPixelType.PixelType_Gvsp_BayerGR10:
                case MvGvspPixelType.PixelType_Gvsp_BayerRG10:
                case MvGvspPixelType.PixelType_Gvsp_BayerGB10:
                case MvGvspPixelType.PixelType_Gvsp_BayerBG10:
                case MvGvspPixelType.PixelType_Gvsp_BayerGR12:
                case MvGvspPixelType.PixelType_Gvsp_BayerRG12:
                case MvGvspPixelType.PixelType_Gvsp_BayerGB12:
                case MvGvspPixelType.PixelType_Gvsp_BayerBG12:
                case MvGvspPixelType.PixelType_Gvsp_BayerGR10_Packed:
                case MvGvspPixelType.PixelType_Gvsp_BayerRG10_Packed:
                case MvGvspPixelType.PixelType_Gvsp_BayerGB10_Packed:
                case MvGvspPixelType.PixelType_Gvsp_BayerBG10_Packed:
                case MvGvspPixelType.PixelType_Gvsp_BayerGR12_Packed:
                case MvGvspPixelType.PixelType_Gvsp_BayerRG12_Packed:
                case MvGvspPixelType.PixelType_Gvsp_BayerGB12_Packed:
                case MvGvspPixelType.PixelType_Gvsp_BayerBG12_Packed:
                case MvGvspPixelType.PixelType_Gvsp_RGB8_Packed:
                case MvGvspPixelType.PixelType_Gvsp_YUV422_Packed:
                case MvGvspPixelType.PixelType_Gvsp_YUV422_YUYV_Packed:
                    return true;

                default:
                    return false;
            }
        }
        private Bitmap getBitmapFromByteStream(byte[] imgByte, int imgH, int imgW, int channel)
        {
            //申请目标位图的变量,并将其内存区域锁定
            Bitmap bitmap = null;
            if (channel == 3)
            {
                bitmap = new Bitmap(imgW, imgH, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            }
            else if (channel == 1)
            {
                bitmap = new Bitmap(imgW, imgH, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            }
            else if (channel == 4)
            {
                bitmap = new Bitmap(imgW, imgH, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            }
            else
            {
                return bitmap;
            }

            BitmapData bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, imgW, imgH), ImageLockMode.WriteOnly, bitmap.PixelFormat);

            //获取图像参数
            int stride = bitmapData.Stride; //扫描线的宽度
            int offset = stride - imgW * channel;        //显示宽度与扫描线宽度的问题
            IntPtr iptr = bitmapData.Scan0;    //获取bitmapdata的内存起始位置
            int scanbytes = stride * imgH;   //用stride宽度,表示这是内存区域的大小

            int posScan = 0, posReal = 0;
            byte[] pixelvalues = new byte[scanbytes];

            if (0 != offset)
            {
                for (int x = 0; x < imgH; x++)
                {
                    for (int y = 0; y < imgW * channel; y++)
                    {
                        pixelvalues[posScan++] = imgByte[posReal++];
                    }
                    posScan += offset;
                }
                Marshal.Copy(pixelvalues, 0, iptr, scanbytes);
            }
            else
            {
                Marshal.Copy(imgByte, 0, iptr, scanbytes);
            }

            bitmap.UnlockBits(bitmapData);

            if (channel == 1)
            {
                //从伪彩改为灰度
                var pal = bitmap.Palette;
                for (int j = 0; j < 256; j++)
                    pal.Entries[j] = System.Drawing.Color.FromArgb(j, j, j);
                bitmap.Palette = pal;
            }

            return bitmap;
        }
        #endregion
    }


    public class MCamera_daheng
    {
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="objUserParam"></param>
        /// <param name="objIFrameData"></param>
        private void ImageCallbackFunc(object objUserParam, IFrameData objIFrameData)
        {
            Console.WriteLine(SN + " 回调触发");
            if (m_bIsColor)
            {
                GX_VALID_BIT_LIST emValidBits = GX_VALID_BIT_LIST.GX_BIT_0_7;
                emValidBits = __GetBestValudBit(objIFrameData.GetPixelFormat());
                IntPtr pBufferColor = objIFrameData.ConvertToRGB24(emValidBits, GX_BAYER_CONVERT_TYPE_LIST.GX_RAW2RGB_NEIGHBOUR, false);
                CameraData = new Bitmap((int)objIFrameData.GetWidth(), (int)objIFrameData.GetHeight(), (int)objIFrameData.GetWidth() * 3, System.Drawing.Imaging.PixelFormat.Format24bppRgb, pBufferColor);

            }
            else
            {
                //MCamera_daheng objdhCamera = objUserParam as MCamera_daheng;
                CameraData = new Bitmap((int)objIFrameData.GetWidth(), (int)objIFrameData.GetHeight(), (int)objIFrameData.GetWidth(), System.Drawing.Imaging.PixelFormat.Format8bppIndexed, objIFrameData.GetBuffer());

                //添加调色板
                ColorPalette palette;
                palette = CameraData.Palette;
                int i = 0;
                for (i = 0; i <= 255; i++)
                {
                    palette.Entries[i] = System.Drawing.Color.FromArgb(i, i, i);
                }
                CameraData.Palette = palette;
            }
            process(CameraData);

        }

        #region 变量
        Action<Bitmap> process;
        int channel;

        string SN;


        static List<IGXDeviceInfo> listGXDeviceInfo;                ///<设备信息表  
        static IGXFactory m_objIGXFactory = null;                   ///<Factory对像

        IGXDevice m_objIGXDevice = null;                            ///<设备对像
        IGXStream m_objIGXStream = null;                            ///<流对像
        IGXFeatureControl m_objIGXFeatureControl = null;            ///<远端设备属性控制器对像
        IGXFeatureControl m_objIGXStreamFeatureControl = null;      ///<流层属性控制器对象
        bool m_bIsOpen = false;                                     ///<设备打开状态
        bool m_bIsSnap = false;                                     ///<发送开采命令标识                                             
        int m_nPayloadSize = 0;                                     ///<图像数据大小
        int CamIndex = 0;                                           ///<相机序号
        Bitmap CameraData;                                          ///<输出bitmap图像   
        static int OutCamIndex = 0;                                 ///<将相机的序号输出类外
        public delegate void OutPutData(int index, Bitmap objdata); ///<声明一个委托类型
        OutPutData inPutFunc;                                       ///<定义一个委托对象
        bool m_isStartGrab = false;                                 ///<标志是否开始了流通道采集                                                                   
        public bool m_bIsColor = false;                                    ///<是否支持彩色相机

        #endregion

        #region 对外接口

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="pro">回调函数中处理函数</param>
        /// <returns></returns>
        public MCamera_daheng(Action<Bitmap> pro, int chan)
        {
            //使用其他接口之前,必须执行初始化
            IGXFactory.GetInstance().Init();

            process = pro;
            channel = chan;
        }

        /// <summary>
        /// 根据SN打开相机
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public bool OpenOneCameraBySN(string str)
        {

            List<IGXDeviceInfo> listGXDeviceInfo = new List<IGXDeviceInfo>();

            IGXFactory.GetInstance().UpdateAllDeviceList(200, listGXDeviceInfo);

            Console.WriteLine("当前设备个数:" + listGXDeviceInfo.Count);
            // 判断当前连接设备个数
            if (listGXDeviceInfo.Count <= 0)
            {
                Console.WriteLine("未发现设备");
                return false;
            }
            int i;
            for (i = 0; i < listGXDeviceInfo.Count; i++)
            {
                string s = listGXDeviceInfo[i].GetSN();
                if (s == str)
                {
                    break;
                }
            }
            if (i >= listGXDeviceInfo.Count)
            {
                Console.WriteLine("未找到与所输SN对应的设备");
                return false;
            }
            SN = str;

            //按照sn打开设备
            m_objIGXDevice = IGXFactory.GetInstance().OpenDeviceBySN(str, GX_ACCESS_MODE.GX_ACCESS_EXCLUSIVE);
            m_objIGXFeatureControl = m_objIGXDevice.GetRemoteFeatureControl();

            //打开流通道
            if (null != m_objIGXDevice)
            {
                m_objIGXStream = m_objIGXDevice.OpenStream(0);

                m_objIGXStreamFeatureControl = m_objIGXStream.GetFeatureControl();
            }
            // a = objFunc;
            m_nPayloadSize = (int)m_objIGXDevice.GetRemoteFeatureControl().GetIntFeature("PayloadSize").GetValue();
            //获取是否为彩色相机
            string strValue = null;
            if (m_objIGXDevice.GetRemoteFeatureControl().IsImplemented("PixelColorFilter"))
            {
                strValue = m_objIGXDevice.GetRemoteFeatureControl().GetEnumFeature("PixelColorFilter").GetValue();

                if ("None" != strValue)
                {
                    m_bIsColor = true;
                }
            }


            // 建议用户在打开网络相机之后,根据当前网络环境设置相机的流通道包长值,
            // 以提高网络相机的采集性能,设置方法参考以下代码。
            GX_DEVICE_CLASS_LIST objDeviceClass = m_objIGXDevice.GetDeviceInfo().GetDeviceClass();
            if (GX_DEVICE_CLASS_LIST.GX_DEVICE_CLASS_GEV == objDeviceClass)
            {
                // 判断设备是否支持流通道数据包功能
                if (true == m_objIGXFeatureControl.IsImplemented("GevSCPSPacketSize"))
                {
                    // 获取当前网络环境的最优包长值
                    uint nPacketSize = m_objIGXStream.GetOptimalPacketSize();
                    // 将最优包长值设置为当前设备的流通道包长值
                    m_objIGXFeatureControl.GetIntFeature("GevSCPSPacketSize").SetValue(nPacketSize);
                }
            }


            m_bIsOpen = true;

            Console.WriteLine(SN + " 设置打开成功");
            return true;
        }

        /// <summary>
        /// 根据IP地址打开相机  待修改
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public bool OpenOneCameraByIP(string str)
        {

            List<IGXDeviceInfo> listGXDeviceInfo = new List<IGXDeviceInfo>();

            IGXFactory.GetInstance().UpdateAllDeviceList(200, listGXDeviceInfo);

            Console.WriteLine("当前设备个数:" + listGXDeviceInfo.Count);
            // 判断当前连接设备个数
            if (listGXDeviceInfo.Count <= 0)
            {
                Console.WriteLine("未发现设备");
                return false;
            }

            //按照sn打开设备
            m_objIGXDevice = IGXFactory.GetInstance().OpenDeviceByIP(str, GX_ACCESS_MODE.GX_ACCESS_EXCLUSIVE);
            m_objIGXFeatureControl = m_objIGXDevice.GetRemoteFeatureControl();

            //打开流通道
            if (null != m_objIGXDevice)
            {
                m_objIGXStream = m_objIGXDevice.OpenStream(0);
            }
            // a = objFunc;
            m_nPayloadSize = (int)m_objIGXDevice.GetRemoteFeatureControl().GetIntFeature("PayloadSize").GetValue();
            //获取是否为彩色相机
            string strValue = null;
            if (m_objIGXDevice.GetRemoteFeatureControl().IsImplemented("PixelColorFilter"))
            {
                strValue = m_objIGXDevice.GetRemoteFeatureControl().GetEnumFeature("PixelColorFilter").GetValue();

                if ("None" != strValue)
                {
                    m_bIsColor = true;
                }
            }

            m_bIsOpen = true;

            return true;
        }

        /// <summary>
        /// 根据MAC地址打开相机  待修改
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public bool OpenOneCameraByMAC(string str)
        {

            List<IGXDeviceInfo> listGXDeviceInfo = new List<IGXDeviceInfo>();

            IGXFactory.GetInstance().UpdateAllDeviceList(200, listGXDeviceInfo);

            Console.WriteLine("当前设备个数:" + listGXDeviceInfo.Count);
            // 判断当前连接设备个数
            if (listGXDeviceInfo.Count <= 0)
            {
                Console.WriteLine("未发现设备");
                return false;
            }

            //按照sn打开设备
            m_objIGXDevice = IGXFactory.GetInstance().OpenDeviceByMAC(str, GX_ACCESS_MODE.GX_ACCESS_EXCLUSIVE);
            m_objIGXFeatureControl = m_objIGXDevice.GetRemoteFeatureControl();

            //打开流通道
            if (null != m_objIGXDevice)
            {
                m_objIGXStream = m_objIGXDevice.OpenStream(0);
            }
            // a = objFunc;
            m_nPayloadSize = (int)m_objIGXDevice.GetRemoteFeatureControl().GetIntFeature("PayloadSize").GetValue();
            //获取是否为彩色相机
            string strValue = null;
            if (m_objIGXDevice.GetRemoteFeatureControl().IsImplemented("PixelColorFilter"))
            {
                strValue = m_objIGXDevice.GetRemoteFeatureControl().GetEnumFeature("PixelColorFilter").GetValue();

                if ("None" != strValue)
                {
                    m_bIsColor = true;
                }
            }

            m_bIsOpen = true;

            return true;
        }

        /// <summary>
        /// 设置曝光时间
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        public bool SetExposureTime(double exp)
        {
            //获取当前相机的曝光值、最小值、最大值和单位
            if (null != m_objIGXFeatureControl)
            {
                double dMin, dMax;
                dMin = m_objIGXFeatureControl.GetFloatFeature("ExposureTime").GetMin();
                dMax = m_objIGXFeatureControl.GetFloatFeature("ExposureTime").GetMax();
                //判断输入值是否在曝光时间的范围内
                //若大于最大值则将曝光值设为最大值
                if (exp > dMax)
                {
                    exp = dMax;
                    Console.WriteLine(SN + " 所设曝光大于最大值 已设为最大值" + dMax);
                }
                //若小于最小值将曝光值设为最小值
                if (exp < dMin)
                {
                    exp = dMin;
                    Console.WriteLine(SN + " 所设曝光小于最小值 已设为最大值" + dMin);
                }

                m_objIGXFeatureControl.GetFloatFeature("ExposureTime").SetValue(exp);

                Console.WriteLine(SN + " 设置曝光成功");
                return true;
            }
            Console.WriteLine(SN + " 设置曝光失败");
            return false;


        }

        /// <summary>
        /// 设置增益
        /// </summary>
        /// <param name="gain"></param>
        /// <returns></returns>
        public bool SetGain(double gain)
        {
            //当前相机的增益值、最小值、最大值
            if (null != m_objIGXFeatureControl)
            {
                double dMin, dMax;
                dMin = m_objIGXFeatureControl.GetFloatFeature("Gain").GetMin();
                dMax = m_objIGXFeatureControl.GetFloatFeature("Gain").GetMax();

                //判断输入值是否在增益值的范围内
                //若输入的值大于最大值则将增益值设置成最大值
                if (gain > dMax)
                {
                    gain = dMax;
                    Console.WriteLine(SN + " 所设增益大于最大值 已设为最大值" + dMax);
                }

                //若输入的值小于最小值则将增益的值设置成最小值
                if (gain < dMin)
                {
                    gain = dMin;
                    Console.WriteLine(SN + " 所设增益大于最大值 已设为最大值" + dMax);
                }

                m_objIGXFeatureControl.GetFloatFeature("Gain").SetValue(gain);

                Console.WriteLine(SN + "设置增益成功");
                return true;
            }
            Console.WriteLine(SN + "设置增益失败");
            return false;

        }

        /// <summary>
        /// 设置触发方式
        /// 0:关闭触发模式
        /// 1:软触发
        /// 2:硬触发
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public bool SetTriggerMode(int index)
        {
            if (m_objIGXFeatureControl == null)
            {
                Console.WriteLine("SN输入错误 设置触发失败");
                return false;
            }

            if (index == 0)
            {
                m_objIGXFeatureControl.GetEnumFeature("TriggerMode").SetValue("Off");
            }
            else if (index == 1)
            {
                m_objIGXFeatureControl.GetEnumFeature("TriggerMode").SetValue("On");
                m_objIGXFeatureControl.GetEnumFeature("TriggerSource").SetValue("Software");
                Console.WriteLine(SN + " 触发模式设置成功!");
            }
            else if (index == 2)
            {
                m_objIGXFeatureControl.GetEnumFeature("TriggerMode").SetValue("On");
                m_objIGXFeatureControl.GetEnumFeature("TriggerSource").SetValue("Line0");
            }

            return true;
        }

        /// <summary>
        /// 单次软触发
        /// </summary>
        /// <returns></returns>
        public bool OneSoftTrigger()
        {
            //发送软触发命令
            if (null != m_objIGXFeatureControl)
            {
                m_objIGXFeatureControl.GetCommandFeature("TriggerSoftware").Execute();
                Console.WriteLine(SN + "单次触发成功");
                return true;
            }
            Console.WriteLine(SN + "单次触发失败");
            return false;
        }
        /// <summary>
        /// 开始取流
        /// </summary>
        /// <returns></returns>
        public bool StartGetStream()
        {
            if (null != m_objIGXStreamFeatureControl)
            {
                try
                {
                    //设置流层Buffer处理模式为OldestFirst
                    m_objIGXStreamFeatureControl.GetEnumFeature("StreamBufferHandlingMode").SetValue("OldestFirst");
                }
                catch (Exception)
                {
                }
            }

            //开启采集流通道
            if (null != m_objIGXStream)
            {
                //RegisterCaptureCallback第一个参数属于用户自定参数(类型必须为引用
                //类型),若用户想用这个参数可以在委托函数中进行使用
                m_objIGXStream.RegisterCaptureCallback(this, ImageCallbackFunc);
                m_objIGXStream.StartGrab();
                m_isStartGrab = true;
            }

            //发送开采命令
            if (null != m_objIGXFeatureControl)
            {
                m_objIGXFeatureControl.GetCommandFeature("AcquisitionStart").Execute();
            }
            m_bIsSnap = true;


            return true;
        }

        /// <summary>
        /// 关闭取流
        /// </summary>
        /// <returns></returns>
        public bool CloseCamera()
        {
            if (m_bIsSnap)
            {
                if (null != m_objIGXFeatureControl)
                {
                    m_objIGXFeatureControl.GetCommandFeature("AcquisitionStop").Execute();
                    m_objIGXFeatureControl = null;

                    m_objIGXStreamFeatureControl = null;
                }
            }
            m_bIsSnap = false;
            Console.WriteLine(SN + " 取流已停止!");
            //停止流通道、注销采集回调和关闭流
            if (null != m_objIGXStream)
            {
                //停止流通道采集
                m_objIGXStream.StopGrab();
                //注销采集回调函数
                m_objIGXStream.UnregisterCaptureCallback();
                m_objIGXStream.Close();
                m_objIGXStream = null;
            }
            //关闭设备
            if (null != m_objIGXDevice)
            {
                m_objIGXDevice.Close();
                m_objIGXDevice = null;
            }
            Console.WriteLine(SN + " 设备已关闭");
            m_bIsOpen = false;
            return true;
        }


        #endregion

        #region 私有方法
        /// <summary>
        /// 通过GX_PIXEL_FORMAT_ENTRY获取最优Bit位
        /// </summary>
        /// <param name="em">图像数据格式</param>
        /// <returns>最优Bit位</returns>
        private GX_VALID_BIT_LIST __GetBestValudBit(GX_PIXEL_FORMAT_ENTRY emPixelFormatEntry)
        {
            GX_VALID_BIT_LIST emValidBits = GX_VALID_BIT_LIST.GX_BIT_0_7;
            switch (emPixelFormatEntry)
            {
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO8:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR8:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG8:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB8:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG8:
                    {
                        emValidBits = GX_VALID_BIT_LIST.GX_BIT_0_7;
                        break;
                    }
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO10:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR10:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG10:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB10:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG10:
                    {
                        emValidBits = GX_VALID_BIT_LIST.GX_BIT_2_9;
                        break;
                    }
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO12:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR12:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG12:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB12:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG12:
                    {
                        emValidBits = GX_VALID_BIT_LIST.GX_BIT_4_11;
                        break;
                    }
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO14:
                    {
                        //暂时没有这样的数据格式待升级
                        break;
                    }
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO16:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR16:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG16:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB16:
                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG16:
                    {
                        //暂时没有这样的数据格式待升级
                        break;
                    }
                default:
                    break;
            }
            return emValidBits;
        }

        #endregion

        ~MCamera_daheng()
        {
            //关闭设备之后,不能再调用其他任何库接口
            IGXFactory.GetInstance().Uninit();
        }

    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牛奶奥利奥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值