機器視覺,運用Halcon識別QR Code並解碼讀取字符串

項目地址:
https://gitee.com/wanghaoli/Halcon_QrCode

項目運行程序exe根目錄截圖:
Halcon程序運行是需要證書的,在license裡面,參考截圖裡面的程序dll,需要都要放在exe根目錄裡面,不然運行會報錯
在這裏插入圖片描述
在這裏插入圖片描述

程序識別效果:
光線很暗的情況下,也可以正確識別
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
qr二維碼尺寸比較小時,也可以正確識別
在這裏插入圖片描述
在這裏插入圖片描述

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

namespace WindowsFormsApp_MachineVision
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //ECC200二維碼識別(經測試,推薦用此方法,識別率高)
        static HDevelopExport_ECC200 hd = new HDevelopExport_ECC200();

        //ecc200二維碼
        static HDevelopExport_ECC200_Simple ecc200 = new HDevelopExport_ECC200_Simple();

        //qr碼識別
        //static HDevelopExport_QR qr = new HDevelopExport_QR();
        static HDevelopExport_QR02 qr = new HDevelopExport_QR02();

        private void button1_Click(object sender, EventArgs e)
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                try
                {
                    //HDevelopExport_QR qr = new HDevelopExport_QR();
                    HTuple _window = hWindowControl1.HalconWindow;
                
                    //識別字母
                    //HDevelopExport2 hd = new HDevelopExport2();
                    //hd.RunHalcon(_window);

                    //ecc200二維碼 
                    //C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_cpu_001.png
                    //hd.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_cpu_001.png";
                    //背景黑暗
                    //hd.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_cpu_006.png";
                    //hd.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_disturbed_008.png";
                    //光纖幹擾識別參數配置和小尺寸識別參數不兼容,互相導致識別不出
                    //hd.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_contrast_variations_05.png";
                    //小尺寸識別
                    //hd.ImgPath = "d:/Desktop/2D_code/ecc200/ECC200_03.jpg";
                    //hd.ImgPath = "d:/Desktop/2D_code/ecc200/ECC200_05.jpg";
                    //hd.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/gs1datamatrix/gs1datamatrix_generated_01.png";
                    //幹擾多,識別報錯  
                    //hd.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_damaged_finder_pattern_06.png";
                    //光纖很暗黑
                    //hd.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_disturbed_011.png";
                    //有幹擾
                    //hd.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_disturbed_017.png";
                    //點狀
                    //hd.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_to_preprocess_003.png";
                    //hd.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_to_preprocess_004.png";
                    //hd.ImgPath = textBox1.Text.Trim()?.Replace(@"\","/");
                    //hd.RunHalcon(_window);

                    //ecc200二維碼
                    HDevelopExport_ECC200_Simple ecc200 = new HDevelopExport_ECC200_Simple();
                    ////ecc200.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_disturbed_017.png";
                    ////ecc200.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_disturbed_008.png";
                    //ecc200.ImgPath = "d:/Desktop/2D_code/ecc200/ECC200_03.jpg";
                    //點狀
                    //ecc200.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_to_preprocess_003.png";
                    //模糊,灰色背景
                    //ecc200.ImgPath = "C:/Users/Public/Documents/MVTec/HALCON-18.05-Progress/examples/images/datacode/ecc200/ecc200_to_preprocess_004.png";
                    //ecc200.RunHalcon(_window);

                    //qr code識別
                    qr.ImgPath = textBox1.Text.Trim()?.Replace(@"\", "/");
                    qr.RunHalcon(_window);
                }
                catch (Exception ex)
                {
                    ShowMsg($"異常:{ex.Message} {ex.InnerException?.Message}");
                }

                stopwatch.Stop();
                ShowMsg($"識別耗時:{stopwatch.ElapsedMilliseconds}毫秒");
            });
        }

        /// <summary>
        /// 顯示識別信息
        /// </summary>
        /// <param name="msg"></param>
        public static void ShowMsg(string msg)
        {
            var formObj = Program.form1.richTextBox1;
            formObj.BeginInvoke(new Action(() =>
            {
                if (string.IsNullOrEmpty(formObj.Text))
                {
                    formObj.AppendText(msg);
                }
                else
                {
                    formObj.AppendText("\r"+msg);
                }               
            }));
        }

        private void textBox1_Enter(object sender, EventArgs e)
        {
            textBox1.Text = "";
        }
    }
}

