1. 资源释放
1)所有的Hobject类型必须要手动进行资源释放,GC是没办法进行回收的。在官方文档中的说明是Hobject类型占有的内存太小,GC无法检索到。所以这部分建议放在finally里面,无论如何都要执行。
using System;
using HalconDotNet;
public class HalconTestClass
{
public static string action(string ImagePath,double ScaleFactor)
{
string ResultCode = "";
HObject ho_Image, ho_ImageZoomed, ho_SymbolXLDs;
HTuple hv_CodeResult = null, hv_ImagePath = null;
HTuple hv_ScaleFactor = null, hv_DataCodeHandle = null;
HTuple hv_ResultHandles = null, hv_DecodedDataStrings = null;
// Initialize local and output iconic variables
HOperatorSet.GenEmptyObj(out ho_Image);
HOperatorSet.GenEmptyObj(out ho_ImageZoomed);
HOperatorSet.GenEmptyObj(out ho_SymbolXLDs);
try
{
//结果部分
hv_CodeResult = "";
//参数部分
hv_ImagePath = ImagePath;
hv_ScaleFactor = ScaleFactor;
//图像处理部分
#region 图像处理部分
ho_Image.Dispose();
HOperatorSet.ReadImage(out ho_Image, hv_ImagePath);
ho_ImageZoomed.Dispose();
HOperatorSet.ZoomImageFactor(ho_Image, out ho_ImageZoomed, 1, hv_ScaleFactor,
"constant");
HOperatorSet.CreateDataCode2dModel("QR Code", new HTuple(), new HTuple(), out hv_DataCodeHandle);
ho_SymbolXLDs.Dispose();
HOperatorSet.FindDataCode2d(ho_ImageZoomed, out ho_SymbolXLDs, hv_DataCodeHandle,
new HTuple(), new HTuple(), out hv_ResultHandles, out hv_DecodedDataStrings);
HOperatorSet.ClearDataCode2dModel(hv_DataCodeHandle);
if ((int)(new HTuple(hv_DecodedDataStrings.TupleNotEqual(new HTuple()))) != 0)
{
hv_CodeResult = hv_DecodedDataStrings.Clone();
}
#endregion
ResultCode = hv_CodeResult.S;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
ho_Image.Dispose();
ho_ImageZoomed.Dispose();
ho_SymbolXLDs.Dispose();
}
return ResultCode;
}
}
2)所有的Halcon代码中的Create开头的算法,都对应有一个Clear的算法进行释放,比如识别一维码的create_bar_code_model对应clear_bar_code_model,其他类似的还有识别二维码、识别OCR、模板匹配等,务必注意!!!建议用完以后,马上进行Clear操作,否则很容易出现内存泄漏。C#中的代码可参考上面一项。
create_bar_code_model([], [], BarCodeHandle)
clear_bar_code_model(BarCodeHandle)
create_data_code_2d_model('Data Matrix ECC 200', [], [], DataCodeHandle)
clear_data_code_2d_model(DataCodeHandle)
read_shape_model('1.shm', ModelID)
clear_shape_model(ModelID)
2.版本兼容问题
1)若出现提示“试图加载格式不正确的程序”,是因为Halcon的版本和编译的平台版本不对应,安装的是64位的Halcon,就必须将生成平台改成X64,32位的对应X86。
报错提示:
System.BadImageFormatException
HResult=0x8007000B
Message=试图加载格式不正确的程序。 (异常来自 HRESULT:0x8007000B)
Source=halcondotnet
3.不安装Halcon的前提下运行程序
从Halcon的安装目录下Halcon\bin\x64-win64里面全部的dll放在bin根目录下。