• C#二维码识别


    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using HalconDotNet;
    using System.Threading;
    
    namespace HDevQRTest.UIX64
    {
        
        public partial class Form1 : Form
        {
    
            private SynchronizationContext _SynCtx = null;
    
            HTuple _FatherWindow =null;
            private bool _Enable = false;                           //正常测试线程停止标记
            public Form1()
            {
                InitializeComponent();
                //
                _FatherWindow = pictureBox1.Handle;
                _SynCtx = System.Threading.SynchronizationContext.Current;
            }
    
            public void Do()
            {
                try
                {
                    #region
                    // Local iconic variables 
                    Console.WriteLine("任务启动!");
                    HObject ho_Image = null, ho_SymbolXLDs = null;
    
                    // Local control variables 
                    HTuple hv_WindowHandle = null;
                    HTuple hv_AcqHandle = null, hv_DataCodeHandle = null;
                    HTuple hv_ResultHandles = new HTuple();
                    HTuple hv_DecodedDataStrings = new HTuple();
                    // Initialize local and output iconic variables 
                    HOperatorSet.GenEmptyObj(out ho_Image);
                    HOperatorSet.GenEmptyObj(out ho_SymbolXLDs);
                    //Image Acquisition 01: Code generated by Image Acquisition 01
                    //Image Acquisition 01: Attention: The initialization may fail in case parameters need to
                    //Image Acquisition 01: be set in a specific order (e.g., image resolution vs. offset).
                    HOperatorSet.OpenFramegrabber("GigEVision2", 0, 0, 0, 0, 0, 0, "progressive",
                        8, "rgb", -1, "false", "default", "c42f90f5f892_Hikvision_MVCA06010GC", 0,
                        -1, out hv_AcqHandle);
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "DeviceUserID", "");
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "RegionSelector", "Region0");
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "Width", 1280);
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "Height", 1280);
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "OffsetX", 952);
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "OffsetY", 684);
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "PixelFormat", "YUV422_8");
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "TestPattern", "Off");
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "AcquisitionMode", "Continuous");
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "AcquisitionBurstFrameCount",
                        1);
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "AcquisitionFrameRate", 7.4);
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "AcquisitionFrameRateEnable",
                        1);
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "ExposureMode", "Timed");
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "ExposureAuto", "Continuous");
                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "TriggerSelector", "FrameBurstStart");
                    HOperatorSet.GrabImageStart(hv_AcqHandle, -1);
                    HOperatorSet.CreateDataCode2dModel("QR Code", new HTuple(), new HTuple(), out hv_DataCodeHandle);
                    if (HDevWindowStack.IsOpen())
                    {
                        HOperatorSet.CloseWindow(HDevWindowStack.Pop());
                    }
                    HOperatorSet.SetWindowAttr("background_color", "black");
    
                    HOperatorSet.OpenWindow(0, 0, this.pictureBox1.Width, this.pictureBox1.Height, _FatherWindow, "visible", "", out hv_WindowHandle);
    
                    HDevWindowStack.Push(hv_WindowHandle);
                    #endregion
                    while (_Enable)
                    {
                        ho_Image.Dispose();
                        HOperatorSet.GrabImageAsync(out ho_Image, hv_AcqHandle, -1);
                        ho_SymbolXLDs.Dispose();
                        HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
                            new HTuple(), new HTuple(), out hv_ResultHandles, out hv_DecodedDataStrings);
    
                        #region 调整图像大小
                        HTuple width = null, height = null;
    
                        //获取图像大小
                        HOperatorSet.GetImageSize(ho_Image, out width, out height);
    
    
                        //通过改变图像的缩放来适应图像在窗口的正常显示
                        HOperatorSet.SetPart(hv_WindowHandle, 0, 0, height, width);
    
    
                        #endregion
                        if (HDevWindowStack.IsOpen())
                        {
                            //在窗口上显示图像
                            HOperatorSet.DispObj(ho_Image, HDevWindowStack.GetActive());
                        }
                        if (HDevWindowStack.IsOpen())
                        {
                            HOperatorSet.DispObj(ho_SymbolXLDs, HDevWindowStack.GetActive());
                        }
                        var code = hv_DecodedDataStrings.ToString();
                        if (!string.IsNullOrWhiteSpace(code) && code != "[]")
                        {
                            Console.WriteLine(string.Format("[{0}]读取条码:{1}", DateTime.Now, code));
                            _SynCtx.Post(o => { textBox1.Text = DateTime.Now.ToString("HH:mm:ss") + ":" + "
    " + code; }, null);
                        }
                        //会报错,copy  hcanvas.dll后不报错,但是图片无法显示了
                        //disp_message(hv_WindowHandle, "读出的二维码是:" + hv_DecodedDataStrings, "window", 40, 12, "black", "true");
                        //Image Acquisition 01: Do something
                    }
                    HOperatorSet.ClearDataCode2dModel(hv_DataCodeHandle);
                    HOperatorSet.CloseFramegrabber(hv_AcqHandle);
    
    
                    ho_Image.Dispose();
                    ho_SymbolXLDs.Dispose();
    
                    _Enable = false;
                    Console.WriteLine("任务停止");
                }
                catch (Exception ex)
                {
                    _Enable = false;
                    Console.WriteLine(ex.Message);
                }
            }
    
            // 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 = null, hv_GenParamValue = null;
                HTuple hv_Color_COPY_INP_TMP = hv_Color.Clone();
                HTuple hv_Column_COPY_INP_TMP = hv_Column.Clone();
                HTuple hv_CoordSystem_COPY_INP_TMP = hv_CoordSystem.Clone();
                HTuple hv_Row_COPY_INP_TMP = hv_Row.Clone();
    
                // Initialize local and output iconic variables 
                //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)
                {
    
                    return;
                }
                if ((int)(new HTuple(hv_Row_COPY_INP_TMP.TupleEqual(-1))) != 0)
                {
                    hv_Row_COPY_INP_TMP = 12;
                }
                if ((int)(new HTuple(hv_Column_COPY_INP_TMP.TupleEqual(-1))) != 0)
                {
                    hv_Column_COPY_INP_TMP = 12;
                }
                //
                //Convert the parameter Box to generic parameters.
                hv_GenParamName = new HTuple();
                hv_GenParamValue = new HTuple();
                if ((int)(new HTuple((new HTuple(hv_Box.TupleLength())).TupleGreater(0))) != 0)
                {
                    if ((int)(new HTuple(((hv_Box.TupleSelect(0))).TupleEqual("false"))) != 0)
                    {
                        //Display no box
                        hv_GenParamName = hv_GenParamName.TupleConcat("box");
                        hv_GenParamValue = hv_GenParamValue.TupleConcat("false");
                    }
                    else if ((int)(new HTuple(((hv_Box.TupleSelect(0))).TupleNotEqual("true"))) != 0)
                    {
                        //Set a color other than the default.
                        hv_GenParamName = hv_GenParamName.TupleConcat("box_color");
                        hv_GenParamValue = hv_GenParamValue.TupleConcat(hv_Box.TupleSelect(0));
                    }
                }
                if ((int)(new HTuple((new HTuple(hv_Box.TupleLength())).TupleGreater(1))) != 0)
                {
                    if ((int)(new HTuple(((hv_Box.TupleSelect(1))).TupleEqual("false"))) != 0)
                    {
                        //Display no shadow.
                        hv_GenParamName = hv_GenParamName.TupleConcat("shadow");
                        hv_GenParamValue = hv_GenParamValue.TupleConcat("false");
                    }
                    else if ((int)(new HTuple(((hv_Box.TupleSelect(1))).TupleNotEqual("true"))) != 0)
                    {
                        //Set a shadow color other than the default.
                        hv_GenParamName = hv_GenParamName.TupleConcat("shadow_color");
                        hv_GenParamValue = hv_GenParamValue.TupleConcat(hv_Box.TupleSelect(1));
                    }
                }
                //Restore default CoordSystem behavior.
                if ((int)(new HTuple(hv_CoordSystem_COPY_INP_TMP.TupleNotEqual("window"))) != 0)
                {
                    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 = new HTuple();
                }
                //
                HOperatorSet.DispText(hv_WindowHandle, 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);
    
                return;
            }
            private void Form1_Load(object sender, EventArgs e)
            {
    
            }
            protected override void OnClosed(EventArgs e)
            {
                if (_Enable)
                {
                    _Enable = false;
                    Thread.Sleep(1000 * 3);
                }
                base.OnClosed(e);
            }
            private void button1_Click(object sender, EventArgs e)
            {
                try
                {
                    _Enable = true;
                    ThreadPool.QueueUserWorkItem(o => { Do(); }, null);
                    button1.Enabled = false;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                    
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                try
                {
                    if (!_Enable)
                    {
                        throw new Exception("任务未启动!");
                    }
                    _Enable = false;
                    Console.WriteLine("停止任务...");
                    button1.Enabled = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
    
            }
        }
    }
    View Code

    //会报错,copy hcanvas.dll后不报错,但是图片无法显示了
    //disp_message(hv_WindowHandle,.....

    相机参数注意调整成连爆光,图片尺寸设置小点这样不卡,另外设置图片中心参数(其他部分会被忽略)图片中心选择镜头畸变小的地方

    另外那个USB相机采用的是directShow驱动,注意区别

    open_framegrabber ('GigEVision2', 0, 0, 0, 0, 0, 0, 'progressive', 8, 'rgb', -1, 'false', 'default', 'c42f90f5f892_Hikvision_MVCA06010GC', 0, -1, AcqHandle)
    set_framegrabber_param (AcqHandle, 'DeviceUserID', '')
    set_framegrabber_param (AcqHandle, 'RegionSelector', 'Region0')
    set_framegrabber_param (AcqHandle, 'Width', 1280)
    set_framegrabber_param (AcqHandle, 'Height', 1280)
    set_framegrabber_param (AcqHandle, 'OffsetX', 952)
    set_framegrabber_param (AcqHandle, 'OffsetY', 684)
    set_framegrabber_param (AcqHandle, 'PixelFormat', 'YUV422_8')
    set_framegrabber_param (AcqHandle, 'TestPattern', 'Off')
    set_framegrabber_param (AcqHandle, 'AcquisitionMode', 'Continuous')
    set_framegrabber_param (AcqHandle, 'AcquisitionBurstFrameCount', 1)
    set_framegrabber_param (AcqHandle, 'AcquisitionFrameRate', 7.4)
    set_framegrabber_param (AcqHandle, 'AcquisitionFrameRateEnable', 1)
    set_framegrabber_param (AcqHandle, 'ExposureMode', 'Timed')
    set_framegrabber_param (AcqHandle, 'ExposureAuto', 'Continuous')
    set_framegrabber_param (AcqHandle, 'TriggerSelector', 'FrameBurstStart')
    grab_image_start (AcqHandle, -1)
    create_data_code_2d_model ('QR Code', [], [], DataCodeHandle)
    dev_close_window()
    dev_open_window(0,0,1280,1280,'black',WindowHandle)
    while (true)
        grab_image_async (Image, AcqHandle, -1)
        find_data_code_2d (Image, SymbolXLDs, DataCodeHandle, [], [], ResultHandles, DecodedDataStrings)
        dev_display (Image)
        dev_display (SymbolXLDs)
         disp_message (WindowHandle, '读出的二维码是:'+DecodedDataStrings, 'window', 40, 12, 'black', 'true')
        * Image Acquisition 01: Do something
    endwhile
    clear_data_code_2d_model (DataCodeHandle)
    close_framegrabber (AcqHandle)
    View Code

     发布后发现还是运行不了,于是拿安装包装了Halcon的runtime,然后正常了

  • 相关阅读:
    自己的第一个网页
    第一次爬虫测试
    科学计算与可视化
    python自顶向下的设计方法进行体育竞技分析
    python PIL库的相关操作
    python 关于身份证号码的相关操作
    jieba库
    汉诺塔
    Django项目中运行Scrapy项目
    **Django+Echart实现多个饼状图(echart数据格式问题 {value: 135, name: '视频广告'})
  • 原文地址:https://www.cnblogs.com/wdfrog/p/14793455.html
Copyright © 2020-2023  润新知