摘要
機器視覺中經常要用vs(c#版)聯合halcon做winform界面開發,那么如何對其進行環境配置呢?
以最簡單的readimage為例,本篇總結一下如何進行環境配置以及相關問題的解決。
1️⃣halcon生成庫,供c#調用
用halcon讀取一張圖片,然后導出為c#語言
2️⃣在vs中配置環境,並編寫讀取圖像界面
一,創建vs工程,配置環境
- 打開halcon文件所在目錄(以本電腦為例),將D:\MVTec\halcon19\bin\dotnet35下的halcondotnet.dll文件放入vs文件的debug目錄下。
- 在vs工程中的引用下添加halcondotnet.dll引用
- 引用halcondotnet.dll命名空間(using HalconDotNet;)
二,添加readimage類(封裝該類,便於后續調用)
三,編寫界面,並編寫代碼
readimage類代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HalconDotNet; namespace readimage { class readimage { //定義全局變量 public HTuple Hwindows;//定義窗口句柄 HObject currentImg;//定義圖像 HTuple imageWidth, imageHeight;//定義寬高 //定義加載圖像函數 public void loadimg(HWindowControl HW,string Path) { //把當前控件綁定到Hwindows Hwindows = HW.HalconWindow; //讀取圖像 HOperatorSet.ReadImage(out currentImg, Path); //自適應顯示大小 HOperatorSet.GetImageSize(currentImg, out imageWidth, out imageHeight); HOperatorSet.SetPart(Hwindows, 0, 0, imageHeight-1, imageWidth-1); //顯示圖像 HOperatorSet.DispObj(currentImg, Hwindows); } } }
調用readimage類進行圖像讀取顯示:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using HalconDotNet; namespace readimage { public partial class Form1 : Form { public Form1() { InitializeComponent(); } readimage read = new readimage();//對新建類實例化 private void button1_Click(object sender, EventArgs e) { using (OpenFileDialog ofg = new OpenFileDialog()) { ofg.Filter = "圖片|*.jpg;*.png;";//設置選取格式 ofg.Multiselect = false;//不支持多選 ofg.Title = "圖片獲取"; if (ofg.ShowDialog()==DialogResult.OK) { read.loadimg(hWindowControl1,ofg.FileName); } } } } }