//
// File generated by HDevelop for HALCON/.NET (C#) Version 18.11.0.1
// Non-ASCII strings in this file are encoded in UTF-8.
// 
// Please note that non-ASCII characters in string constants are exported
// as octal codes in order to guarantee that the strings are correctly
// created on all systems, independent on any compiler settings.
// 
// Source files with different encoding should not be mixed in one project.
//
//  This file is intended to be used with the HDevelopTemplate or
//  HDevelopTemplateWPF projects located under %HALCONEXAMPLES%\c#

using System;
using System.Windows.Forms;
using HalconDotNet;
namespace WindowsFormsApp_MachineVision
{
    public partial class HDevelopExport_QR02
    {
        public HTuple hv_ExpDefaultWinHandle;

        /// <summary>
        /// 圖片路徑
        /// </summary>
        public string ImgPath { get; set; }
 
        // Chapter: Graphics / Text
        // Short Description: This procedure writes a text message. 
        public void disp_message(HTuple hv_WindowHandle, HTuple hv_String, HTuple hv_CoordSystem,
            HTuple hv_Row, HTuple hv_Column, HTuple hv_Color, HTuple hv_Box)
        {
            // Local iconic variables 
            // Local control variables
            HTuple hv_GenParamName = new HTuple(), hv_GenParamValue = new HTuple();
            HTuple hv_Color_COPY_INP_TMP = new HTuple(hv_Color);
            HTuple hv_Column_COPY_INP_TMP = new HTuple(hv_Column);
            HTuple hv_CoordSystem_COPY_INP_TMP = new HTuple(hv_CoordSystem);
            HTuple hv_Row_COPY_INP_TMP = new HTuple(hv_Row);

            // Initialize local and output iconic variables 
            try
            {
                //This procedure displays text in a graphics window.
                //
                //Input parameters:
                //WindowHandle: The WindowHandle of the graphics window, where
                //   the message should be displayed
                //String: A tuple of strings containing the text message to be displayed
                //CoordSystem: If set to 'window', the text position is given
                //   with respect to the window coordinate system.
                //   If set to 'image', image coordinates are used.
                //   (This may be useful in zoomed images.)
                //Row: The row coordinate of the desired text position
                //   A tuple of values is allowed to display text at different
                //   positions.
                //Column: The column coordinate of the desired text position
                //   A tuple of values is allowed to display text at different
                //   positions.
                //Color: defines the color of the text as string.
                //   If set to [], '' or 'auto' the currently set color is used.
                //   If a tuple of strings is passed, the colors are used cyclically...
                //   - if |Row| == |Column| == 1: for each new textline
                //   = else for each text position.
                //Box: If Box[0] is set to 'true', the text is written within an orange box.
                //     If set to' false', no box is displayed.
                //     If set to a color string (e.g. 'white', '#FF00CC', etc.),
                //       the text is written in a box of that color.
                //     An optional second value for Box (Box[1]) controls if a shadow is displayed:
                //       'true' -> display a shadow in a default color
                //       'false' -> display no shadow
                //       otherwise -> use given string as color string for the shadow color
                //
                //It is possible to display multiple text strings in a single call.
                //In this case, some restrictions apply:
                //- Multiple text positions can be defined by specifying a tuple
                //  with multiple Row and/or Column coordinates, i.e.:
                //  - |Row| == n, |Column| == n
                //  - |Row| == n, |Column| == 1
                //  - |Row| == 1, |Column| == n
                //- If |Row| == |Column| == 1,
                //  each element of String is display in a new textline.
                //- If multiple positions or specified, the number of Strings
                //  must match the number of positions, i.e.:
                //  - Either |String| == n (each string is displayed at the
                //                          corresponding position),
                //  - or     |String| == 1 (The string is displayed n times).
                //
                //
                //Convert the parameters for disp_text.
                if ((int)((new HTuple(hv_Row_COPY_INP_TMP.TupleEqual(new HTuple()))).TupleOr(
                    new HTuple(hv_Column_COPY_INP_TMP.TupleEqual(new HTuple())))) != 0)
                {
                    hv_Color_COPY_INP_TMP.Dispose();
                    hv_Column_COPY_INP_TMP.Dispose();
                    hv_CoordSystem_COPY_INP_TMP.Dispose();
                    hv_Row_COPY_INP_TMP.Dispose();
                    hv_GenParamName.Dispose();
                    hv_GenParamValue.Dispose();
                    return;
                }
                if ((int)(new HTuple(hv_Row_COPY_INP_TMP.TupleEqual(-1))) != 0)
                {
                    hv_Row_COPY_INP_TMP.Dispose();
                    hv_Row_COPY_INP_TMP = 12;
                }
                if ((int)(new HTuple(hv_Column_COPY_INP_TMP.TupleEqual(-1))) != 0)
                {
                    hv_Column_COPY_INP_TMP.Dispose();
                    hv_Column_COPY_INP_TMP = 12;
                }
                //
                //Convert the parameter Box to generic parameters.
                hv_GenParamName.Dispose();
                hv_GenParamName = new HTuple();
                hv_GenParamValue.Dispose();
                hv_GenParamValue = new HTuple();
              
                //Restore default CoordSystem behavior.
                if ((int)(new HTuple(hv_CoordSystem_COPY_INP_TMP.TupleNotEqual("window"))) != 0)
                {
                    hv_CoordSystem_COPY_INP_TMP.Dispose();
                    hv_CoordSystem_COPY_INP_TMP = "image";
                }
                //
                if ((int)(new HTuple(hv_Color_COPY_INP_TMP.TupleEqual(""))) != 0)
                {
                    //disp_text does not accept an empty string for Color.
                    hv_Color_COPY_INP_TMP.Dispose();
                    hv_Color_COPY_INP_TMP = new HTuple();
                }

                //HOperatorSet.DispText(hv_ExpDefaultWinHandle, hv_String, hv_CoordSystem_COPY_INP_TMP,
                //    hv_Row_COPY_INP_TMP, hv_Column_COPY_INP_TMP, hv_Color_COPY_INP_TMP, hv_GenParamName,
                //    hv_GenParamValue);

                //調整顯示位置
                //  HOperatorSet.DispText(hv_ExpDefaultWinHandle, hv_String, hv_CoordSystem_COPY_INP_TMP,
                //"top", "left", hv_Color_COPY_INP_TMP, hv_GenParamName,
                //hv_GenParamValue);
                //    HOperatorSet.DispText(hv_ExpDefaultWinHandle, hv_String, hv_CoordSystem_COPY_INP_TMP,
                //new HTuple(), new HTuple(), hv_Color_COPY_INP_TMP, hv_GenParamName,
                //hv_GenParamValue);

                //         HOperatorSet.DispText(hv_ExpDefaultWinHandle, hv_String, hv_CoordSystem_COPY_INP_TMP,
                //0, 0, hv_Color_COPY_INP_TMP, hv_GenParamName,
                //hv_GenParamValue);

                //設置數組多參數格式
                // (new HTuple("box_color")).TupleConcat("module_size_max"), (new HTuple(5)).TupleConcat(6)
                //            HOperatorSet.DispText(hv_ExpDefaultWinHandle, hv_String, hv_CoordSystem_COPY_INP_TMP,
                //0, 0, hv_Color_COPY_INP_TMP, "box_color", "white");
                HOperatorSet.DispText(hv_ExpDefaultWinHandle, hv_String, hv_CoordSystem_COPY_INP_TMP,
               0, 0, hv_Color_COPY_INP_TMP, 
               //消息框底色、內邊距
               (new HTuple("box_color")).TupleConcat("box_padding"), 
               (new HTuple("white")).TupleConcat(10));

                hv_Color_COPY_INP_TMP.Dispose();
                hv_Column_COPY_INP_TMP.Dispose();
                hv_CoordSystem_COPY_INP_TMP.Dispose();
                hv_Row_COPY_INP_TMP.Dispose();
                hv_GenParamName.Dispose();
                hv_GenParamValue.Dispose();
                return;
            }
            catch (HalconException HDevExpDefaultException)
            {

                hv_Color_COPY_INP_TMP.Dispose();
                hv_Column_COPY_INP_TMP.Dispose();
                hv_CoordSystem_COPY_INP_TMP.Dispose();
                hv_Row_COPY_INP_TMP.Dispose();
                hv_GenParamName.Dispose();
                hv_GenParamValue.Dispose();

                throw HDevExpDefaultException;
            }
        }

