1.下載安裝halcon
通過網盤分享的文件:halcon-25.05.0.0-x64-win64
鏈接: https://pan.baidu.com/s/1XAx-8ZQM-ZHkgHIc-dhCYw
提取碼: whek
2.c#環境配置
創建test_halcon_ocr項目
找到halcon的安裝路徑
我的:
D:\halcon\HALCON-25.05-Progress\bin\x64-win64
D:\halcon\HALCON-25.05-Progress\bin\dotnet35
添加引用("D:\halcon\HALCON-25.05-Progress\bin\dotnet35\halcondotnet.dll")
把halcondotnet.dll拖到工具箱中。
屏幕錄制 2025-08-12 103356
添加HWindowcontrol ,button 和 textbox
設置button1 點擊事件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HalconDotNet;namespace test_halcon_ocr
{public partial class Form1 : Form{HObject TestImage;string Path_testimg = "C:\\Users\\86957\\Desktop\\img_ocr_0296.png";public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){//讀取文件HOperatorSet.ReadImage(out TestImage, Path_testimg);//獲取圖片大小HTuple Width, Height;HOperatorSet.GetImageSize(TestImage, out Width, out Height);//設置圖片顯示范圍 hWindowControl1.HalconWindow獲得窗體句柄HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, (Height - 1), (Width - 1)); //0,0, (Height - 1), (Width - 1)代表從0,0坐標到圖片的寬高坐標,達到全屏顯示//將圖片投射到窗體上HOperatorSet.DispObj(TestImage, hWindowControl1.HalconWindow);//將TestImage變量投射到句柄窗口上}private void button2_Click(object sender, EventArgs e){}}
}
運行,
成功報錯。
解決:
項目右鍵屬性,找到生成,取消勾選首選32位。
再次運行,
成功。
3. ocr 字符識別
-
CreateDeepOcr函數:這個函數負責創建深度OCR處理器。使用HOperatorSet.CreateDeepOcr方法,傳入參數"mode"和"recognition",生成一個OCR句柄。然后調用set_suitable_device_in_ocr_handle來設置合適的運行設備(如GPU或CPU),并設置識別圖像的寬度參數。這個函數的作用是初始化OCR模型,準備后續的識別操作。
-
set_suitable_device_in_ocr_handle函數:該函數用于配置OCR處理器使用的計算設備。首先查詢可用的深度學習設備(GPU和CPU),優先選擇GPU。然后設置識別圖像的寬度參數,確保在處理時不會因為內存問題出錯。這里涉及到異常處理,確保在設備不可用時能夠回退到其他設備,并在最后恢復默認的圖像寬度設置。
-
DeepLearningOCR函數:這是實際的OCR識別函數。它接收圖像、ROI坐標、窗口句柄和OCR處理器句柄作為參數。處理步驟包括圖像預處理(均值濾波和強調處理)、裁剪ROI區域、應用OCR識別,并將結果返回。識別過程中使用Halcon的ApplyDeepOcr方法,并從結果中提取識別的文本。
運行后,
4.完整代碼:
?
using System;
using System.IO;
using System.Windows.Forms;
using HalconDotNet;
namespace test_halcon_ocr
{public partial class Form1 : Form{HObject TestImage;HTuple hv_DeepOcrHandle = new HTuple();string Path_testimg = "C:\\Users\\86957\\Desktop\\img_ocr_0296.png";public Form1(){InitializeComponent();}//自動選擇最佳計算設備(GPU優先),優化模型運行效率static void set_suitable_device_in_ocr_handle(HTuple hv_DeepOcrHandle){// Local control variables HTuple hv_DLDeviceHandles = new HTuple(), hv_RecognitionImageWidthDefault = new HTuple();HTuple hv_Exception = new HTuple(), hv_Index = new HTuple();// Initialize local and output iconic variables try{//Determine deep learning device to work with (prefer GPU over CPU).hv_DLDeviceHandles.Dispose();HOperatorSet.QueryAvailableDlDevices((new HTuple("runtime")).TupleConcat("runtime"),(new HTuple("gpu")).TupleConcat("cpu"), out hv_DLDeviceHandles);if ((int)(new HTuple((new HTuple(hv_DLDeviceHandles.TupleLength())).TupleEqual(0))) != 0){throw new HalconException("No supported device found to continue this example.");}//Set recognition_image_width larger for the example to work without memory problems.try{hv_RecognitionImageWidthDefault.Dispose();HOperatorSet.GetDeepOcrParam(hv_DeepOcrHandle, "recognition_image_width",out hv_RecognitionImageWidthDefault);HOperatorSet.SetDeepOcrParam(hv_DeepOcrHandle, "recognition_image_width",260);}// catch (Exception) catch (HalconException HDevExpDefaultException1){HDevExpDefaultException1.ToHTuple(out hv_Exception);}for (hv_Index = 0; (int)hv_Index <= (int)((new HTuple(hv_DLDeviceHandles.TupleLength())) - 1); hv_Index = (int)hv_Index + 1){try{using (HDevDisposeHelper dh = new HDevDisposeHelper()){HOperatorSet.SetDeepOcrParam(hv_DeepOcrHandle, "device", hv_DLDeviceHandles.TupleSelect(hv_Index));}break;}// catch (Exception) catch (HalconException HDevExpDefaultException1){HDevExpDefaultException1.ToHTuple(out hv_Exception);if ((int)(new HTuple(hv_Index.TupleEqual((new HTuple(hv_DLDeviceHandles.TupleLength())) - 1))) != 0){throw new HalconException("Could not set any of the supported devices to continue this example.");}}}//Reset recognition_image_width to the default value.try{HOperatorSet.SetDeepOcrParam(hv_DeepOcrHandle, "recognition_image_width",hv_RecognitionImageWidthDefault);}// catch (Exception) catch (HalconException HDevExpDefaultException1){HDevExpDefaultException1.ToHTuple(out hv_Exception);}hv_DLDeviceHandles.Dispose();hv_RecognitionImageWidthDefault.Dispose();hv_Exception.Dispose();hv_Index.Dispose();return;}catch (HalconException HDevExpDefaultException){hv_DLDeviceHandles.Dispose();hv_RecognitionImageWidthDefault.Dispose();hv_Exception.Dispose();hv_Index.Dispose();throw HDevExpDefaultException;}}//執行完整的OCR識別流程,包含預處理、ROI裁剪、模型推理和結果解析public static string DeepLearningOCR(HObject ho_ImageSource, int row1, int col1, int row2, int col2, HWindow Window, HTuple hv_DeepOcrHandle){// Local iconic variables HObject ho_ImageMean, ho_Image;HObject ho_ImageWord, ho_Rectangle;// Local control variables HTuple hv_Width = new HTuple();HTuple hv_Height = new HTuple(), hv_DeepOcrResult = new HTuple();HTuple hv_RecognizedWord = new HTuple();// Initialize local and output iconic variables //HOperatorSet.GenEmptyObj(out ho_ImageSource);HOperatorSet.GenEmptyObj(out ho_ImageMean);HOperatorSet.GenEmptyObj(out ho_Image);HOperatorSet.GenEmptyObj(out ho_ImageWord);HOperatorSet.GenEmptyObj(out ho_Rectangle);try{ho_ImageMean.Dispose();HOperatorSet.MeanImage(ho_ImageSource, out ho_ImageMean, 3, 3);// 圖像預處理ho_Image.Dispose();HOperatorSet.Emphasize(ho_ImageMean, out ho_Image, 9, 9, 1);hv_Width.Dispose(); hv_Height.Dispose();HOperatorSet.GetImageSize(ho_ImageSource, out hv_Width, out hv_Height);////Crop the word to be recognized by the recognition component.ho_ImageWord.Dispose();HOperatorSet.CropRectangle1(ho_Image, out ho_ImageWord, row1, col1, row2, col2);// ROI裁剪ho_Rectangle.Dispose();HOperatorSet.GenRectangle1(out ho_Rectangle, row1, col1, row2, col2);////Apply recognition with default recognition_image_width.hv_DeepOcrResult.Dispose();HOperatorSet.ApplyDeepOcr(ho_ImageWord, hv_DeepOcrHandle, "recognition", out hv_DeepOcrResult); // 執行OCR識別hv_RecognizedWord.Dispose();HOperatorSet.GetDictTuple(hv_DeepOcrResult, "word", out hv_RecognizedWord);ho_Image.DispObj(Window);Window.SetDraw("margin");Window.SetColor("red");Window.SetPart(0, 0, (int)(hv_Height - 1), (int)(hv_Width - 1));ho_Rectangle.DispObj(Window);}catch (HalconException HDevExpDefaultException){ho_ImageSource.Dispose();ho_ImageMean.Dispose();ho_Image.Dispose();ho_ImageWord.Dispose();ho_Rectangle.Dispose();// hv_DeepOcrHandle.Dispose();hv_Width.Dispose();hv_Height.Dispose();hv_DeepOcrResult.Dispose();hv_RecognizedWord.Dispose();throw HDevExpDefaultException;}ho_ImageSource.Dispose();ho_ImageMean.Dispose();ho_Image.Dispose();ho_ImageWord.Dispose();ho_Rectangle.Dispose();// hv_DeepOcrHandle.Dispose();hv_Width.Dispose();hv_Height.Dispose();hv_DeepOcrResult.Dispose();hv_RecognizedWord.Dispose();return hv_RecognizedWord.S;}//初始化深度學習OCR模型,創建識別器實例并配置基本參數public static HTuple CreateDeepOcr(){HTuple hv_DeepOcrHandle = new HTuple();hv_DeepOcrHandle.Dispose();HOperatorSet.CreateDeepOcr("mode", "recognition", out hv_DeepOcrHandle);set_suitable_device_in_ocr_handle(hv_DeepOcrHandle);HOperatorSet.SetDeepOcrParam(hv_DeepOcrHandle, "recognition_image_width", 260);return hv_DeepOcrHandle;}private void button1_Click(object sender, EventArgs e)//顯示圖像{//讀取文件HOperatorSet.ReadImage(out TestImage, Path_testimg);//獲取圖片大小HTuple Width, Height;HOperatorSet.GetImageSize(TestImage, out Width, out Height);//設置圖片顯示范圍 hWindowControl1.HalconWindow獲得窗體句柄HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, (Height - 1), (Width - 1)); //0,0, (Height - 1), (Width - 1)代表從0,0坐標到圖片的寬高坐標,達到全屏顯示//將圖片投射到窗體上HOperatorSet.DispObj(TestImage, hWindowControl1.HalconWindow);//將TestImage變量投射到句柄窗口上}private void button2_Click(object sender, EventArgs e)//字符識別{textBox1.AppendText("開始檢測:" + "\r\n");try{hv_DeepOcrHandle = CreateDeepOcr();}catch{MessageBox.Show("error");}if (!File.Exists(Path_testimg)){textBox1.AppendText($"文件不存在: {Path_testimg}" + "\r\n");return;}HalconDotNet.HImage hImage = new HalconDotNet.HImage(Path_testimg);HTuple width, height;hImage.GetImageSize(out width, out height);int intWidth = width.TupleInt();int intHeight = height.TupleInt();textBox1.AppendText("選框坐標為:" + "\r\n");textBox1.AppendText(intWidth.ToString());textBox1.AppendText(width.ToString() + "\r\n");string code = DeepLearningOCR(hImage, 0, 0, intHeight, intWidth, hWindowControl1.HalconWindow, hv_DeepOcrHandle);textBox1.AppendText("code:" + code + "\r\n");}}
}
namespace test_halcon_ocr
{partial class Form1{/// <summary>/// 必需的設計器變量。/// </summary>private System.ComponentModel.IContainer components = null;/// <summary>/// 清理所有正在使用的資源。/// </summary>/// <param name="disposing">如果應釋放托管資源,為 true;否則為 false。</param>protected override void Dispose(bool disposing){if (disposing && (components != null)){components.Dispose();}base.Dispose(disposing);}#region Windows 窗體設計器生成的代碼/// <summary>/// 設計器支持所需的方法 - 不要修改/// 使用代碼編輯器修改此方法的內容。/// </summary>private void InitializeComponent(){this.hWindowControl1 = new HalconDotNet.HWindowControl();this.button1 = new System.Windows.Forms.Button();this.button2 = new System.Windows.Forms.Button();this.textBox1 = new System.Windows.Forms.TextBox();this.SuspendLayout();// // hWindowControl1// this.hWindowControl1.BackColor = System.Drawing.Color.Black;this.hWindowControl1.BorderColor = System.Drawing.Color.Black;this.hWindowControl1.ImagePart = new System.Drawing.Rectangle(0, 0, 640, 480);this.hWindowControl1.Location = new System.Drawing.Point(96, 116);this.hWindowControl1.Name = "hWindowControl1";this.hWindowControl1.Size = new System.Drawing.Size(525, 338);this.hWindowControl1.TabIndex = 0;this.hWindowControl1.WindowSize = new System.Drawing.Size(525, 338);// // button1// this.button1.Location = new System.Drawing.Point(174, 567);this.button1.Name = "button1";this.button1.Size = new System.Drawing.Size(288, 117);this.button1.TabIndex = 1;this.button1.Text = "button1";this.button1.UseVisualStyleBackColor = true;this.button1.Click += new System.EventHandler(this.button1_Click);// // button2// this.button2.Location = new System.Drawing.Point(662, 567);this.button2.Name = "button2";this.button2.Size = new System.Drawing.Size(242, 117);this.button2.TabIndex = 2;this.button2.Text = "button2";this.button2.UseVisualStyleBackColor = true;this.button2.Click += new System.EventHandler(this.button2_Click);// // textBox1// this.textBox1.Location = new System.Drawing.Point(830, 189);this.textBox1.Multiline = true;this.textBox1.Name = "textBox1";this.textBox1.Size = new System.Drawing.Size(317, 254);this.textBox1.TabIndex = 3;// // Form1// this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F);this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;this.ClientSize = new System.Drawing.Size(1269, 736);this.Controls.Add(this.textBox1);this.Controls.Add(this.button2);this.Controls.Add(this.button1);this.Controls.Add(this.hWindowControl1);this.Name = "Form1";this.Text = "Form1";this.ResumeLayout(false);this.PerformLayout();}#endregionprivate HalconDotNet.HWindowControl hWindowControl1;private System.Windows.Forms.Button button1;private System.Windows.Forms.Button button2;private System.Windows.Forms.TextBox textBox1;}
}