一维码识别之barcode_autodiscrimination.hdev

*本例程展示了自动识别特征的条码读取器的使用

  • Example program for the usage of the bar code
  • reader autodiscrimination feature of HALCON.
  • 创建条码读取句柄
  • Create bar code reader model
    create_bar_code_model ([], [], BarCodeHandle)
    *设置条码读取器参数,是否验证空白区域是否干净
    *具体看这里:https://blog.youkuaiyun.com/IntegralforLove/article/details/83722002
    set_bar_code_param (BarCodeHandle, ‘quiet_zone’, ‘true’)
  • 初始化
  • Initialization
    *关闭更新
    dev_update_off ()
    *关闭窗体
    dev_close_window ()
    *打开窗体
    dev_open_window (0, 0, 512, 512, ‘black’, WindowHandle)
    *设置显示字体
    set_display_font (WindowHandle, 14, ‘mono’, ‘true’, ‘false’)
    *设置填充方式
    dev_set_draw (‘margin’)
    *设置线宽
    dev_set_line_width (3)
    *设置显示颜色
    dev_set_color (‘forest green’)
  • 定义样本图像
  • Define the example images to use
  • for part I
    *定义每一种条码的样本图像
    ExampleImagesAny := [‘barcode/ean13/ean1301’,‘barcode/code39/code3901’,‘barcode/gs1databar_omnidir/gs1databar_omnidir_01’]
    *期望条码数量
    ExpectedNumCodes := [1,2,1]
    *期望数据
    ExpectedData := [‘4008535118906’,‘92274A’,‘R74-2001-010’,’(01)00098431358722’]
  • for part II
    *混合图像
    ExampleImagesMixed := [‘barcode/mixed/barcode_mixed_04’,‘barcode/mixed/barcode_mixed_03’,‘barcode/mixed/barcode_mixed_01’]
  • 第一部分
  • PART I
  • 用自动特征识别去解码任何一个条码或者定义位置的条码
  • Use autodiscrimination to decode any of the bar code types
  • supported by HALCON (except PharmaCode) or determine the bar
  • code type of unknown bar codes