        // Local procedures 
        public void display_found_data_codes(HObject ho_SymbolXLDs, HTuple hv_WindowHandle,
            HTuple hv_DecodedDataStrings, HTuple hv_TitleMessage, HTuple hv_ResultMessage,
            HTuple hv_ColorDecodedStrings, HTuple hv_ColorResult)
        {
            // Local iconic variables 
            HObject ho_SymbolXLD = null;

            // Local control variables 
            HTuple hv_J = new HTuple(), hv_Row = new HTuple();
            HTuple hv_Column = new HTuple(), hv_Row1 = new HTuple();
            HTuple hv_Column1 = new HTuple(), hv_Width = new HTuple();
            HTuple hv_Height = new HTuple(), hv_Ascent = new HTuple();
            HTuple hv_Descent = new HTuple(), hv_TWidth = new HTuple();
            HTuple hv_THeight = new HTuple(), hv_DecodedData = new HTuple();
            HTuple hv_DecodedDataSubstrings = new HTuple(), hv_TPosRow = new HTuple();
            HTuple hv_TPosColumn = new HTuple();
            HTuple hv_DecodedDataStrings_COPY_INP_TMP = new HTuple(hv_DecodedDataStrings);

            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_SymbolXLD);
            try
            {
                //This procedure displays the results of the search for
                //2d data codes. The data strings are displayed accordingly
                //to their length so that the whole string is visible.
                //If the data strings are too long only the first 50 chars
                //are displayed.
                //
                //Input parameters are the XLD contours of the decoded
                //data symbols, the decoded data strings, the windowhandle,
                //a title message, a result message, the color of the decoded
                //strings and the color of the result message.
                //
                //Display the result of the search for each found data code
                for (hv_J = 0; (int)hv_J <= (int)((new HTuple(hv_DecodedDataStrings_COPY_INP_TMP.TupleLength()
                    )) - 1); hv_J = (int)hv_J + 1)
                {
                    //
                    //Display the XLD contour
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        ho_SymbolXLD.Dispose();
                        HOperatorSet.SelectObj(ho_SymbolXLDs, out ho_SymbolXLD, hv_J + 1);
                    }
                    hv_Row.Dispose(); hv_Column.Dispose();
                    HOperatorSet.GetContourXld(ho_SymbolXLD, out hv_Row, out hv_Column);
                    HOperatorSet.DispObj(ho_SymbolXLD, hv_ExpDefaultWinHandle);
                    //
                    //Display messages
                    //------------------
                    //Determine the length of the dislayed decoded data string
                    hv_Row1.Dispose(); hv_Column1.Dispose(); hv_Width.Dispose(); hv_Height.Dispose();
                    HOperatorSet.GetWindowExtents(hv_ExpDefaultWinHandle, out hv_Row1, out hv_Column1,
                        out hv_Width, out hv_Height);
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        hv_Ascent.Dispose(); hv_Descent.Dispose(); hv_TWidth.Dispose(); hv_THeight.Dispose();
                        HOperatorSet.GetStringExtents(hv_ExpDefaultWinHandle, hv_DecodedDataStrings_COPY_INP_TMP.TupleSelect(
                            hv_J), out hv_Ascent, out hv_Descent, out hv_TWidth, out hv_THeight);
                    }
                    if ((int)(new HTuple(hv_TWidth.TupleGreater(hv_Width))) != 0)
                    {
                        if (hv_DecodedDataStrings_COPY_INP_TMP == null)
                            hv_DecodedDataStrings_COPY_INP_TMP = new HTuple();
                        //hv_DecodedDataStrings_COPY_INP_TMP[hv_J] = (((hv_DecodedDataStrings_COPY_INP_TMP.TupleSelect(
                        //    hv_J))).TupleSubstr(0, 50)) + "...";

                        //whl新增
                        int len = hv_DecodedDataStrings_COPY_INP_TMP.ToString().Length;
                        if (len>50)
                        {
                            len = 50;
                        }
                        //hv_DecodedDataStrings_COPY_INP_TMP[hv_J] = (((hv_DecodedDataStrings_COPY_INP_TMP.TupleSelect(
                        //    hv_J))).TupleSubstr(0, len)) + "...";
                        hv_DecodedDataStrings_COPY_INP_TMP[hv_J] =
                            hv_DecodedDataStrings_COPY_INP_TMP.ToString().Substring(0, len)+"...";

                        using (HDevDisposeHelper dh = new HDevDisposeHelper())
                        {
                            hv_Ascent.Dispose(); hv_Descent.Dispose(); hv_TWidth.Dispose(); hv_THeight.Dispose();
                            HOperatorSet.GetStringExtents(hv_ExpDefaultWinHandle, hv_DecodedDataStrings_COPY_INP_TMP.TupleSelect(
                                hv_J), out hv_Ascent, out hv_Descent, out hv_TWidth, out hv_THeight);
                        }
                    }
                    //
                    //Split the decoded string in new lines for better readability
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        hv_DecodedData.Dispose();
                        HOperatorSet.TupleRegexpReplace(hv_DecodedDataStrings_COPY_INP_TMP.TupleSelect(
                            hv_J), (new HTuple("[\\r\\f,^#;]")).TupleConcat("replace_all"), "\n",
                            out hv_DecodedData);
                    }
                    hv_DecodedDataSubstrings.Dispose();
                    HOperatorSet.TupleSplit(hv_DecodedData, "\n", out hv_DecodedDataSubstrings);
                    //
                    //Determine the position of the displayed decoded data string
                    if ((int)((new HTuple(((hv_Row.TupleMax())).TupleGreater(420))).TupleAnd(
                        new HTuple(((hv_Row.TupleMin())).TupleLess(40)))) != 0)
                    {
                        hv_TPosRow.Dispose();
                        using (HDevDisposeHelper dh = new HDevDisposeHelper())
                        {
                            hv_TPosRow = (hv_Row.TupleMax()
                                ) - 30;
                        }
                    }
                    else if ((int)(new HTuple(((hv_Row.TupleMax())).TupleGreater(420))) != 0)
                    {
                        hv_TPosRow.Dispose();
                        using (HDevDisposeHelper dh = new HDevDisposeHelper())
                        {
                            hv_TPosRow = (hv_Row.TupleMin()
                                ) - 20;
                        }
                    }
                    else if ((int)(new HTuple(((hv_Row.TupleMin())).TupleLess(100))) != 0)
                    {
                        hv_TPosRow.Dispose();
                        using (HDevDisposeHelper dh = new HDevDisposeHelper())
                        {
                            hv_TPosRow = (hv_Row.TupleMax()
                                ) - 20;
                        }
                    }
                    else
                    {
                        hv_TPosRow.Dispose();
                        using (HDevDisposeHelper dh = new HDevDisposeHelper())
                        {
                            hv_TPosRow = (hv_Row.TupleMax()
                                ) - 30;
                        }
                    }
                    hv_TPosColumn.Dispose();
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        hv_TPosColumn = (((((((((hv_Column.TupleMean()
                            ) - (hv_TWidth / 2))).TupleConcat((hv_Width - 32) - hv_TWidth))).TupleMin())).TupleConcat(
                            12))).TupleMax();
                    }
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        disp_message(hv_ExpDefaultWinHandle, hv_DecodedDataStrings_COPY_INP_TMP.TupleSelect(
                            hv_J), "image", hv_TPosRow, hv_TPosColumn, hv_ColorDecodedStrings, "true");
                    }
                }
                ////
                ////Display the title message and result message
                //disp_message(hv_ExpDefaultWinHandle, hv_TitleMessage, "window", 12, 12, "black",
                //    "true");
                //disp_message(hv_ExpDefaultWinHandle, hv_ResultMessage, "window", 40, 12, hv_ColorResult,
                //    "true");
                ho_SymbolXLD.Dispose();

                hv_DecodedDataStrings_COPY_INP_TMP.Dispose();
                hv_J.Dispose();
                hv_Row.Dispose();
                hv_Column.Dispose();
                hv_Row1.Dispose();
                hv_Column1.Dispose();
                hv_Width.Dispose();
                hv_Height.Dispose();
                hv_Ascent.Dispose();
                hv_Descent.Dispose();
                hv_TWidth.Dispose();
                hv_THeight.Dispose();
                hv_DecodedData.Dispose();
                hv_DecodedDataSubstrings.Dispose();
                hv_TPosRow.Dispose();
                hv_TPosColumn.Dispose();

                return;
            }
            catch (HalconException HDevExpDefaultException)
            {
                ho_SymbolXLD.Dispose();

                hv_DecodedDataStrings_COPY_INP_TMP.Dispose();
                hv_J.Dispose();
                hv_Row.Dispose();
                hv_Column.Dispose();
                hv_Row1.Dispose();
                hv_Column1.Dispose();
                hv_Width.Dispose();
                hv_Height.Dispose();
                hv_Ascent.Dispose();
                hv_Descent.Dispose();
                hv_TWidth.Dispose();
                hv_THeight.Dispose();
                hv_DecodedData.Dispose();
                hv_DecodedDataSubstrings.Dispose();
                hv_TPosRow.Dispose();
                hv_TPosColumn.Dispose();

                throw HDevExpDefaultException;
            }
        }

        // Main procedure 
        private void action()
        {
            // Local iconic variables 
            HObject ho_Image, ho_SymbolXLDs = null;
            // Local control variables 
            //HTuple hv_ImageFiles = new HTuple(), hv_ImageNum = new HTuple();
            HTuple hv_WindowHandle = new HTuple(), hv_DataCodeHandle = new HTuple();
            HTuple hv_ResultHandles = new HTuple(), hv_DecodedDataStrings = new HTuple();
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_Image);
            HOperatorSet.GenEmptyObj(out ho_SymbolXLDs);
            try
            {
                //***********************************************************
                //This example program demonstrates how to read QR codes with
                //manually adapted parameter settings to optimize the
                //recognition and runtime.
                //
                //The following parameters are set manually:
                //   - 'version'
                //   - 'model_type'
                //   - 'module_size_min'
                //   - 'module_size_max'
                //   - 'module_gap'
                //   - 'mirrored'
                //   - 'contrast_min'
                //
                //************************************************************
                //
                //Initialize image path and visual settings
                //dev_update_off();

                //dev_close_window(...);
                //hv_ImageFiles.Dispose();
                //hv_ImageFiles = "datacode/qrcode/qr_workpiece_";
                //hv_ImageNum.Dispose();
                //hv_ImageNum = 9;
                //read_image (Image, ImageFiles + '07')
                ho_Image.Dispose();
                //HOperatorSet.ReadImage(out ho_Image, "C:/Users/Public/Documents/MVTec/HALCON-18.11-Progress/examples/images/datacode/qrcode/qr_workpiece_01.png");
                HOperatorSet.ReadImage(out ho_Image, ImgPath);

                hv_WindowHandle.Dispose();
                //dev_open_window_fit_image(ho_Image, 0, 0, -1, -1, out hv_WindowHandle);

                HOperatorSet.SetLineWidth(hv_ExpDefaultWinHandle, 3);
                HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "green");

                //
                //Step 1: Create a 2d data code model
                //----------------------------------------------------
                //Create a 2d data code model of the 2d data code class
                //'Data Matrix ECC 200'. The operator returns a handle to
                //the 2d data code model which can be used for all further
                //operations on the data code.
                hv_DataCodeHandle.Dispose();
                //HOperatorSet.CreateDataCode2dModel("QR Code", new HTuple(), new HTuple(), out hv_DataCodeHandle);
                HOperatorSet.CreateDataCode2dModel("QR Code", "default_parameters", "enhanced_recognition", out hv_DataCodeHandle);

                //
                //Step 2: Adapt some parameters manually
                //----------------------------------------------------
                //Set some selected parameters of the 2d data code model
                //in order to adapt the model to the symbol appearance.
                //HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle, "version", 1);
                //HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle, "model_type", 2);
                //HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle, (new HTuple("module_size_min")).TupleConcat(
                //    "module_size_max"), (new HTuple(5)).TupleConcat(6));
                //HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle, "module_gap", "no");
                //HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle, "mirrored", "no");
                //HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle, "contrast_min", 10);
                HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle, "small_modules_robustness", "high");

                //
                //Step 3: Read the data codes
                //----------------------------------------------------
                //Search and read the data codes in each image and
                //display the decoded string for each found data code
                //for Index := 1 to ImageNum by 1
                //*     read_image (Image, ImageFiles + Index$'.2d')
                HOperatorSet.DispObj(ho_Image, hv_ExpDefaultWinHandle);
                //
                //Find and decode the data codes and measure the runtime
                //count_seconds (T1)
                ho_SymbolXLDs.Dispose(); hv_ResultHandles.Dispose(); hv_DecodedDataStrings.Dispose();
                //HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
                //    new HTuple(), new HTuple(), out hv_ResultHandles, out hv_DecodedDataStrings);
                HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle, "train", "all", out hv_ResultHandles, out hv_DecodedDataStrings);

                //顯示識別字符串
                Form1.ShowMsg(hv_DecodedDataStrings);
 
                //display_found_data_codes(ho_SymbolXLDs, hv_WindowHandle, hv_DecodedDataStrings,
                //    new HTuple(), new HTuple(), "green", "black");
                //#000000字體顏色
                display_found_data_codes(ho_SymbolXLDs, hv_WindowHandle, hv_DecodedDataStrings,
               new HTuple(), new HTuple(), "#000000", "black");

            }
            catch (HalconException HDevExpDefaultException)
            {
                ho_Image.Dispose();
                ho_SymbolXLDs.Dispose();

                //hv_ImageFiles.Dispose();
                //hv_ImageNum.Dispose();
                hv_WindowHandle.Dispose();
                hv_DataCodeHandle.Dispose();
                hv_ResultHandles.Dispose();
                hv_DecodedDataStrings.Dispose();

                throw HDevExpDefaultException;
            }
            ho_Image.Dispose();
            ho_SymbolXLDs.Dispose();

            //hv_ImageFiles.Dispose();
            //hv_ImageNum.Dispose();
            hv_WindowHandle.Dispose();
            hv_DataCodeHandle.Dispose();
            hv_ResultHandles.Dispose();
            hv_DecodedDataStrings.Dispose();

        }

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

        public void RunHalcon(HTuple Window)
        {
            hv_ExpDefaultWinHandle = Window;

            //設置字體
            //HTuple hv_Font, hv_FontWithSize;
            //HOperatorSet.QueryFont(hv_ExpDefaultWinHandle, out hv_Font);
            ////Specify font name and size 
            ////hv_FontWithSize = (hv_Font.TupleSelect(0)) + "-20";
            ////hv_FontWithSize = "宋體-20";
            ////宋體
            //hv_FontWithSize = (hv_Font.TupleSelect(53)) + "-20";
            //HOperatorSet.SetFont(hv_ExpDefaultWinHandle, hv_FontWithSize);

            //設置字體
            //字體名稱-樣式粗細-字體大小:宋體-Bold-20或宋體-20          
            HOperatorSet.SetFont(hv_ExpDefaultWinHandle, "宋體-20");
            action();
        }
    }
}

