HDevelopCodeLearn.cs 9.6 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace URSoldering.DeviceLibrary
{
    //
    //  File generated by HDevelop for HALCON/DOTNET (C#) Version 12.0
    //
    //  This file is intended to be used with the HDevelopTemplate or
    //  HDevelopTemplateWPF projects located under %HALCONEXAMPLES%\c#

    using System;
    using System.Threading;
    using System.Windows.Forms;
    using HalconDotNet;
    using URSoldering.Common;

    public class HDevelopCodeLearn
    {
        public static HWindow hv_ExpDefaultWinHandle;
        public static HTuple hv_AcqHandle = null;
        public static void HDevelopStop()
        {
            //MessageBox.Show("Press button to continue", "Program stop");
        }



        public static void InitHalcon()
        {
            // Default settings used in HDevelop 
            HOperatorSet.SetSystem("width", 512);
            HOperatorSet.SetSystem("height", 512);
        }

        public static void RunHalcon(HWindow Window, string camerName, string codeType, string paramPath, int codeCount)
        {
            InitHalcon();
            hv_ExpDefaultWinHandle = Window;
            action(camerName, codeType, paramPath, codeCount);
        }

        private static bool  OpenCamera(string cameraName)
        {
            try
            {   //[1] HD USB Camera
                //HOperatorSet.OpenFramegrabber("GigEVision", 0, 0, 0, 0, 0, 0, "default", -1,
                //    "default", -1, "false", "default", cameraName, 0, -1, out hv_AcqHandle);
                HOperatorSet.OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "rgb",
                     -1, "false", "default", "[1] HD USB Camera", 0, -1, out hv_AcqHandle);
                return true;
            }
            catch (Exception ex)
            {
                LogUtil.error("打开摄像机失败:" + ex.ToString() + ",调用关闭摄像头");
                CloseCamera(cameraName);
                return false;
            }
        }
        private static void  CloseCamera(string cameraName)
        {
            try
            {
                HOperatorSet.CloseFramegrabber(hv_AcqHandle);
                hv_AcqHandle = null;
            }
            catch (Exception ex)
            {
                LogUtil.error("关闭摄像机失败:" + ex.ToString());
            }
        }

        public static bool IsRun = false;
        // Main procedure 
        private static bool  action(string cameraName, string codeType, string paramPath, int codeCount)
        {
            IsRun = true;
            IsLearnEnd = false;
            IsTestEnd = false;
            try
            {
                HTuple hv_code_type = codeType;
                HTuple hv_model_path = paramPath;

                HObject ho_Image = null, ho_SymbolXLDs = null;

                HTuple hv_train_first = null, /*hv_AcqHandle = null,*/ hv_DataCodeHandle = null;
                HTuple hv_ResultHandles = new HTuple(), hv_DecodedDataStrings = new HTuple();
                HTuple hv_GenParamNames = new HTuple(), hv_ModelBeforeTraining = new HTuple();
                // Initialize local and output iconic variables 
                HOperatorSet.GenEmptyObj(out ho_Image);
                HOperatorSet.GenEmptyObj(out ho_SymbolXLDs);
                //Image Acquisition 04: Code generated by Image Acquisition 04
                //Image Acquisition 01: Code generated by Image Acquisition 01

                //hv_code_type = "Data Matrix ECC 200";
                //hv_model_path = ("E:/BaiduNetdiskDownload/" + hv_code_type) + ".dcm";
                hv_train_first = 1;
                if (!OpenCamera(cameraName))
                {
                    return false ;
                }

                //HOperatorSet.GrabImageStart(hv_AcqHandle, -1);
                HOperatorSet.CreateDataCode2dModel(hv_code_type, new HTuple(), new HTuple(),
                    out hv_DataCodeHandle);
                //set_data_code_2d_param (DataCodeHandle, 'strict_model', 'yes')
                //set_data_code_2d_param (DataCodeHandle, 'persistence', 0)
                //set_data_code_2d_param (DataCodeHandle, 'polarity', 'light_on_dark')
                List<string> findCode = new List<string>();
                if ((int)(hv_train_first) != 0)
                {
                    while (findCode.Count < codeCount&&IsLearnEnd.Equals(false ))
                    {
                        ho_Image.Dispose();
                        HOperatorSet.GrabImageAsync(out ho_Image, hv_AcqHandle, -1);
                        //Image Acquisition 04: Do something

                        //write_image (Image, 'jpeg', 0, 'E:/BaiduNetdiskDownload/fuba2.jpg')
                        if (ho_Image != null)
                        {
                            ho_SymbolXLDs.Dispose();
                            HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
                                "train", "all", out hv_ResultHandles, out hv_DecodedDataStrings);
                            if ((int)(new HTuple((new HTuple(hv_DecodedDataStrings.TupleLength())).TupleNotEqual(
                                0))) != 0)
                            {
                                HOperatorSet.QueryDataCode2dParams(hv_DataCodeHandle, "get_model_params",
                                    out hv_GenParamNames);
                                HOperatorSet.GetDataCode2dParam(hv_DataCodeHandle, hv_GenParamNames, out hv_ModelBeforeTraining);
                                HDevelopStop();
                                string[] resultList = hv_DecodedDataStrings.SArr;
                                foreach (string str in resultList)
                                {
                                    if (!findCode.Contains(str))
                                    {
                                        LogUtil.info("["+cameraName + "][" + codeType + "]学习【" + str+"】");
                                        findCode.Add(str);
                                    }
                                }
                            }
                            ShowImage(ho_Image,ho_SymbolXLDs);

                        }
                        Thread.Sleep(500);
                    }

                    //*参数写入文件
                    LogUtil.info("["+cameraName + "][" + codeType + "]保存参数到文件【" + paramPath+"】");
                    HOperatorSet.WriteDataCode2dModel(hv_DataCodeHandle, hv_model_path);
                    HOperatorSet.ClearDataCode2dModel(hv_DataCodeHandle);
                }

                //Read the previously saved data code model
                findCode = new List<string>();
                HOperatorSet.ReadDataCode2dModel(hv_model_path, out hv_DataCodeHandle);
                while (findCode.Count < codeCount&&IsTestEnd.Equals(false ))
                {
                    ho_Image.Dispose();
                    HOperatorSet.GrabImageAsync(out ho_Image, hv_AcqHandle, -1);
                    //Image Acquisition 04: Do something

                    //write_image (Image, 'jpeg', 0, 'E:/BaiduNetdiskDownload/fuba2.jpg')
                    if (ho_Image != null)
                    {
                        ho_SymbolXLDs.Dispose();
                        HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
                            "stop_after_result_num", 5, out hv_ResultHandles, out hv_DecodedDataStrings);
                        ShowImage(ho_Image,ho_SymbolXLDs);
                        if ((int)(new HTuple((new HTuple(hv_DecodedDataStrings.TupleLength())).TupleNotEqual(
                             0))) != 0)
                        {
                            string[] resultList = hv_DecodedDataStrings.SArr;
                            foreach (string str in resultList)
                            {
                                if (!findCode.Contains(str))
                                {
                                    findCode.Add(str);
                                    LogUtil.info("[" + cameraName + "][" + codeType + "]检测到【" + str + "】");
                                }
                            }
                        }
                    }
                    Thread.Sleep(500);
                }

                HOperatorSet.ClearDataCode2dModel(hv_DataCodeHandle);

                CloseCamera(cameraName);
                ho_Image.Dispose();
                ho_SymbolXLDs.Dispose();
                IsRun = false;
                return true;
            }catch(Exception ex)
            {
                LogUtil.error("出错了:" + ex.ToString());
                CloseCamera(cameraName);
                IsRun = false;
                return false; 
            }
        }
        public static bool IsTestEnd = false;
        public static bool IsLearnEnd = false;
        public static void StopLearn()
        {
            IsTestEnd = true;
            IsLearnEnd = true; 
        }

        private static int dWidth = 0;
        private static int dHeight = 0;
        private static void ShowImage(HObject ho_Image,HObject ho_SymbolXLDs)
        {
            if (dWidth <= 0)
            {
                HTuple width, height;
                //int dWidth = 0; int dHeight = 0;
                HOperatorSet.GetImageSize(ho_Image, out width, out height);

                dWidth = (int)width.D;
                dHeight = (int)height.D;
                hv_ExpDefaultWinHandle.SetPart(0, 0, dHeight, dWidth);
            }

            HOperatorSet.DispObj(ho_Image, hv_ExpDefaultWinHandle);
            HOperatorSet.DispObj(ho_SymbolXLDs, hv_ExpDefaultWinHandle);
        }

    }


}