for IdxExample := 0 to 1 by 1
*
* Use different parameters for each run
*第一步:搜索所有条码类型
* First: Search for all bar code types
*第二部:搜索期望条码类型
* Second: Search only expected bar code types
*定义各种显示信息
Message := ‘Usage of autodiscrimination to decode’
Message[1] := ‘unknown bar code types.’
Message[2] := ’ ’

  • 搜索所有条码类型的参数和显示信息
    if (IdxExample == 0)
    CodeTypes := ‘auto’
    Message[3] := ‘Part I:’
    Message[4] := ‘Compare performance between automatic’
    Message[5] := ‘bar code discrimination and search for’
    Message[6] := ‘specific code types only.’
    Message[7] := ’ ’
    Message[8] := ‘In the first run we use CodeType=’’ + CodeTypes + ‘’ to look’
    Message[9] := ‘for all bar code types known to HALCON’
    Message[10] := ’ ’
    Message[11] := ‘Please note that’
    Message[12] := ’ - Wrong bar codes may be found’
    Message[13] := ’ - Execution times are longer than necessary’
    Color := [gen_tuple_const(|Message| - 2,‘black’),gen_tuple_const(3,‘red’)]
    *搜索期望条码类型的参数和显示信息
    else
    CodeTypes := [‘EAN-13’,‘Code 39’,‘GS1 DataBar Omnidir’]
    Message := ‘In the second run we look for the expected types only:’
    Message[1] := sum(’ ’ + CodeTypes)
    Message[2] := ‘This reduces the decoding time and’
    Message[3] := ‘increases the decoding reliability.’
    Color := gen_tuple_const(|Message|,‘black’)
    endif
    *关闭窗体
    dev_clear_window ()
    *显示信息
    disp_message (WindowHandle, Message, ‘window’, 12, 12, Color, ‘true’)
    *右下角显示’Press F5 to continue’
    disp_continue_message (WindowHandle, ‘black’, ‘true’)
    stop ()
    *用两种参数跑两次
  • Run the test 2 times with different parameters
    for IdxIma := 0 to |ExampleImagesAny| - 1 by 1
    *读取图像
    FileName := ExampleImagesAny[IdxIma]
    read_image (Image, FileName)
    • 设置啊默认显示参数
    • Set display defaults
      *获取图像尺寸
      get_image_size (Image, Width, Height)
      *限制窗体尺寸
      dev_set_window_extents (-1, -1, Width, Height)
      *显示图像
      dev_display (Image)
      *显示图像
      disp_message (WindowHandle, [‘Looking for bar code(s) of type:’,sum(’ ’ + CodeTypes)], ‘window’, 12, 12, ‘black’, ‘true’)
    • 寻找和定义一维码并测量所需时间
    • Find and decode bar codes. Measure the time needed.
      *开始计时
      count_seconds (Start)
      *寻找一维码
      find_bar_code (Image, SymbolRegions, BarCodeHandle, CodeTypes, DecodedDataStrings)
      *计时结束
      count_seconds (Stop)
      *消耗时间
      Duration := (Stop - Start) * 1000
    • 检查结果是否正确,用上面期望的值与找到的值进行对比
    • Check, if results are correct
      Start := sum(ExpectedNumCodes[0:IdxIma]) - ExpectedNumCodes[IdxIma]
      DataExp := ExpectedData[Start:Start + ExpectedNumCodes[IdxIma] - 1]
      WrongIndex := []
      *找到的值是否包含在期望的值中
      for I := 0 to |DecodedDataStrings| - 1 by 1
      tuple_find (DataExp, DecodedDataStrings[I], Indices)
      if (Indices == -1)
      WrongIndex := [WrongIndex,I]
      endif
      endfor
      *自动生成一个颜色数组
      Color := [‘black’,gen_tuple_const(|DecodedDataStrings|,‘forest green’)]
      Color[WrongIndex + 1] := ‘red’
    • *显示结果和执行时间
    • Display results and the execution time
      for I := 1 to |DecodedDataStrings| by 1
      *选择条码区域
      select_obj (SymbolRegions, ObjectSelected, I)
      *设置显示颜色
      dev_set_color (Color[I])
      *显示选择区域
      dev_display (ObjectSelected)
      endfor
      *获取条码结果,这里是获取条码类型
      get_bar_code_result (BarCodeHandle, ‘all’, ‘decoded_types’, DecodedDataTypes)
      *显示信息
      disp_message (WindowHandle, [‘Found bar code(s) in ’ + Duration$’.0f’ + ’ ms:’,DecodedDataTypes + ‘: ’ + DecodedDataStrings], ‘window’, 5 * 12, 12, Color, ‘true’)
      *右下角显示’Press F5 to continue’
      disp_continue_message (WindowHandle, ‘black’, ‘true’)
      stop ()
      endfor
      endfor
  • 第二部分
  • Part II
  • 开始一次读取多种类型条码
  • Now we decode multiple bar code types
  • 显示信息
  • Display information for the user
    Message := ‘Part II’
    Message[1] := ’ ’
    Message[2] := ‘Now we demonstrate the usage of autodiscrimination’
    Message[3] := ‘to decode multiple mixed bar code types within one image.’
    *清除窗体
    dev_clear_window ()
    *显示信息
    disp_message (WindowHandle, Message, ‘window’, 12, 12, ‘black’, ‘true’)
    *右下角显示’Press F5 to continue’
    disp_continue_message (WindowHandle, ‘black’, ‘true’)
    stop ()
  • 分为两部分
    for IdxExample := 0 to 1 by 1
    if (IdxExample)
    * 扫描所有条码类型,除去固定类型条码
    * We could scan for all bar codes except certain bar code
    * families…
    获取参数,这里是获取条码类型名称
    get_param_info (‘find_bar_code’, ‘CodeType’, ‘value_list’, AllCodeTypes)
    NoGS1 := ‘~’ + regexp_select(AllCodeTypes,'GS1.
    ’)
    NoUPC := ‘~’ + regexp_select(AllCodeTypes,‘UPC.*’)
    CodeTypes := [‘auto’,NoGS1,NoUPC]
    CodeTypesDescription := ‘all types, except GS1 and UPC variants’
    else
    * 在这里,只扫描EAN和Code 39类型
    * …or (as we do here) scan only for the EAN family and
    * Code 39
    获取参数,这里是获取条码类型名称
    get_param_info (‘find_bar_code’, ‘CodeType’, ‘value_list’, AllCodeTypes)
    AllEAN := regexp_select(AllCodeTypes,'EAN-13.
    ’)
    CodeTypes := [AllEAN,‘Code 39’]
    CodeTypesDescription := ‘Code 39 and all EAN variants’
    endif
    • 展示混合多种条码的自动识别和区分
    • Demonstrate autodiscrimination for mixed bar code types
      for IdxIma := 0 to |ExampleImagesMixed| - 1 by 1
      FileName := ExampleImagesMixed[IdxIma]
      *读取图像
      read_image (Image, FileName)
      • 显示图像和描述
      • Display image and description
        *获取图像尺寸
        get_image_size (Image, Width, Height)
        *限制窗体尺寸
        dev_set_window_extents (-1, -1, Width / 2, Height / 2)
        *显示图像
        dev_display (Image)
        *显示信息
        disp_message (WindowHandle, [‘Looking for bar code(s) of type:’,’ ’ + CodeTypesDescription], ‘window’, 12, 12, ‘black’, ‘true’)
      • 解码混合条码
      • Decode mixed bar codes
        find_bar_code (Image, SymbolRegions, BarCodeHandle, CodeTypes, DecodedDataStrings)
      • 显示条码和条码区域
      • Display decoded data and symbol region
        *设置显示颜色
        dev_set_color (‘forest green’)
        *显示条码区域
        dev_display (SymbolRegions)
        *获取条码结果,这里是条码类型参数
        get_bar_code_result (BarCodeHandle, ‘all’, ‘decoded_types’, DecodedDataTypes)
        *求灰度面积和区域中心坐标
        area_center (SymbolRegions, Area, Rows, Columns)
        *显示信息
        disp_message (WindowHandle, DecodedDataTypes + ‘: ’ + DecodedDataStrings, ‘image’, Rows, Columns - 160, ‘forest green’, ‘true’)
        *是否跳出循环
        if (IdxIma < |ExampleImagesMixed| - 1 or IdxExample == 0)
        *右下角显示’Press F5 to continue’
        disp_continue_message (WindowHandle, ‘black’, ‘true’)
        stop ()
        endif
        endfor
        endfor
  • 清除条码读取器,释放内存
  • Close the bar code reader to clean up memory
    stop ()
    clear_bar_code_model (BarCodeHandle)
