HDCodeHelper.cs 17.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ScanCodeServer
{
    public class HDCodeHelper
    {
        /// <summary>
        /// 二维码参数文件保存的默认路径\CodeParam\
        /// </summary>
        public static string CodeParamPath = @"CodeParam";
        /// <summary>
        /// 显示的窗口
        /// </summary>
        public static HWindow HalconWindow = null;

        /// <summary>
        /// 根据图片路径解析二维码
        /// </summary>
        /// <param name="filePath">图片路径</param>
        /// <param name="codeCount">二维码数量</param>
        /// <param name="codeParamPath">二维码参数路径,""表示不使用参数</param>
        /// <param name="paramType">二维码类型,不传类型默认Data Matrix ECC 200</param>
        /// <returns>解析到的二维码</returns>
        public static List<CodeInfo> DecodeCode(string filePath, int codeCount, string codeParamPath, params string[] paramType)
        {
            HObject ho_Image;
            HOperatorSet.GenEmptyObj(out ho_Image);
            ho_Image.Dispose();
            HOperatorSet.ReadImage(out ho_Image, filePath);
            if (HalconWindow != null)
            {
                HOperatorSet.DispObj(ho_Image, HalconWindow);
            }
            return DecodeCode(ho_Image, codeCount, codeParamPath, paramType);
        }
        ///// <summary>
        ///// 根据图片解析二维码
        ///// </summary>
        ///// <param name="map">图片对象</param>
        ///// <param name="codeCount">二维码数量</param>
        ///// <param name="codeParamPath">二维码参数路径,""表示不使用参数</param>
        ///// <param name="paramType">二维码类型,不传类型默认Data Matrix ECC 200</param>
        ///// <returns>解析到的二维码</returns>
        //public static List<CodeInfo> DecodeCode(Bitmap map, int codeCount, string codeParamPath, params string[] paramType)
        //{
        //    HObject ho_image;
        //    Bitmap2HObjectBpp24(map,out ho_image);
        //    return DecodeCode(ho_image, codeCount, codeParamPath, paramType);
        //}
        /// <summary>
        /// 根据图片解析二维码
        /// </summary>
        /// <param name="ho_Image">Halcon中的图片对象</param>
        /// <param name="codeCount">二维码数量</param>
        /// <param name="codeParamPath">二维码参数路径,""表示不使用参数</param>
        /// <param name="paramType">二维码类型,不传类型默认Data Matrix ECC 200</param>
        /// <returns>解析到的二维码</returns>
        public static List<CodeInfo> DecodeCode(HObject ho_Image, int codeCount, string codeParamPath, params string[] paramType)
        {
            List<string> codeType = new List<string>(paramType.ToList());
            if (codeType.Count<string>() <= 0)
            {
                codeType.Add("Data Matrix ECC 200");
            }
            List<CodeInfo> codeList = new List<CodeInfo>();

            foreach (string t in codeType)
            {
                List<CodeInfo> array = DecodeCode(ho_Image, t, codeParamPath, codeCount);
                codeList.AddRange(array.ToArray<CodeInfo>());
            }

            return codeList;
        }
        public static List<CodeInfo> DecodeCode(HObject ho_Image, string symbolType, string hv_model_path, int codeCount, int timeOut = 1500)
        {
            Common.log.Debug(" DecodeCode[" + symbolType + "][" + hv_model_path + "][" + codeCount + "] 开始");
            List<CodeInfo> codeList = new List<CodeInfo>();
            try
            {
                HTuple hv_Area = null;
                HTuple hv_Row1 = null;
                HTuple hv_Column = null;
                HTuple hv_PointOrder = null;
                HObject ho_SymbolXLDs;

                HTuple hv_ResultHandles = null;
                HTuple hv_DecodedDataStrings = null;
                HTuple hv_DataCodeHandle = null;
                HOperatorSet.GenEmptyObj(out ho_SymbolXLDs);
                HOperatorSet.CreateDataCode2dModel(symbolType, "default_parameters", "maximum_recognition", out hv_DataCodeHandle);

                //string hv_model_path = GetCodeParamFilePath(symbolType);
                if (!hv_model_path.Equals("") && File.Exists(hv_model_path))
                {
                    HOperatorSet.ReadDataCode2dModel(hv_model_path, out hv_DataCodeHandle);
                }
                //    HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle, "timeout", 3000);
                ho_SymbolXLDs.Dispose();
                // set_data_code_2d_param(DataCodeHandle, 'timeout', 200)
                HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle, "timeout", timeOut);
                //HOperatorSet.SetDataCode2dParam(hv_DataCodeHandle, "string_encoding", "raw");
                if (codeCount <= 0)
                {
                    HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
                    new HTuple(), new HTuple(), out hv_ResultHandles, out hv_DecodedDataStrings);
                }
                else
                {
                    HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
                    "stop_after_result_num", codeCount, out hv_ResultHandles, out hv_DecodedDataStrings);
                }
                HOperatorSet.AreaCenterXld(ho_SymbolXLDs, out hv_Area, out hv_Row1, out hv_Column, out hv_PointOrder);
                if (HalconWindow != null)
                {
                    ShowImage(HalconWindow, ho_Image, ho_SymbolXLDs);
                }
                HOperatorSet.ClearDataCode2dModel(hv_DataCodeHandle);

                if (hv_DecodedDataStrings.Length > 0)
                {
                    string[] resultList = hv_DecodedDataStrings.SArr;
                    for (int i = 0; i < hv_DecodedDataStrings.SArr.Length; i++)
                    {
                        try
                        {
                            int x = (int)Math.Round(hv_Column.DArr[i]);
                            int y = (int)Math.Round(hv_Row1.DArr[i]);
                            string str = hv_DecodedDataStrings.SArr[i];
                            CodeInfo code = new CodeInfo(str, x, y);
                            codeList.Add(code);
                        }
                        catch (Exception ex)
                        {
                            Common.log.Error("处理二维码出错:索引=" + i + "," + resultList.ToString());
                        }
                    }
                }
                Common.log.Debug(" DecodeCode[" + symbolType + "][" + hv_model_path + "][" + codeCount + "] 结束,返回数量:" + codeList.Count);
                if (hv_Area != null)
                {
                    hv_Area.UnPinTuple();
                }
                if (hv_Row1 != null)
                {
                    hv_Row1.UnPinTuple();
                }
                if (hv_Column != null)
                {
                    hv_Column.UnPinTuple();
                }
                if (hv_PointOrder != null)
                {
                    hv_PointOrder.UnPinTuple();
                }
                if (hv_ResultHandles != null)
                {
                    hv_ResultHandles.UnPinTuple();
                }
                if (hv_DecodedDataStrings != null)
                {
                    hv_DecodedDataStrings.UnPinTuple();
                }
                if (hv_DataCodeHandle != null)
                {
                    hv_DataCodeHandle.UnPinTuple();
                }

                if (ho_SymbolXLDs != null)
                {
                    ho_SymbolXLDs.Dispose();
                    ho_SymbolXLDs = null;
                }

                return codeList;
            }
            catch (Exception ex)
            {
                Common.log.Error("DecodeCode出错:" + ex.ToString());
                Common.log.Debug(" DecodeCode[" + symbolType + "][" + hv_model_path + "][" + codeCount + "] 结束,返回数量:" + codeList.Count);
                return codeList;
            }

        }
        internal static void ShowImage(HWindow window, HObject ho_Image, HObject ho_SymbolXLDs)
        {
            if (window == null || ho_Image == null)
            {
                return;
            }
            Task.Factory.StartNew(delegate ()
            {
                try
                {

                    HTuple width, height;
                    //int dWidth = 0; int dHeight = 0;
                    HOperatorSet.GetImageSize(ho_Image, out width, out height);

                    int dWidth = (int)width.D;
                    int dHeight = (int)height.D;
                    window.SetPart(0, 0, dHeight, dWidth);

                    HOperatorSet.SetColor(window, "red");
                    HOperatorSet.SetLineWidth(window, new HTuple(2));
                    if (ho_Image != null)
                    {
                        HOperatorSet.DispObj(ho_Image, window);
                    }
                    if (ho_SymbolXLDs != null)
                    {
                        HOperatorSet.DispObj(ho_SymbolXLDs, window);
                    }
                }
                catch (Exception ex)
                {

                }
            });
        }
        /// <summary>
        /// 将BitMap转换为HObject对象
        /// </summary> 
        public static bool Bitmap2HObjectBpp24(Bitmap bmp, out HObject ho_Image)
        {
            ho_Image = null;
            try
            {
                HOperatorSet.GenEmptyObj(out ho_Image);
                ho_Image.Dispose();
                Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);

                BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);
                if (bmp.PixelFormat == PixelFormat.Format8bppIndexed)
                    HOperatorSet.GenImage1(out ho_Image, "byte", bmp.Width, bmp.Height, srcBmpData.Scan0);
                else
                    HOperatorSet.GenImageInterleaved(out ho_Image, srcBmpData.Scan0, "bgrx", bmp.Width, bmp.Height, 0, "byte", 0, 0, 0, 0, -1, 0);
                bmp.UnlockBits(srcBmpData);

                return true;
            }
            catch (Exception ex)
            {
                Common.log.Error("将BitMap转换为HObject对象出错:" + ex.ToString());
                ho_Image = null;
            }
            return false;
        }
        public static void HObject2Bpp8(HObject image, out Bitmap res)
        {
            HTuple hpoint, type, width, height;

            const int Alpha = 255;
            long[] ptr = new long[2];
            HOperatorSet.GetImagePointer1(image, out hpoint, out type, out width, out height);

            res = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
            ColorPalette pal = res.Palette;
            for (int i = 0; i <= 255; i++)
            {
                pal.Entries[i] = Color.FromArgb(Alpha, i, i, i);
            }
            res.Palette = pal;
            Rectangle rect = new Rectangle(0, 0, width, height);
            BitmapData bitmapData = res.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
            int PixelSize = Bitmap.GetPixelFormatSize(bitmapData.PixelFormat) / 8;
            ptr[0] = (long)bitmapData.Scan0;
            ptr[1] = hpoint.L;
            if (width % 4 == 0)
                CopyMemory((IntPtr)ptr[0], (IntPtr)ptr[1], width * height * PixelSize);
            else
            {
                for (int i = 0; i < height - 1; i++)
                {
                    ptr[1] += width;
                    CopyMemory((IntPtr)ptr[0], (IntPtr)ptr[1], width * PixelSize);
                    ptr[0] += bitmapData.Stride;
                }
            }
            res.UnlockBits(bitmapData);

        }
        [DllImport("Kernel32.dll")]
        private static extern void CopyMemory(IntPtr dest, IntPtr source, int size);
        internal static string GetCodeParamFilePath(string codeType)
        {
            string appPath = Path.Combine(Application.StartupPath, "..\\");
            
            if (!Directory.Exists(Path.Combine(appPath,CodeParamPath)))
            {
                appPath = Application.StartupPath;
            }

            string filePath = Path.Combine(Path.Combine(appPath, CodeParamPath), codeType + ".dcm");
            return filePath;
        }
        public static List<CodeInfo> DecodeBarCode(HObject ho_Image)
        {
            List<CodeInfo> codeList = new List<CodeInfo>();
            try
            {
                HObject ho_GrayImage, ho_SymbolRegions;
                HTuple hv_BarCodeHandle = null, hv_DecodedDataStrings = null, hv_DecodedDataTypes = null; ;
                HOperatorSet.GenEmptyObj(out ho_GrayImage);
                HOperatorSet.GenEmptyObj(out ho_SymbolRegions);

                HTuple hv_Area = null;
                HTuple hv_Row1 = null;
                HTuple hv_Column = null;
                HTuple hv_Orientation = null;
                HOperatorSet.Rgb1ToGray(ho_Image, out ho_GrayImage);
                HOperatorSet.GenEmptyObj(out ho_SymbolRegions);
                ho_SymbolRegions.Dispose();

                HOperatorSet.CreateBarCodeModel(new HTuple(), new HTuple(), out hv_BarCodeHandle);

                HOperatorSet.FindBarCode(ho_GrayImage, out ho_SymbolRegions, hv_BarCodeHandle, "auto", out hv_DecodedDataStrings);
                //HOperatorSet.AreaCenterXld(ho_SymbolRegions, out hv_Area, out hv_Row1, out hv_Column, out hv_PointOrder);
                HOperatorSet.GetBarCodeResult(hv_BarCodeHandle, "all", "decoded_types", out hv_DecodedDataTypes);
                HOperatorSet.GetBarCodeResult(hv_BarCodeHandle, "all", "orientation", out hv_Orientation);
                HOperatorSet.AreaCenter(ho_SymbolRegions, out hv_Area, out hv_Row1, out hv_Column);
                if (HalconWindow != null)
                {
                    HOperatorSet.SetDraw(HalconWindow, "margin");
                    ShowImage(HalconWindow, ho_Image, ho_SymbolRegions);
                }

                string[] resultList = hv_DecodedDataStrings.SArr;
                if (resultList.Length > 0)
                {
                    for (int i = 0; i < hv_DecodedDataStrings.SArr.Length; i++)
                    {
                        try
                        {
                            int x = (int)Math.Round(hv_Column.DArr[i]);
                            int y = (int)Math.Round(hv_Row1.DArr[i]);
                            string str = hv_DecodedDataStrings.SArr[i];
                            string type = hv_DecodedDataTypes.SArr[i];
                            CodeInfo code = new CodeInfo(str, x, y, type);
                            code.Orientation = hv_Orientation.DArr[i];
                            codeList.Add(code);
                            if (HalconWindow != null)
                            {
                                HOperatorSet.SetTposition(HalconWindow, new HTuple(x), new HTuple(y));
                                HOperatorSet.WriteString(HalconWindow, new HTuple("(" + (i + 1).ToString() + ")"));
                            }
                        }
                        catch (Exception ex)
                        {
                            Common.log.Error("处理一维码出错:索引=" + i + "," + resultList.ToString());
                        }
                    }
                }
                HOperatorSet.ClearBarCodeModel(hv_BarCodeHandle);
                if (hv_Area != null)
                {
                    hv_Area.UnPinTuple();
                }
                if (hv_Row1 != null)
                {
                    hv_Row1.UnPinTuple();
                }
                if (hv_Column != null)
                {
                    hv_Column.UnPinTuple();
                }
                if (hv_Orientation != null)
                {
                    hv_Orientation.UnPinTuple();
                }
                if (ho_GrayImage != null)
                {
                    ho_GrayImage.Dispose();
                    ho_GrayImage = null;
                }
                if (ho_SymbolRegions != null)
                {
                    ho_SymbolRegions.Dispose();
                    ho_SymbolRegions = null;
                }

                return codeList;
            }
            catch (Exception ex)
            {
                return codeList;
            }
        }

    }


    [DataContract]
    public class CodeInfo
    {
        [DataMember]
        public string CodeStr = "";
        [DataMember]
        public int X = 0;
        [DataMember]
        public int Y = 0;
        [DataMember]
        public string CodeType;
        [DataMember]
        public double Orientation = 0;
        public CodeInfo() { }
        public CodeInfo(string codeStr, int x, int y)
        {
            this.CodeStr = codeStr;
            this.X = x;
            this.Y = y;
        }
        public CodeInfo(string codeStr, int x, int y, string type)
        {
            this.CodeType = type;
            this.CodeStr = codeStr;
            this.X = x;
            this.Y = y;
        }
    }
}