using HalconDotNet; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace Bro.Common.Base { public class HDevEngineTool : IDisposable { #region 常量 // path of external procedures readonly string ProcedurePath = Environment.CurrentDirectory + "\\Vision\\"; #endregion #region 成员变量 /// /// 处理过程名 /// public string ProcedureName; /// /// hdev程序启动引擎 /// private readonly HDevEngine myEngine; /// /// 过程载入工具 .hdvp /// private HDevProcedureCall procedureCall; /// /// 程序运行是否成功 /// public bool IsSuccessful { get; set; } = false; /// /// 控制参数字典 /// public Dictionary InputTupleDic { get; set; } /// /// 图形参数字典 /// public Dictionary InputImageDic { get; set; } #endregion #region 初始化 /// /// 实例化 默认搜索路径为: 启动路径//Vision// /// public HDevEngineTool() { ProcedureName = ""; myEngine = new HalconDotNet.HDevEngine(); myEngine.SetProcedurePath(ProcedurePath); InputImageDic = new Dictionary(); InputTupleDic = new Dictionary(); } /// /// 实例化 /// /// 外部函数搜索路径 public HDevEngineTool(string path) { myEngine = new HalconDotNet.HDevEngine(); myEngine.SetProcedurePath(path); InputImageDic = new Dictionary(); InputTupleDic = new Dictionary(); } #endregion /// /// 设置函数运行所需参数 /// /// 控制参数 /// 图形参数 public void SetDictionary(Dictionary _tupleDictionary, Dictionary _imageDictionary) { InputTupleDic = _tupleDictionary; InputImageDic = _imageDictionary; } /// /// 载入过程 .hdvp /// /// 过程名 public void LoadProcedure(string procedureName) { ProcedureName = procedureName; try { HDevProcedure procedure = new HDevProcedure(procedureName); procedureCall = new HDevProcedureCall(procedure); } catch (HDevEngineException Ex) { Trace.TraceInformation("HDevProgram {0} Load fail ,Error Line : {1}, Line number: {2}, Halcon error number : {3}", Ex.ProcedureName, Ex.LineText, Ex.LineNumber, Ex.HalconError); return; } } /// /// 执行过程 /// public bool RunProcedure(out string errorMsg) { errorMsg = ""; try { foreach (KeyValuePair pair in InputTupleDic) { procedureCall.SetInputCtrlParamTuple(pair.Key, pair.Value); } foreach (KeyValuePair pair in InputImageDic) { procedureCall.SetInputIconicParamObject(pair.Key, pair.Value); } procedureCall.Execute(); IsSuccessful = true; return true; } catch (HDevEngineException ex) { IsSuccessful = false; errorMsg = $"HDevProgram {ex.ProcedureName} Run fail , Line number: {ex.LineNumber}, Halcon error number : {ex.HalconError},ex:{ex.Message}"; return false; } catch (Exception ex) { IsSuccessful = false; //Trace.TraceInformation("HDevProgram {0} Run fail , Line number: {1}, Halcon error number : {2},ex:{3}", ex.ProcedureName, ex.LineNumber, ex.HalconError, ex.Message); //return; errorMsg = $"{ex.Message}"; return false; } } public HTuple GetResultTuple(string key) { if (IsSuccessful) { return procedureCall.GetOutputCtrlParamTuple(key); } else { return new HTuple(); } } public HObject GetResultObject(string key, bool ignoreError = false) { if (ignoreError || IsSuccessful) { return procedureCall.GetOutputIconicParamObject(key); } else { return new HObject(); } } public void Dispose() { procedureCall?.Dispose(); myEngine?.Dispose(); } } public static class HalconHelper { [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)] public static extern void CopyMemory(int dest, int src, uint count); //public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count); public static HImage ConvertBitmapToHObject(this Bitmap bmp) { HImage himage = new HImage(); try { //判断输入图像不为null if (bmp == null) { return null; } { //重绘himage //HImage curImage = new HImage(); BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed); himage.GenImage1("byte", bmp.Width, bmp.Height, bmpData.Scan0); bmp.UnlockBits(bmpData); //himage = curImage; } return himage; } catch (Exception e) { return null; } } public static Bitmap ConvertHImageToBitmap(this HImage hImage) { try { HTuple type, width, height, pointer; //HOperatorSet.AccessChannel(ho, out ho, 1); HOperatorSet.GetImagePointer1(hImage, out pointer, out type, out width, out height); //himg.GetImagePointer1(out type, out width, out height); Bitmap bmp = new Bitmap(width.I, height.I, PixelFormat.Format8bppIndexed); ColorPalette pal = bmp.Palette; for (int i = 0; i <= 255; i++) { pal.Entries[i] = Color.FromArgb(255, i, i, i); } bmp.Palette = pal; BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); int PixelSize = Bitmap.GetPixelFormatSize(bitmapData.PixelFormat) / 8; int stride = bitmapData.Stride; int ptr = bitmapData.Scan0.ToInt32(); for (int i = 0; i < height; i++) { CopyMemory(ptr, pointer, (uint)(width * PixelSize)); pointer += width; ptr += bitmapData.Stride; } bmp.UnlockBits(bitmapData); return bmp; } catch (Exception exc) { return null; } } public static List HTupleToDouble(this HTuple tuple) { List list = new List(); for (int i = 0; i < tuple.Length; i++) { list.Add(tuple[i].D); } return list; } public static HImage ConvertHObjectToHImage(this HObject obj) { HTuple pointer, type, width, heght; HOperatorSet.GetImagePointer1(obj, out pointer, out type, out width, out heght); HImage img = new HImage(); img.GenImage1(type, width, heght, pointer); return img; } public static Bitmap ConvertHImageTo16GrayBitmap(this HImage originHImage) { HImage hImage = originHImage.Clone(); //get_domain(Image, rectangle) //* 获取全图中像素灰度值的最大和最小值 //min_max_gray(rectangle, Image, 0, Min, Max, range) hImage.MinMaxGray(hImage.GetDomain(), 0, out double min, out double max, out double range); //* 将16位图的灰度值映射到0 - 255上 double mult = 255.0 / (max - min); double add = -mult * min; hImage = hImage.ScaleImage(mult, add); //* 转换为'byte'类型 //convert_image_type(Image_scaled, ImageConverted, 'byte') hImage = hImage.ConvertImageType("byte"); Bitmap showImage = hImage.ConvertHImageToBitmap(); hImage.Dispose(); return showImage; } public static Bitmap ConvertSignedHImageTo16GrayBitmap(this HImage originHImage) { HImage hImage = originHImage.Clone(); hImage = hImage.ConvertImageType("int4"); hImage = hImage.ScaleImage(1.0, 32768); hImage = hImage.ConvertImageType("uint2"); //get_domain(Image, rectangle) //* 获取全图中像素灰度值的最大和最小值 //min_max_gray(rectangle, Image, 0, Min, Max, range) hImage.MinMaxGray(hImage.GetDomain(), 0, out double min, out double max, out double range); //* 将16位图的灰度值映射到0 - 255上 double mult = 255.0 / (max - min); double add = -mult * min; hImage = hImage.ScaleImage(mult, add); //* 转换为'byte'类型 //convert_image_type(Image_scaled, ImageConverted, 'byte') hImage = hImage.ConvertImageType("byte"); Bitmap showImage = hImage.ConvertHImageToBitmap(); hImage.Dispose(); return showImage; } } }