c#聯合Halcon進行OCR字符識別(含halcon-25.05 百度網盤)

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 字符識別

  1. CreateDeepOcr函數:這個函數負責創建深度OCR處理器。使用HOperatorSet.CreateDeepOcr方法,傳入參數"mode"和"recognition",生成一個OCR句柄。然后調用set_suitable_device_in_ocr_handle來設置合適的運行設備(如GPU或CPU),并設置識別圖像的寬度參數。這個函數的作用是初始化OCR模型,準備后續的識別操作。

  2. set_suitable_device_in_ocr_handle函數:該函數用于配置OCR處理器使用的計算設備。首先查詢可用的深度學習設備(GPU和CPU),優先選擇GPU。然后設置識別圖像的寬度參數,確保在處理時不會因為內存問題出錯。這里涉及到異常處理,確保在設備不可用時能夠回退到其他設備,并在最后恢復默認的圖像寬度設置。

  3. 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;}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/95245.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/95245.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/95245.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

絲桿支撐座怎樣助力升降設備實現智能化?

絲桿支撐座作為傳動系統中的關鍵支撐部件&#xff0c;憑借其高剛性、抗沖擊及精準定位能力&#xff0c;廣泛應用于重型機械與升降設備領域&#xff0c;為設備提供穩定可靠的軸向承載與徑向支撐&#xff0c;確保高負荷工況下的安全運行。電梯 / 升降平臺&#xff1a;液壓電梯的輔…

Notta:高效智能的音頻轉文字工具

本文轉載自&#xff1a;Notta&#xff1a;高效智能的音頻轉文字工具 - Hello123 ** 一、產品簡介 Notta 是一款基于 AI 語音識別引擎的語音轉文字工具&#xff0c;支持 58 種語言的轉錄和 42 種語言的翻譯。用戶可通過實時錄音或上傳音頻 / 視頻文件&#xff08;如 MP3、WAV …

Docker私有倉庫創建及Docky存儲與網絡配置(小白的“升級打怪”成長之路)

目錄 一、Docker私有倉庫創建 1、在一臺安裝Docker私有倉庫的主機上添加docker-compose 命令 2、安裝docker-ce服務 3、Docker 鏡像加速 4、安裝Harbor倉庫 5、使用腳本安裝倉庫 6、網站登陸 7、客戶端使用Harbor倉庫 二、Docky存儲與網絡配置 1、存儲與網絡 掛載主機…

谷歌ADK接入文件操作MCP

文章目錄MCP基礎概念文件操作服務器文件操作MCP接入谷歌ADK項目創建多輪對話代碼MCP基礎概念 MCP技術體系中&#xff0c;會將外部工具運行腳本稱作服務器&#xff0c;而接入這些外部工具的大模型運行環境稱作客戶端。 一個客戶端可以接入多個不同類型的服務器&#xff0c;但都…

高光譜技術的獨特優勢

高光譜技術憑借其?納米級連續光譜采集能力?和?圖譜合一的探測模式?&#xff0c;在多個領域展現出不可替代的獨特優勢&#xff1a;一、光譜維度&#xff1a;精細物質指紋識別?納米級連續光譜解析? 通過 ?5-10nm帶寬的數百個連續波段?&#xff08;最高330個通道&#xff…

基于Vue+Element UI集成高德地圖的完整實踐指南

本次開發使用deepseek 簡直如虎添翼得心應手 生成模擬數據、解決報錯那真是嘎嘎地 在 Vue Element UI 項目中引入高德地圖 具體實現步驟&#xff1a; 高德開放平臺&#xff1a;注冊賬號 → 進入控制臺 → 創建應用 → 獲取 Web端(JS API)的Key https://lbs.amap.com/ 這里需要…

Day50--圖論--98. 所有可達路徑(卡碼網),797. 所有可能的路徑

Day50–圖論–98. 所有可達路徑&#xff08;卡碼網&#xff09;&#xff0c;797. 所有可能的路徑 刷今天的內容之前&#xff0c;要先去《代碼隨想錄》網站&#xff0c;先看完&#xff1a;圖論理論基礎和深度優先搜索理論基礎。做完之后可以看題解。有余力&#xff0c;把廣度優先…

Python 異常捕獲

一、獲取未知錯誤try:# 相關處理邏輯 異常后面輸出print(輸入信息……) except Exception as e:print(未知錯誤,e)二、獲取已知錯誤except 錯誤單詞&#xff08;來源于錯誤信息的第一個單詞&#xff09;多個已知錯誤使用 except XXXXX:try:# 相關處理邏輯 異常后面輸出print…

RIOT、RT-Thread 和 FreeRTOS 是三種主流的實時操作系統

RIOT、RT-Thread 和 FreeRTOS 是三種主流的實時操作系統&#xff08;RTOS&#xff09;&#xff0c;專為嵌入式系統和物聯網&#xff08;IoT&#xff09;設備設計。它們在架構、功能、生態和應用場景上有顯著差異&#xff0c;以下是詳細對比&#xff1a;1. 架構與設計理念特性RI…