下面有個ECC200二維碼識別類:
如果要替換成識別ECC200二維碼,則直接將QR識別類替換為此類就好

// ECC200二維碼識別
// File generated by HDevelop for HALCON/.NET (C#) Version 18.05.0.1
//
//  This file is intended to be used with the HDevelopTemplate or
//  HDevelopTemplateWPF projects located under %HALCONEXAMPLES%\c#

using System;
using System.Windows.Forms;
using HalconDotNet;

namespace WindowsFormsApp_MachineVision
{

    public class HDevelopExport_ECC200
    {
        public HTuple hv_ExpDefaultWinHandle;

        /// <summary>
        /// 識別的圖片地址
        /// </summary>
        public string ImgPath { get; set; }

        //public void HDevelopStop()
        //{
        //    MessageBox.Show("Press button to continue", "Program stop");
        //}

        /// <summary>
        /// 是否支持小尺寸識別,true是
        /// </summary>
        /// <param name="minSizeEnabled"></param>
        //private void action(bool minSizeEnabled = false)
        private void action()
        {
            // Local iconic variables 
            HObject ho_Image = null, ho_SymbolXLDs1 = null;
            // Local control variables 
            HTuple hv_WindowHandle1 = new HTuple(), hv_Row = new HTuple();
            HTuple hv_Column = new HTuple(), hv_WidthOriginal = new HTuple();
            HTuple hv_HeightOriginal = new HTuple(), hv_DataCodeHandle1 = new HTuple();
            HTuple hv_ResultHandles1 = new HTuple(), hv_DecodedDataStrings1 = new HTuple();
            // Initialize local and output iconic variables 
            //HOperatorSet.GenEmptyObj(out ho_Image);
            //HOperatorSet.GenEmptyObj(out ho_SymbolXLDs1);

            //This example program shows how to find and decode ECC200 symbols
            //that have a very small module size.
            //
            //To read these symbols successfully, the parameter
            //'small_modules_robustness', which is set to 'low' by default, must
            //be set to 'high'. Additionally, the parameter 'module_size_min'
            //has to be set to the minimum expected module size, in this case
            //to the value 1.
            //In order to show the influence of the parameter 'small_modules_robustness'
            //on the data code reader, the operator find_data_code_2d is called
            //twice with different settings of the regarding parameter.
            //
            //dev_update_off();
            //dev_close_window(...);
            //ho_Image.Dispose();

            //whl調整
            //HOperatorSet.ReadImage(out ho_Image, "datacode/ecc200/ecc200_cpu_001");
            HOperatorSet.ReadImage(out ho_Image, ImgPath);

            //ZoomFactorStart := 0.8
            //* zoom_image_factor (Image, ImageZoomed, ZoomFactorStart, ZoomFactorStart, 'constant')
            //*dev_open_window_fit_image(ImageZoomed, 0, 0, -1, -1, WindowHandle1)
            hv_WindowHandle1.Dispose();
            //dev_open_window_fit_image(ho_Image, 0, 0, -1, -1, out hv_WindowHandle1);

            //
            //Open a second window with in the same size as the first window
            hv_Row.Dispose(); hv_Column.Dispose(); hv_WidthOriginal.Dispose(); hv_HeightOriginal.Dispose();
            HOperatorSet.GetWindowExtents(hv_ExpDefaultWinHandle, out hv_Row, out hv_Column,
                out hv_WidthOriginal, out hv_HeightOriginal);
            //dev_open_window_fit_size (0, WidthOriginal + 10, WidthOriginal, HeightOriginal, -1, -1, WindowHandle2)

            //設置識別框線寬度
            HOperatorSet.SetLineWidth(hv_ExpDefaultWinHandle, 2);
            //設置識別框顏色
            HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "green");