``` Public Class FormInOut Dim TempStr As String ' 一時文字列 Private Sub FormInOut_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim SerPort As Integer = Spec(30) Barcode_Comm.BaudRate = 9600 'Barcode_Comm.Parity = IO.Ports.Parity.Even Barcode_Comm.Parity = IO.Ports.Parity.None Barcode_Comm.DataBits = 7 Barcode_Comm.StopBits = IO.Ports.StopBits.One Barcode_Comm.PortName = "COM" & SerPort Barcode_Comm.Handshake = IO.Ports.Handshake.RequestToSend If Barcode_Comm.IsOpen = True Then Barcode_Comm.Close() ElseIf Barcode_Comm.IsOpen = False Then Barcode_Comm.Open() End If End Sub Delegate Sub RecvDataDelegate(ByVal RecvStr As String) Private Sub RecvData(ByVal RecvStr As String) LaRecv.Text = RecvStr BarCodePub = RecvStr BarCodeFlag = 1 End Sub Private Sub Barcode_Comm_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles Barcode_Comm.DataReceived Dim Recv As New RecvDataDelegate(AddressOf RecvData) Dim strReceived As String Try ' 受信データ読込 strReceived = Barcode_Comm.ReadExisting() ' 受信文字列結合 TempStr = TempStr + strReceived ' CR受信(受信完了) If strReceived(strReceived.Length - 1) = vbCr Then ' CR削除 TempStr = TempStr.Remove(TempStr.Length - 1, 1) ' TextBox1からInvoke Invoke(Recv, TempStr) ' 一時文字列初期化 TempStr = "" End If Catch ex As Exception MessageBox.Show(ex.Message, "受信エラー", _ MessageBoxButtons.OK, _ MessageBoxIcon.Error, _ MessageBoxDefaultButton.Button3) End Try End Sub End Class```VB.NET 编写,将在窗体Equipment下重新设置Barcode_comm类和参数设置并打开端口,在FormInout窗体处理事件数据接收和TEXTBOX1显示
最新发布
04-03
这段代码展示了如何通过 `SerialPort` 类实现串口通信,并将接收到的数据展示到窗体控件中。接下来我们详细分析其功能以及如何在另一个窗体(例如 `Equipment` 窗体)完成类似的功能。 --- ### 功能概述 该程序的主要任务是: 1. **初始化串口**:在 `FormInOut_Load` 中配置了串口号、波特率等参数。 2. **接收数据**:当有数据到达时触发 `DataReceived` 事件,然后调用委托更新界面内容。 3. **显示结果**:把接收到的数据去除最后的换行符后显示在文本框 (`LaRecv`) 和全局变量中。 如果需要在一个新的窗体(如 `Equipment`)上重新创建这个过程,则可以参考以下步骤: #### 步骤一:复制必要的属性和方法 可以在新窗体 `Equipment` 下添加相同的字段和构造函数来进行串口通信设置,比如下面的例子: ```vb.net Public Class Equipment Dim TempStr_Equipment As String ' 新窗口的一時文字列 Public Barcode_Comm_Eqmt As SerialPort Private Sub Equipment_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' 初始化设备上的串口实例及参数设定 (类似于 FormInOut 的做法) Barcode_Comm_Eqmt = New SerialPort() With { .BaudRate = 9600, .Parity = IO.Ports.Parity.None, .DataBits = 8, .StopBits = IO.Ports.StopBits.One, .Handshake = IO.Ports.Handshake.RequestToSend } Dim SerPort As Integer = Spec(45) ' 假设使用其他端口编号规则获取值 Barcode_Comm_Eqmt.PortName = "COM" & SerPort If Not Barcode_Comm_Eqmt.IsOpen Then Try Barcode_Comm_Eqmt.Open() Catch ex As Exception MessageBox.Show("无法打开指定端口:" & ex.Message) End Try Else Barcode_Comm_Eqmt.Close() End If End Sub Delegate Sub RecvDataEqmtDelegate(ByVal RecvStr As String) Private Sub RecvData_Equipment(ByVal RecvStr As String) LabelEquip.Text = RecvStr ' 更新标签内容 BarCodePub_Equip = RecvStr BarCodeFlag_Equip = 1 End Sub Private Sub Barcode_Comm_Eqmt_DataReceived(sender As Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles Barcode_Comm_Eqmt.DataReceived Dim Recv As New RecvDataEqmtDelegate(AddressOf RecvData_Equipment) Dim strReceived As String Try strReceived = Barcode_Comm_Eqmt.ReadExisting() TempStr_Equipment &= strReceived If strReceived(strReceived.Length - 1) = vbCr Then TempStr_Equipment = TempStr_Equipment.Remove(TempStr_Equipment.Length - 1, 1) Me.Invoke(Recv, TempStr_Equipment) TempStr_Equipment = "" End If Catch ex As Exception MessageBox.Show(ex.Message, "受信エラー", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub End Class ``` 以上就是从原有模块抽取公共部分并在另一处复用的新版本简化设计示例。 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值