海康工业相机操作类 hikccdHelper version1.0

勇哥手上有几个案子用到了海康工业相机,为了方便自己,简单写了一个操作类。

目前初步出了一个v1.0,功能围绕项目需要,因此十分简单,暂支持下面的内容:

  • 连续触发和外部信号触发

  • 外部触发时的软件触发模式

  • 枚举设备列表


可以看到连断线重连都没做。

先放上来吧,以后会持续完善它,并收录到netMarketing类库。


对于怎么接外部触发信号,请参考下面的贴子:

http://www.skcircle.com/?id=1420



演示程序如下:

其实我就是拷贝的官方程序的界面,各位正好看看有了操作类,相对于原例程来讲是大大的简化了编程。


简单说说用法:

如果你想得到连续拍图的效果,则勾选连续模式->开始采集

如果你想简单拍次一次图片,不用硬件触发,则勾选触发模式->开始采庥->勾选软触发->软触发一次

如果你想硬件触发一次,则勾选触发模式->开始采集->然后用的你的plc或者其它输出IO之类的硬件out一次


image.png

操作类的使用示例:

唯一要说明的是,你得在UI线程中注册一个OutImgEvent事件,以获取拍到的图片。

using HalconDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MvsHelper
{
    public partial class Form1 : Form
    {
        hikccdHelper ccd;
        HWindow m_Window;
        public Form1()
        {
            InitializeComponent();
            ccd = new hikccdHelper("测试相机A");
            m_Window = new HWindow();
            DisplayWindowsInitial();

            ccd.OutImgEvent += Ccd_OutImgEvent;
        }

        private void Ccd_OutImgEvent(object sender, EventArgs e)
        {
            HTuple width, height;
            HOperatorSet.GetImageSize(sender as HObject, out width, out height);
            HOperatorSet.SetPart(m_Window, 0, 0, height, width);
            HOperatorSet.DispImage(sender as HObject, m_Window);
            HOperatorSet.DispObj(sender as HObject, m_Window);
        }

        private void bnEnum_Click(object sender, EventArgs e)
        {
            var res=hikccdHelper.DeviceListAcq();
            cbDeviceList.Items.Clear();
            foreach (var m in res)
            {
                cbDeviceList.Items.Add(string.Format("{0},{1},{2}",m.ioType,m.userDefinedName,m.deviceSerialNum));
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            SetCtrlWhenClose();
            ccd.CloseCCD();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            bnEnum_Click(null, null);
            cbDeviceList.SelectedIndex = 0;
        }
        private void DisplayWindowsInitial()
        {
            //定义显示的起点和宽高
            HTuple hWindowRow, hWindowColumn, hWindowWidth, hWindowHeight;

            //设置显示窗口的起点和宽高
            hWindowRow = 0;
            hWindowColumn = 0;
            hWindowWidth = pictureBox1.Width;
            hWindowHeight = pictureBox1.Height;

            try
            {
                HTuple hWindowID = (HTuple)pictureBox1.Handle;
                m_Window.OpenWindow(hWindowRow, hWindowColumn, hWindowWidth, hWindowHeight, hWindowID, "visible", "");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }

        }

        private void bnOpen_Click(object sender, EventArgs e)
        {
            var txt = cbDeviceList.Text;
            if (cbDeviceList.SelectedIndex < 0) return;
            try
            {
                ccd.OpenCCD(txt.Split(',')[2]);
                SetCtrlWhenOpen();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void SetCtrlWhenOpen()
        {
            bnOpen.Enabled = false;

            bnClose.Enabled = true;
            bnStartGrab.Enabled = true;
            bnStopGrab.Enabled = false;
            bnContinuesMode.Enabled = true;
            bnContinuesMode.Checked = true;
            bnTriggerMode.Enabled = true;
            cbSoftTrigger.Enabled = false;
            bnTriggerExec.Enabled = false;

        }

        private void SetCtrlWhenClose()
        {
            bnOpen.Enabled = true;

            bnClose.Enabled = false;
            bnStartGrab.Enabled = false;
            bnStopGrab.Enabled = false;
            bnContinuesMode.Enabled = false;
            bnTriggerMode.Enabled = false;
            cbSoftTrigger.Enabled = false;
            bnTriggerExec.Enabled = false;

        }

        private void SetCtrlWhenStopGrab()
        {
            bnStartGrab.Enabled = true;
            bnStopGrab.Enabled = false;

            bnTriggerExec.Enabled = false;
        }

        private void SetCtrlWhenStartGrab()
        {
            bnStartGrab.Enabled = false;
            bnStopGrab.Enabled = true;

            if (bnTriggerMode.Checked && cbSoftTrigger.Checked)
            {
                bnTriggerExec.Enabled = true;
            }

        }

        private void bnClose_Click(object sender, EventArgs e)
        {
            ccd.CloseCCD();
            SetCtrlWhenClose();
        }

        private void bnContinuesMode_CheckedChanged(object sender, EventArgs e)
        {
            ccd.SetConitnueMode();
        }

        private void bnTriggerMode_CheckedChanged(object sender, EventArgs e)
        {
            if (bnTriggerMode.Checked)
            {
                ccd.SetTriggerMode(hikccdTriggerModeEnum.Line0);
            }
        }

        private void bnStartGrab_Click(object sender, EventArgs e)
        {
            ccd.StartGrab();
            cbSoftTrigger.Enabled = true;
            SetCtrlWhenStartGrab();
        }

        private void bnStopGrab_Click(object sender, EventArgs e)
        {
            ccd.StopGrab();
            SetCtrlWhenStopGrab();
        }

        private void cbSoftTrigger_CheckedChanged(object sender, EventArgs e)
        {

            ccd.SetSoftTrigger(cbSoftTrigger.Checked);
            if (cbSoftTrigger.Checked)
            {
                if (ccd.Grabbing)
                {
                    bnTriggerExec.Enabled = true;
                }
            }
            else
            {
                bnTriggerExec.Enabled = false;
            }
        }

        private void bnTriggerExec_Click(object sender, EventArgs e)
        {
            if (cbSoftTrigger.Checked && ccd.Grabbing)
                ccd.SoftTrigger();
        }
    }
}


海康相机操作类hkccdHelper v1.0

using HalconDotNet;
using MvCamCtrl.NET;
using netMarketing.Message;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MvsHelper
{

    public enum hikccdTriggerModeEnum
    {
        Line0 = 0, Line1, Line2, Line3, Counter, Software
    }

    /// <summary>
    /// 枚举设备的信息
    /// </summary>
    public struct EnumDeviceInfo
    {
        //GigE: QT6-104-B-CAM1 (00797114078)

        /// <summary>
        /// 设备IO类型,有usb,GigE
        /// </summary>
        public string ioType;
        /// <summary>
        /// 用户自定义的设备名称
        /// </summary>
        public string userDefinedName;

        /// <summary>
        /// 缺少的设备名称
        /// </summary>
        public string ManufacturerName;
        /// <summary>
        /// 设备模块名称
        /// </summary>
        public string modelName;
        /// <summary>
        /// 设备备唯一的串行号
        /// </summary>
        public string deviceSerialNum;
    }

    public struct grabImgStruct
    {
        public HObject img;
        public DateTime grabTime;
    }

    /// <summary>
    /// 海康面阵相机操作类 hikccdHelper version1.0
    /// www.skcircle.com  by 刘小勇(很想停止)
    /// QQ:496103864  微信:abc496103864
    /// </summary>
    public class hikccdHelper
    {
        private static MyCamera.MV_CC_DEVICE_INFO_LIST m_pDeviceList;
        private MyCamera hkCamera;
        private uint payloadSize;
        private bool grabbing;
        private byte[] m_pDataForRed = new byte[20 * 1024 * 1024];
        private byte[] m_pDataForGreen = new byte[20 * 1024 * 1024];
        private byte[] m_pDataForBlue = new byte[20 * 1024 * 1024];
        private grabImgStruct currentImg;
        public event EventHandler OutImgEvent;

        private hikccdTriggerModeEnum triggerMode;

        public hikccdTriggerModeEnum TriggerMode
        {
            get { return triggerMode; }
            set { triggerMode = value; }
        }

        /// <summary>
        /// 开始采集的状态
        /// </summary>
        public bool Grabbing
        {
            get { return grabbing; }
            set { grabbing = value; }
        }


        public hikccdHelper(string ccdname)
        {
            hkCamera = new MyCamera();
        }

        /// <summary>
        /// 取系统已经安装的海康相机数量
        /// </summary>
        /// <returns></returns>
        public static uint GetDeviceNum()
        {
            return m_pDeviceList.nDeviceNum;
        }

        /// <summary>
        /// 枚举系统已经安装的海康相机
        /// </summary>
        /// <returns>返回EnumDeviceInfo列表</returns>
        public static List<EnumDeviceInfo> DeviceListAcq()
        {
            var msg = string.Empty;
            var reslist = new List<EnumDeviceInfo>();
            int nRet;
            // ch:创建设备列表 || en: Create device list
            System.GC.Collect();
            
            nRet = MyCamera.MV_CC_EnumDevices_NET(MyCamera.MV_GIGE_DEVICE | MyCamera.MV_USB_DEVICE, ref m_pDeviceList);
            if (MyCamera.MV_OK != nRet)
            {
                msg = "Enum Devices Fail";
                NotifyG.Error(msg);
                throw new ArgumentException(msg);
            }

            // ch:在窗体列表中显示设备名 || Display the device'name on window's list
            for (int i = 0; i < m_pDeviceList.nDeviceNum; i++)
            {
                MyCamera.MV_CC_DEVICE_INFO device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[i], 
                    typeof(MyCamera.MV_CC_DEVICE_INFO));
                if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
                {
                    IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stGigEInfo, 0);
                    MyCamera.MV_GIGE_DEVICE_INFO gigeInfo = (MyCamera.MV_GIGE_DEVICE_INFO)Marshal.PtrToStructure(buffer, 
                        typeof(MyCamera.MV_GIGE_DEVICE_INFO));
                    if (gigeInfo.chUserDefinedName != "")
                    {
                        reslist.Add(new EnumDeviceInfo()
                        {
                            ioType = "GigE",
                            userDefinedName = gigeInfo.chUserDefinedName,
                            deviceSerialNum = gigeInfo.chSerialNumber,
                             ManufacturerName="", modelName=""
                        });
                    }
                    else
                    {
                        reslist.Add(new EnumDeviceInfo()
                        {
                            ioType = "GigE",
                            ManufacturerName = gigeInfo.chManufacturerName,
                            deviceSerialNum = gigeInfo.chSerialNumber,
                            modelName = gigeInfo.chModelName,
                            userDefinedName = ""
                        }) ;
                      
                    }
                }
                else if (device.nTLayerType == MyCamera.MV_USB_DEVICE)
                {
                    IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stUsb3VInfo, 0);
                    MyCamera.MV_USB3_DEVICE_INFO usbInfo = (MyCamera.MV_USB3_DEVICE_INFO)Marshal.PtrToStructure(buffer, 
                        typeof(MyCamera.MV_USB3_DEVICE_INFO));
                    if (usbInfo.chUserDefinedName != "")
                    {
                        reslist.Add(new EnumDeviceInfo()
                        {
                            ioType = "USB",
                            deviceSerialNum = usbInfo.chSerialNumber,
                            userDefinedName = usbInfo.chUserDefinedName,
                            modelName = "",
                            ManufacturerName = ""
                        });
                    }
                    else
                    {
                        reslist.Add(new EnumDeviceInfo()
                        {
                            ioType="USB", deviceSerialNum= usbInfo.chSerialNumber,
                             ManufacturerName= usbInfo.chManufacturerName,
                             modelName = usbInfo.chModelName, userDefinedName=""
                        });

                    }
                }
            }

            return reslist;
        }

        /// <summary>
        /// 打开指定的相机(按序列号) 异常:ArgumentException
        /// </summary>
        /// <param name="serialNum"></param>
        public void OpenCCD(string serialNum)
        {
            var msg = string.Empty;
            if (m_pDeviceList.nDeviceNum == 0)
            {
                msg = "No device,please select";
                NotifyG.Error(msg);
                throw new ArgumentNullException(msg);
            }
            int nRet = -1;

            for (int i = 0; i < m_pDeviceList.nDeviceNum; i++)
            {
                var device =
                    (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[i],
                                                                  typeof(MyCamera.MV_CC_DEVICE_INFO));
                IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stGigEInfo, 0);
                MyCamera.MV_GIGE_DEVICE_INFO gigeInfo = (MyCamera.MV_GIGE_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_GIGE_DEVICE_INFO));
                if(gigeInfo.chSerialNumber== serialNum)
                {
                    nRet = hkCamera.MV_CC_CreateDevice_NET(ref device);
                    if (MyCamera.MV_OK != nRet)
                    {
                        msg = "MV_CC_CreateDevice_NET Error!";
                        NotifyG.Error(msg);
                        throw new ArgumentException(msg);
                    }
                    //打开设备
                    nRet = hkCamera.MV_CC_OpenDevice_NET();
                    if (MyCamera.MV_OK != nRet)
                    {
                        msg = "Open Device Fail";
                        NotifyG.Error(msg);
                        throw new ArgumentException(msg);
                    }

                    //获取包大小
                    MyCamera.MVCC_INTVALUE stParam = new MyCamera.MVCC_INTVALUE();
                    nRet = hkCamera.MV_CC_GetIntValue_NET("PayloadSize", ref stParam);
                    if (MyCamera.MV_OK != nRet)
                    {
                        msg = "Get PayloadSize Fail";
                        NotifyG.Error(msg);
                        throw new ArgumentException(msg);
                    }
                    payloadSize = stParam.nCurValue;

                    //获取高
                    nRet = hkCamera.MV_CC_GetIntValue_NET("Height", ref stParam);
                    if (MyCamera.MV_OK != nRet)
                    {
                        msg = "Get Height Fail";
                        NotifyG.Error(msg);
                        throw new ArgumentException(msg);
                    }
                    uint nHeight = stParam.nCurValue;

                    //获取宽
                    nRet = hkCamera.MV_CC_GetIntValue_NET("Width", ref stParam);
                    if (MyCamera.MV_OK != nRet)
                    {
                        msg = "Get Width Fail";
                        NotifyG.Error(msg);
                        throw new ArgumentException(msg);
                    }
                    uint nWidth = stParam.nCurValue;

                    m_pDataForRed = new byte[nWidth * nHeight];
                    m_pDataForGreen = new byte[nWidth * nHeight];
                    m_pDataForBlue = new byte[nWidth * nHeight];


                    //设置触发模式为off
                    hkCamera.MV_CC_SetEnumValue_NET("AcquisitionMode", 2);
                    hkCamera.MV_CC_SetEnumValue_NET("TriggerMode", 0);
                    return;
                }

            }
            msg = string.Format("serialNum[{0}] not exist!", serialNum);
            NotifyG.Error(msg);
            throw new ArgumentException(msg);
        }

        /// <summary>
        /// 设置为连续拍照模式
        /// </summary>
        public void SetConitnueMode()
        {
            int nRet = MyCamera.MV_OK;

            nRet = hkCamera.MV_CC_SetEnumValue_NET("TriggerMode", 0);
            if (nRet != MyCamera.MV_OK)
            {
                NotifyG.Error("Set TriggerMode Fail");
                return;
            }
        }

        /// <summary>
        /// 设置为触发模式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void SetTriggerMode(hikccdTriggerModeEnum Mode)
        {
            int nRet = MyCamera.MV_OK;

            nRet = hkCamera.MV_CC_SetEnumValue_NET("TriggerMode", 1);
            if (nRet != MyCamera.MV_OK)
            {
                NotifyG.Error("Set TriggerMode Fail");
                return;
            }


            if ((int)Mode==7)
            {
                nRet = hkCamera.MV_CC_SetEnumValue_NET("TriggerSource", 7);
                if (nRet != MyCamera.MV_OK)
                {
                    NotifyG.Error("Set TriggerSource Fail");
                    return;
                }
                
            }
            else
            {
                nRet = hkCamera.MV_CC_SetEnumValue_NET("TriggerSource", (uint)Mode);
                if (nRet != MyCamera.MV_OK)
                {
                    NotifyG.Error("Set TriggerSource Fail");
                    return;
                }
            }
         

        }

        /// <summary>
        /// 外部触发-软触发
        /// </summary>
        /// <param name="isSoftTrigger"></param>
        public void SetSoftTrigger(bool isSoftTrigger)
        {
            if (isSoftTrigger)
            {
                //触发源设为软触发
                hkCamera.MV_CC_SetEnumValue_NET("TriggerSource", 7);
            }
            else
            {
                hkCamera.MV_CC_SetEnumValue_NET("TriggerSource", 0);
            }
        }

        /// <summary>
        /// 关闭相机
        /// </summary>
        public void CloseCCD()
        {
            if (grabbing)
            {
                grabbing = false;
                //停止抓图
                hkCamera.MV_CC_StopGrabbing_NET();
            }

            //关闭设备
            hkCamera.MV_CC_CloseDevice_NET();
            grabbing = false;
        }

        private bool IsMonoPixelFormat(MyCamera.MvGvspPixelType enType)
        {
            switch (enType)
            {
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono12_Packed:
                    return true;
                default:
                    return false;
            }
        }

        private bool IsColorPixelFormat(MyCamera.MvGvspPixelType enType)
        {
            switch (enType)
            {
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BGR8_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_RGBA8_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BGRA8_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_YUV422_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_YUV422_YUYV_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB12_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG12_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG12_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR12_Packed:
                    return true;
                default:
                    return false;
            }
        }

        private Int32 ConvertToMono8(object obj, IntPtr pInData, IntPtr pOutData, ushort nHeight, ushort nWidth, 
            MyCamera.MvGvspPixelType nPixelType)
        {
            if (IntPtr.Zero == pInData || IntPtr.Zero == pOutData)
            {
                return MyCamera.MV_E_PARAMETER;
            }

            int nRet = MyCamera.MV_OK;
            MyCamera device = obj as MyCamera;
            MyCamera.MV_PIXEL_CONVERT_PARAM stPixelConvertParam = new MyCamera.MV_PIXEL_CONVERT_PARAM();

            stPixelConvertParam.pSrcData = pInData;//源数据
            if (IntPtr.Zero == stPixelConvertParam.pSrcData)
            {
                return -1;
            }

            stPixelConvertParam.nWidth = nWidth;//图像宽度
            stPixelConvertParam.nHeight = nHeight;//图像高度
            stPixelConvertParam.enSrcPixelType = nPixelType;//源数据的格式
            stPixelConvertParam.nSrcDataLen = (uint)(nWidth * nHeight * ((((uint)nPixelType) >> 16) & 0x00ff) >> 3);

            stPixelConvertParam.nDstBufferSize = (uint)(nWidth * nHeight * ((((uint)MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed) >> 16) & 0x00ff) >> 3);
            stPixelConvertParam.pDstBuffer = pOutData;//转换后的数据
            stPixelConvertParam.enDstPixelType = MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8;
            stPixelConvertParam.nDstBufferSize = (uint)(nWidth * nHeight * 3);

            nRet = device.MV_CC_ConvertPixelType_NET(ref stPixelConvertParam);//格式转换
            if (MyCamera.MV_OK != nRet)
            {
                return -1;
            }

            return nRet;
        }

        private Int32 ConvertToRGB(object obj, IntPtr pSrc, ushort nHeight, ushort nWidth, 
            MyCamera.MvGvspPixelType nPixelType, IntPtr pDst)
        {
            if (IntPtr.Zero == pSrc || IntPtr.Zero == pDst)
            {
                return MyCamera.MV_E_PARAMETER;
            }

            int nRet = MyCamera.MV_OK;
            MyCamera device = obj as MyCamera;
            MyCamera.MV_PIXEL_CONVERT_PARAM stPixelConvertParam = new MyCamera.MV_PIXEL_CONVERT_PARAM();

            stPixelConvertParam.pSrcData = pSrc;//源数据
            if (IntPtr.Zero == stPixelConvertParam.pSrcData)
            {
                return -1;
            }

            stPixelConvertParam.nWidth = nWidth;//图像宽度
            stPixelConvertParam.nHeight = nHeight;//图像高度
            stPixelConvertParam.enSrcPixelType = nPixelType;//源数据的格式
            stPixelConvertParam.nSrcDataLen = (uint)(nWidth * nHeight * ((((uint)nPixelType) >> 16) & 0x00ff) >> 3);

            stPixelConvertParam.nDstBufferSize = (uint)(nWidth * nHeight * ((((uint)MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed) >> 16) & 0x00ff) >> 3);
            stPixelConvertParam.pDstBuffer = pDst;//转换后的数据
            stPixelConvertParam.enDstPixelType = MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed;
            stPixelConvertParam.nDstBufferSize = (uint)nWidth * nHeight * 3;

            nRet = device.MV_CC_ConvertPixelType_NET(ref stPixelConvertParam);//格式转换
            if (MyCamera.MV_OK != nRet)
            {
                return -1;
            }

            return MyCamera.MV_OK;
        }


        /// <summary>
        /// 开始采集
        /// </summary>
        public void StartGrab()
        {
            int nRet;

            //开启抓图
            nRet = hkCamera.MV_CC_StartGrabbing_NET();
            if (MyCamera.MV_OK != nRet)
            {
                NotifyG.Error(string.Format("Start Grabbing Fail"));
                return;
            }
            grabbing = true;

            Thread hReceiveImageThreadHandle = new Thread(ReceiveImageWorkThread);
            hReceiveImageThreadHandle.Start(hkCamera);

        }

        /// <summary>
        /// 停止采集
        /// </summary>
        public void StopGrab()
        {
            int nRet = -1;
            //停止抓图
            nRet = hkCamera.MV_CC_StopGrabbing_NET();
            if (nRet != MyCamera.MV_OK)
            {
                NotifyG.Error(string.Format("Stop Grabbing Fail"));
            }
            grabbing = false;
        }

        /// <summary>
        /// 软触发拍照
        /// </summary>
        public void SoftTrigger()
        {
            int nRet;

            // 软触发命令
            nRet = hkCamera.MV_CC_SetCommandValue_NET("TriggerSoftware");
            if (MyCamera.MV_OK != nRet)
            {
                NotifyG.Error(string.Format("TriggerSoftware Fail"));
            }
        }

        private void ReceiveImageWorkThread(object obj)
        {
            int nRet = MyCamera.MV_OK;
            MyCamera device = obj as MyCamera;
            MyCamera.MV_FRAME_OUT_INFO_EX pFrameInfo = new MyCamera.MV_FRAME_OUT_INFO_EX();
            IntPtr pData = Marshal.AllocHGlobal((int)payloadSize * 3);
            if (pData == IntPtr.Zero)
            {
                return;
            }
            IntPtr pImageBuffer = Marshal.AllocHGlobal((int)payloadSize * 3);
            if (pImageBuffer == IntPtr.Zero)
            {
                return;
            }

            uint nDataSize = payloadSize * 3;
            HObject Hobj = new HObject();
            IntPtr RedPtr = IntPtr.Zero;
            IntPtr GreenPtr = IntPtr.Zero;
            IntPtr BluePtr = IntPtr.Zero;
            IntPtr pTemp = IntPtr.Zero;

            while (grabbing)
            {
                nRet = device.MV_CC_GetOneFrameTimeout_NET(pData, nDataSize, ref pFrameInfo, 1000);
                if (MyCamera.MV_OK == nRet)
                {
                    if (IsColorPixelFormat(pFrameInfo.enPixelType))
                    {
                        if (pFrameInfo.enPixelType == MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed)
                        {
                            pTemp = pData;
                        }
                        else
                        {
                            nRet = ConvertToRGB(obj, pData, pFrameInfo.nHeight, pFrameInfo.nWidth, pFrameInfo.enPixelType, pImageBuffer);
                            if (MyCamera.MV_OK != nRet)
                            {
                                return;
                            }
                            pTemp = pImageBuffer;
                        }

                        unsafe
                        {
                            byte* pBufForSaveImage = (byte*)pTemp;

                            UInt32 nSupWidth = (pFrameInfo.nWidth + (UInt32)3) & 0xfffffffc;

                            for (int nRow = 0; nRow < pFrameInfo.nHeight; nRow++)
                            {
                                for (int col = 0; col < pFrameInfo.nWidth; col++)
                                {
                                    m_pDataForRed[nRow * nSupWidth + col] = pBufForSaveImage[nRow * pFrameInfo.nWidth * 3 + (3 * col)];
                                    m_pDataForGreen[nRow * nSupWidth + col] = pBufForSaveImage[nRow * pFrameInfo.nWidth * 3 + (3 * col + 1)];
                                    m_pDataForBlue[nRow * nSupWidth + col] = pBufForSaveImage[nRow * pFrameInfo.nWidth * 3 + (3 * col + 2)];
                                }
                            }
                        }

                        RedPtr = Marshal.UnsafeAddrOfPinnedArrayElement(m_pDataForRed, 0);
                        GreenPtr = Marshal.UnsafeAddrOfPinnedArrayElement(m_pDataForGreen, 0);
                        BluePtr = Marshal.UnsafeAddrOfPinnedArrayElement(m_pDataForBlue, 0);

                        try
                        {
                            HOperatorSet.GenImage3Extern(out Hobj, (HTuple)"byte", pFrameInfo.nWidth, pFrameInfo.nHeight,
                                                (new HTuple(RedPtr)), (new HTuple(GreenPtr)), (new HTuple(BluePtr)), IntPtr.Zero);
                        }
                        catch (System.Exception ex)
                        {
                            NotifyG.Error(string.Format("GenImage3Extern,error:[{0}]", ex.Message));
                        }
                    }
                    else if (IsMonoPixelFormat(pFrameInfo.enPixelType))
                    {
                        if (pFrameInfo.enPixelType == MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8)
                        {
                            pTemp = pData;
                        }
                        else
                        {
                            nRet = ConvertToMono8(device, pData, pImageBuffer, pFrameInfo.nHeight, pFrameInfo.nWidth, pFrameInfo.enPixelType);
                            if (MyCamera.MV_OK != nRet)
                            {
                                return;
                            }
                            pTemp = pImageBuffer;
                        }
                        try
                        {
                            HOperatorSet.GenImage1Extern(out Hobj, "byte", pFrameInfo.nWidth, pFrameInfo.nHeight,
                                pTemp, IntPtr.Zero);
                        }
                        catch (System.Exception ex)
                        {
                            NotifyG.Error(string.Format("GenImage1Extern,error:[{0}]", ex.Message));
                            return;
                        }
                    }
                    else
                    {
                        continue;
                    }
                    currentImg = new grabImgStruct()
                    {
                        img = Hobj,
                        grabTime = DateTime.Now
                    };
                    OutImgEvent(currentImg.img, new EventArgs());
                    //HalconDisplay(m_Window, Hobj, pFrameInfo.nHeight, pFrameInfo.nWidth);
                }
                else
                {
                    continue;
                }
            }
            if (pData != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(pData);
            }
            if (pImageBuffer != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(pImageBuffer);
            }
            return;
        }






    }
}