            //
            //Create two ECC 200 data code models for 'small_modules_robustness' set to 'high'
            //and 'small_modules_robustness' set to 'low', respectively (set 'module_size_min' to 1).
            //create_data_code_2d_model ('Data Matrix ECC 200', ['small_modules_robustness','module_size_min'], ['high',1], DataCodeHandle1)
            hv_DataCodeHandle1.Dispose();
            //maximum_recognition*enhanced_recognition
            //HOperatorSet.CreateDataCode2dModel("Data Matrix ECC 200", "default_parameters", "maximum_recognition", out hv_DataCodeHandle1);
            HOperatorSet.CreateDataCode2dModel("Data Matrix ECC 200", "default_parameters", "enhanced_recognition", out hv_DataCodeHandle1);

            //*對比度寬容:高   
            HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle1, "contrast_tolerance", "high");
            //提高:識別小尺寸
            //HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle1, "module_size_min", 1);
            //if (minSizeEnabled)
            //{
            //    //*尺寸寬容:高 (兼容極小尺寸識別)
            //    HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle1, "small_modules_robustness", "high");
            //}
            //*尺寸寬容:高 (兼容極小尺寸識別)
            //HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle1, "small_modules_robustness", "high");

            //create_data_code_2d_model ('Data Matrix ECC 200', ['small_modules_robustness','module_size_min'], ['low',1], DataCodeHandle2)