【FAQ】Win11創建資源不足繞開微軟賬號登錄

Win11安裝資源限制 因為 Windows 11 有兩項強制檢測 VMware 8 默認沒提供&#xff1a; TPM 2.0&#xff08;可信平臺模塊&#xff09;Secure Boot&#xff08;安全啟動&#xff09; 一步到位解決辦法&#xff08;官方兼容方式&#xff09; 關閉虛擬機電源編輯虛擬機設置 選項 →…

Docker使用----(安裝_Windows版)

一、Docker Docker 鏡像就像是一個軟件包&#xff0c;里面包括了應用程序的代碼、運行所需的庫和工具、配置文件等等&#xff0c;所有這些都打包在一起&#xff0c;以確保應用程序在不同的計算機上運行時&#xff0c;都能保持一致性。 可以把 Docker 鏡像想象成一個軟件安裝文件…

91、23種經典設計模式

設計模式是軟件設計中反復出現的解決方案的模板&#xff0c;用于解決特定問題并提高代碼的可維護性、可擴展性和可復用性。23種經典設計模式可分為創建型、結構型和行為型三大類&#xff0c;以下是具體分類及模式概述&#xff1a; 一、創建型模式&#xff08;5種&#xff09; 關…

Illustrator總監級AI魔法:一鍵讓低清logo變矢量高清,徹底告別手動描摹!

在海外從事設計十幾年&#xff0c;我敢說&#xff0c;每個設計師都經歷過一種“史詩級”的折磨&#xff1a;客戶發來一個像素低得感人、邊緣模糊不清的JPG格式Logo&#xff0c;然后要求你把它用在巨幅海報或者高清視頻上。這意味著什么&#xff1f;意味著我們要打開Illustrator…

各種 dp 刷題下

6.#8518 杰瑞征途 / 洛谷 P4072 征途 題意 Pine 開始了從 SSS 地到 TTT 地的征途。從 SSS 地到 TTT 地的路可以劃分成 nnn 段&#xff0c;相鄰兩段路的分界點設有休息站。Pine 計劃用 mmm 天到達 TTT 地。除第 mmm 天外&#xff0c;每一天晚上 Pine 都必須在休息站過夜。所以…

本地WSL部署接入 whisper + ollama qwen3:14b 總結字幕增加利用 Whisper 分段信息,全新 Prompt功能

1. 實現功能 M4-3: 智能后處理 - 停頓感知增強版 (終極版) 本腳本是 M4-3 的重大升級&#xff0c;引入了“停頓感知”能力&#xff1a; 利用 Whisper 分段信息: 將 Whisper 的 segments 間的自然停頓作為強信號 ([P]) 提供給 LLM。全新 Prompt: 設計了專門的 Prompt&#xff0c…

微算法科技(NASDAQ:MLGO)開發經典增強量子優化算法(CBQOA):開創組合優化新時代

近年來&#xff0c;量子計算在組合優化領域的應用日益受到關注&#xff0c;各類量子優化算法層出不窮。然而&#xff0c;由于現階段量子硬件的局限性&#xff0c;如何充分利用已有的經典計算能力來增強量子優化算法的表現&#xff0c;成為當前研究的重要方向。基于此&#xff0…

功能、延遲、部署、成本全解析:本地化音視頻 SDK 對比 云端方案

引言 在構建實時音視頻系統時&#xff0c;技術選型往往決定了項目的天花板。開發者面臨的第一個關鍵抉擇&#xff0c;就是是選擇完全可控的本地化音視頻內核&#xff0c;還是依賴云廠商的實時音視頻服務。 以大牛直播SDK&#xff08;SmartMediaKit&#xff09;為代表的本地部…

微調入門:為什么微調

歡迎來到啾啾的博客&#x1f431;。 記錄學習點滴。分享工作思考和實用技巧&#xff0c;偶爾也分享一些雜談&#x1f4ac;。 有很多很多不足的地方&#xff0c;歡迎評論交流&#xff0c;感謝您的閱讀和評論&#x1f604;。 目錄1 什么時候我們需要微調呢&#xff1f;1.1 微調的…

3、匹配一組字符

在本章里&#xff0c;你將學習如何與字符集合打交道。與可以匹配任意單個字符的.字符&#xff08;參見第2章&#xff09;不同&#xff0c;字符集合能匹配特定的字符和字符區間。3.1 匹配多個字符中的某一個第2章介紹的.?字符&#xff0c;可以匹配任意單個字符。當時在最后一個…

強化學習在量化交易中的禁區:回測表現好實盤虧錢的4個原因

引言 “為什么你的強化學習策略在回測中年化 50%,到了實盤卻三個月虧光本金?” 如果你做過量化交易,尤其是嘗試用強化學習(Reinforcement Learning, RL),這種場景可能并不陌生: 回測曲線平滑向上,最大回撤可控,勝率穩定 模型參數和架構調到極致,每次迭代都帶來更高的…