演示代码打包下载:

vs2019+halcon19.11

https://download.csdn.net/download/suneggs/12729864



--------------------- 

作者:hackpig

来源:www.skcircle.com

版权声明:本文为博主原创文章,转载请附上博文链接!


#转载请注明出处 www.skcircle.com 《少有人走的路》勇哥的工业自动化技术网站。如果需要本贴图片源码等资源,请向勇哥索取。
扫码加本站公众号
  • 评论列表:
  •  访客
     发布于 2020-09-29 09:57:40  回复该评论
  • Ccd_OutImgEvent中,采集到图像处理时 . 如果出现异常退出,重开会连接相机异常.提示相机连接失败
    •  勇哥,很想停止
       发布于 2020-09-29 10:17:07  回复该评论
    • 请参考下面两个贴子,可以解决你说的问题:
      http://www.skcircle.com/?id=1428
      http://www.skcircle.com/?id=1427

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

会员中心
搜索
«   2021年2月   »
1234567
891011121314
15161718192021
22232425262728
网站分类
标签列表
最新留言
    热门文章 | 热评文章 | 随机文章
文章归档
友情链接
  • 订阅本站的 RSS 2.0 新闻聚合
  • 扫描加本站机器视觉QQ群,验证答案为:halcon勇哥的机器视觉
  • 扫描加站长微信:站长微信:abc496103864
  • 扫描加站长QQ:
  • 扫描赞赏本站:

Powered By Z-BlogPHP 1.6.0 Valyria

Copyright Your skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864