            //222
            //ho_SymbolXLDs1.Dispose();
            //hv_ResultHandles1.Dispose();
            //hv_DecodedDataStrings1.Dispose();

            //設置"train", "all"是邊識別,邊的調整參數
            HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs1, hv_DataCodeHandle1, "train", "all", out hv_ResultHandles1, out hv_DecodedDataStrings1);
            //HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs1, hv_DataCodeHandle1, new HTuple(), new HTuple(), out hv_ResultHandles1, out hv_DecodedDataStrings1);

            //識別的字符串
            Form1.ShowMsg(hv_DecodedDataStrings1);
            HOperatorSet.SetLineWidth(hv_ExpDefaultWinHandle, 2);
            HOperatorSet.DispObj(ho_Image, hv_ExpDefaultWinHandle);
            //顯示識別框
            HOperatorSet.DispObj(ho_SymbolXLDs1, hv_ExpDefaultWinHandle);

            //*     disp_message (WindowHandle1, Message + 'high', 'window', 4, 4, 'black', 'true')
            //disp_results(ho_SymbolXLDs1, hv_WindowHandle1, hv_DataCodeHandle1, hv_ResultHandles1,
            //    hv_DecodedDataStrings1); 
            //dev_close_window(...);
            ho_Image.Dispose();
            ho_SymbolXLDs1.Dispose();

            hv_WindowHandle1.Dispose();
            hv_Row.Dispose();
            hv_Column.Dispose();
            hv_WidthOriginal.Dispose();
            hv_HeightOriginal.Dispose();
            hv_DataCodeHandle1.Dispose();
            hv_ResultHandles1.Dispose();
            hv_DecodedDataStrings1.Dispose();
        }

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

        /// <summary>
        ///  
        /// </summary>
        /// <param name="Window"></param>
        /// <param name="minSizeEnabled">是否支持小尺寸識別,true是</param>
        public void RunHalcon(HTuple Window)   //, bool minSizeEnabled = false
        {
            hv_ExpDefaultWinHandle = Window;
            action();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章