HDCodeHelper.cs
24.6 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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CodeLibrary
{
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)
{
HDLogUtil.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);
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);
//HOperatorSet.ClearObj
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)
{
HDLogUtil.error("处理二维码出错:索引=" + i + "," + resultList.ToString());
}
}
}
HDLogUtil.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)
{
HDLogUtil.error("DecodeCode出错:" + ex.ToString());
HDLogUtil.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);
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)
{
HDLogUtil.error("将BitMap转换为HObject对象出错:" + ex.ToString());
ho_Image = null;
}
return false ;
}
internal static string GetCodeParamFilePath(string codeType)
{
if (CodeParamPath.Equals(""))
{
CodeParamPath = @"\CodeParam\";
}
string appPath = Application.StartupPath + CodeParamPath;
if (!Directory.Exists(appPath))
{
Directory.CreateDirectory(appPath);
}
string filePath = appPath + codeType + ".dcm";
return filePath;
}
public static List<CodeInfo> DecodeBarCode(string filePath)
{
HObject ho_Image;
HOperatorSet.GenEmptyObj(out ho_Image);
ho_Image.Dispose();
HOperatorSet.ReadImage(out ho_Image, filePath);
return DecodeBarCode(ho_Image);
}
//public static List<CodeInfo> DecodeBarCode(Bitmap bitmap)
//{
// HObject ho_image;
// Bitmap2HObjectBpp24(bitmap,out ho_image);
// return DecodeBarCode(ho_image);
//}
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)
{
HDLogUtil.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;
}
}
public static void CloseCamera(string cameraName)
{
Camera._cam.Close(cameraName);
}
public static void CloseAllCamera()
{
Camera._cam.CloseAll();
}
private static int ScanCount = 0;
[HandleProcessCorruptedStateExceptions]
public static List<string> CameraScan(string deviceName, List<string> codeTypeList, int codeCount,params string[] cameraList)
{
List<string> codeList = new List<string>();
if (cameraList == null || cameraList.Length <= 0)
{
return codeList;
}
try
{
foreach (string cameraName in cameraList)
{
if (cameraName.Trim().Equals(""))
{
continue;
}
ScanCount++;
DateTime startTime = DateTime.Now;
if (deviceName != "")
{
HDLogUtil.debug(deviceName + " 【" + cameraName + "】开始取图片");
}
HalconDotNet.HObject ho_Image = null;
bool findRightCode = false;
try
{
ho_Image = Camera._cam.CaptureOnImage(cameraName);
if (ho_Image == null)
{
HDLogUtil.error(deviceName + " 【" + cameraName + "】取图片失败[" + Camera._cam.ErrInfo + "],关闭相机");
CloseCamera(cameraName);
continue;
}
HDLogUtil.debug(deviceName + " 【" + cameraName + "】取图片完成,开始扫码");
List<CodeInfo> cc = new List<CodeInfo>();
string r = "";
foreach (string codeType in codeTypeList)
{
//判断是否是一维码
if (codeType.ToLower().Equals("barcode"))
{
cc = HDCodeHelper.DecodeBarCode(ho_Image);
}
else
{
cc = HDCodeHelper.DecodeCode(ho_Image, codeType, GetCodeParamFilePath(codeType), codeCount, 2500);
}
foreach (CodeInfo c in cc)
{
string str = ReplaceCode(c.CodeStr);
if (!codeList.Contains(str))
{
codeList.Add(str);
r = r + "##" + str;
if (!findRightCode)
{
findRightCode = HasRightCode(str);
}
}
}
}
//if (!findRightCode)
//{
// SaveImageToFile(deviceName, cameraName, ho_Image);
//}
if (deviceName != "" || r != "")
{
HDLogUtil.info(deviceName + " 【" + cameraName + "】扫码完成【" + GetSpanStr(DateTime.Now - startTime) + "】[" + findRightCode + "]" + ScanCount + " :" + r);
}
}
catch (AccessViolationException e)
{
HDLogUtil.error(deviceName + " 扫码出现AccessViolationException异常,关闭相机【" + cameraName + "】:" + e.ToString());
Camera._cam.Close(cameraName);
// GC.Collect();
}
catch (Exception ex)
{
HDLogUtil.error(deviceName + " 扫码出错:" + ex.ToString());
}
finally
{
if (ho_Image != null)
{
ho_Image.Dispose();
}
//int value = ScanCount % 30;
//if (value.Equals(0))
//{
// GC.Collect();
// GC.WaitForPendingFinalizers();
//}
}
}
}
catch (AccessViolationException e)
{
HDLogUtil.error(deviceName + " 扫码出现AccessViolationException异常,关闭所有相机:" + e.ToString());
Camera._cam.CloseAll();
//GC.Collect();
}
catch (Exception ex)
{
HDLogUtil.error(deviceName + " 扫码出错:" + ex.ToString());
}
return codeList;
}
private static string GetSpanStr(TimeSpan span)
{
//return Convert.ToDateTime(span.ToString()).ToString("HH:mm:ss");
string seconds = Math.Round(span.TotalSeconds % 60, 1).ToString();
if (seconds.IndexOf(".") >= 0)
{
seconds = seconds.ToString().PadLeft(4, '0');
}
else
{
seconds = seconds.ToString().PadLeft(2, '0');
}
return span.Hours.ToString().PadLeft(2, '0') + ":" + span.Minutes.ToString().PadLeft(2, '0') + ":" + seconds;
}
private static string ReplaceCode(string message)
{
message = message.Trim();
message = message.Replace("\r", "");
message = message.Replace("\n", "");
char a = (char)02;
message = message.Replace(a.ToString(), "");
message = message.Trim();
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
byte[] bytes = asciiEncoding.GetBytes(message);
List<byte> newBytes = new List<byte>();
foreach (byte by in bytes)
{
int value = (int)by;
if (value.Equals(24) || value.Equals(30) || value.Equals(29) || value.Equals(4))
{
continue;
}
if (!value.Equals(24))
{
newBytes.Add(by);
}
}
message = asciiEncoding.GetString(newBytes.ToArray());
return message;
}
private static bool HasRightCode(params string[] codes)
{
//分号分割后长度=4,L,E,B,R
try
{
foreach (string code in codes)
{
string[] strarray = code.Split(';');
if (strarray.Length == 4)
{
if (strarray[0].StartsWith("L") &&
strarray[1].StartsWith("E") &&
strarray[2].StartsWith("B"))
{
return true;
}
}
}
}
catch (Exception ex)
{
}
return false;
}
}
public class CodeInfo
{
public string CodeStr = "";
public int X = 0;
public int Y = 0;
public string CodeType;
public double Orientation = 0;
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;
}
public string GetCodeStr()
{
return Gb2312Correct(CodeStr);
}
/// <summary>
/// 判断字符串中是否包含中文
/// </summary>
/// <param name="str">需要判断的字符串</param>
/// <returns>判断结果</returns>
public static bool HasChinese(string str)
{
return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");
}
/// <summary>
/// utf8文字用gb2312格式显示时候乱码,需要转换为gb2312
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string Gb2312Correct(string text)
{
if (HasChinese(text) == false)
{
return text;
}
//声明字符集
System.Text.Encoding utf8, gb2312;
//utf8
utf8 = System.Text.Encoding.GetEncoding("utf-8");
//gb2312
gb2312 = System.Text.Encoding.GetEncoding("gb2312");
byte[] gb;
gb = utf8.GetBytes(text);
gb = System.Text.Encoding.Convert(utf8, gb2312, gb);
//返回转换后的字符
return gb2312.GetString(gb);
}
}
}