Barcode.cs
16.1 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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using HalconDotNet;
using Asa.CameraFactory;
namespace Asa.Barcode
{
/// <summary>
/// 条码识别,1DBarcode、2DBarcode
/// </summary>
public class Identify
{
private CodeOrder order;
private CodeType type;
private int eyemBlockSize;
private int eyemRangeC;
private int eyemSymbolMin;
private int eyemSymbolMax;
private float zoom1D;
private float zoom2D;
/// <summary>
/// 条码识别,1DBarcode、2DBarcode
/// </summary>
/// <param name="configPath"></param>
/// <param name="logName"></param>
public Identify(string configPath, string logName = "Barcode.Identify")
{
GetConfig(configPath);
if (!string.IsNullOrWhiteSpace(logName))
Log.Load(logName);
}
/// <summary>
/// 获取条码
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public List<CodeInfo> GetCode(Bitmap image)
{
List<CodeInfo> code = new();
if (image == null) return code;
switch (order)
{
case CodeOrder.HalconOnly:
code.AddRange(HalconGetCode(image));
break;
case CodeOrder.EyemLibOnly:
code.AddRange(EyemGetCode(image));
break;
case CodeOrder.HalconEyemLib:
code.AddRange(HalconGetCode(image));
if (code.Count == 0) code.AddRange(EyemGetCode(image));
break;
case CodeOrder.EyemLibHalcon:
code.AddRange(EyemGetCode(image));
if (code.Count == 0) code.AddRange(HalconGetCode(image));
break;
}
return code;
}
private void GetConfig(string path)
{
string json = System.IO.File.ReadAllText(path);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new();
Dictionary<string, object> dic = (Dictionary<string, object>)serializer.DeserializeObject(json);
if (dic.TryGetValue("CodeOrder", out object value))
{
order = (CodeOrder)Enum.Parse(typeof(CodeOrder), value.ToString());
}
if (dic.TryGetValue("Halcon", out value))
{
Dictionary<string, object> param = (Dictionary<string, object>)value;
if (param.TryGetValue("CodeType", out value))
type = (CodeType)Enum.Parse(typeof(CodeType), value.ToString());
if (param.TryGetValue("Zoom1DCode", out value))
zoom1D = Convert.ToSingle(value);
if (param.TryGetValue("Zoom2DCode", out value))
zoom2D = Convert.ToSingle(value);
}
if (dic.TryGetValue("EyemLib", out value))
{
Dictionary<string, object> param = (Dictionary<string, object>)value;
if (param.TryGetValue("CodeType", out value))
type = (CodeType)Enum.Parse(typeof(CodeType), value.ToString());
if (param.TryGetValue("BlockSize", out value))
eyemBlockSize = Convert.ToInt32(value);
if (param.TryGetValue("RangeC", out value))
eyemRangeC = Convert.ToInt32(value);
if (param.TryGetValue("SymbolMin", out value))
eyemSymbolMin = Convert.ToInt32(value);
if (param.TryGetValue("SymbolMax", out value))
eyemSymbolMax = Convert.ToInt32(value);
}
}
private List<CodeInfo> HalconGetCode(Bitmap image)
{
List<CodeInfo> code = new();
Bitmap bmp = new(image); //防止原图被释放
switch (type)
{
case CodeType.All:
code.AddRange(HalconExtract1DCode(bmp, zoom1D));
code.AddRange(HalconExtract2DCode(bmp, zoom2D));
break;
case CodeType.Barcode1D:
code.AddRange(HalconExtract1DCode(bmp, zoom1D));
break;
case CodeType.Barcode2D:
code.AddRange(HalconExtract2DCode(bmp, zoom2D));
break;
}
return code;
}
private List<CodeInfo> EyemGetCode(Bitmap image)
{
List<CodeInfo> code = new();
string tempPath = AppDomain.CurrentDomain.BaseDirectory + string.Format("Img{0:yyyy_MM_dd HH_mm_ss}.png", DateTime.Now);
image.Save(tempPath, ImageFormat.Png);
switch (type)
{
case CodeType.All:
code.AddRange(EyemExtractCode(tempPath, "CODE_128|CODE_39|CODE_93", eyemBlockSize, eyemRangeC, eyemSymbolMin, eyemSymbolMax));
code.AddRange(EyemExtractCode(tempPath, "QR_CODE|DATA_MATRIX", eyemBlockSize, eyemRangeC, eyemSymbolMin, eyemSymbolMax));
break;
case CodeType.Barcode1D:
code.AddRange(EyemExtractCode(tempPath, "CODE_128|CODE_39|CODE_93", eyemBlockSize, eyemRangeC, eyemSymbolMin, eyemSymbolMax));
break;
case CodeType.Barcode2D:
code.AddRange(EyemExtractCode(tempPath, "QR_CODE|DATA_MATRIX", eyemBlockSize, eyemRangeC, eyemSymbolMin, eyemSymbolMax));
break;
}
System.IO.File.Delete(tempPath);
return code;
}
private List<CodeInfo> HalconExtract1DCode(Bitmap bmp, float zoom)
{
List<CodeInfo> codeInfo = new();
//图像转成halcon的类型
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
HObject hObj;
try
{
HOperatorSet.GenImageInterleaved(out hObj, bmpData.Scan0, "bgr", bmp.Width, bmp.Height, 0, "byte", 0, 0, 0, 0, -1, 0);
if (zoom != 1)
HOperatorSet.ZoomImageFactor(hObj, out hObj, zoom, zoom, "bilinear");
bmp.UnlockBits(bmpData);
}
catch (Exception ex)
{
bmp.UnlockBits(bmpData);
Log.Error("Extract1DCode", ex);
return codeInfo;
}
try
{
HOperatorSet.Rgb1ToGray(hObj, out HObject grayImage);
HOperatorSet.CreateBarCodeModel(new HTuple(), new HTuple(), out HTuple hv_BarCode); //创建条码模型
HOperatorSet.SetBarCodeParam(hv_BarCode, "num_scanlines", 5); //扫描线的最大数量
HOperatorSet.SetBarCodeParam(hv_BarCode, "min_identical_scanlines", 3); //成功解码最少扫描线数量
HOperatorSet.SetBarCodeParam(hv_BarCode, "start_stop_tolerance", "high"); //扫描线的起点和终点的容许误差,high误差大,low误差小
HOperatorSet.SetBarCodeParam(hv_BarCode, "max_diff_orient", 5); //条码相邻两条竖条边缘扭曲的最大角度容差
HOperatorSet.FindBarCode(grayImage, out HObject symbolRegions, hv_BarCode, "auto", out HTuple hv_String); //寻找条码
HOperatorSet.GetBarCodeResult(hv_BarCode, "all", "decoded_types", out HTuple hv_Type); //获取条码类型
HOperatorSet.GetBarCodeResult(hv_BarCode, "all", "orientation", out HTuple hv_Orientation); //获取条码方向,x轴逆时针[0,180],顺时针[0,-180]
HOperatorSet.SmallestRectangle2(symbolRegions, out HTuple row, out HTuple column, out HTuple phi, out HTuple length1, out HTuple length2);
HOperatorSet.ClearBarCodeModel(hv_BarCode); //清除条码模型
Log.Info("Halcon Extract1DCode Count=" + hv_String.Length);
if (hv_String.Length > 0)
{
int n = hv_String.SArr.Length;
for (int i = 0; i < n; i++)
{
CodeInfo info = new()
{
Text = hv_String.SArr[i].Trim(),
CodeType = hv_Type.SArr[i],
Angle = Convert.ToSingle(hv_Orientation.DArr[i]),
Center = new PointF(Convert.ToSingle(column.DArr[i] / zoom), Convert.ToSingle(row.DArr[i] / zoom)),
Size = new SizeF(Convert.ToSingle(length1.DArr[i] * 2), Convert.ToSingle(length2.DArr[i] * 2))
};
double tan = Math.Tan(AngleToRadian(0 - info.Angle));
info.Distance = Convert.ToSingle(Math.Abs((tan * info.Center.X - info.Center.Y) / Math.Sqrt(tan * tan + 1)));
codeInfo.Add(info);
}
}
}
catch (Exception ex)
{
Log.Error("Extract1DCode", ex);
}
return codeInfo;
}
private List<CodeInfo> HalconExtract2DCode(Bitmap bmp, float zoom)
{
List<CodeInfo> codeInfo = new();
//图像转成halcon的类型
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
HObject hObj;
try
{
HOperatorSet.GenImageInterleaved(out hObj, bmpData.Scan0, "bgr", bmp.Width, bmp.Height, 0, "byte", 0, 0, 0, 0, -1, 0);
if (zoom != 1)
HOperatorSet.ZoomImageFactor(hObj, out hObj, zoom, zoom, "bilinear");
bmp.UnlockBits(bmpData);
}
catch (Exception ex)
{
bmp.UnlockBits(bmpData);
Log.Error("Extract2DCode", ex);
return codeInfo;
}
string[] type = new string[] { "Data Matrix ECC 200", "QR Code", "PDF417" };
try
{
for (int i = 0; i < type.Length; i++)
{
HOperatorSet.Rgb1ToGray(hObj, out HObject grayImage);
//支持‘Data Matrix ECC 200’、‘QR Code’和‘PDF417’共3种类型
//‘standard_recognition’、‘enhanced_recognition’、‘maximum_recognition’
HOperatorSet.CreateDataCode2dModel(type[i], "default_parameters", "maximum_recognition", out HTuple dataCodeHandle);
HOperatorSet.SetDataCode2dParam(dataCodeHandle, "timeout", 1000); //一个二维码的解码时间
//HOperatorSet.SetDataCode2dParam(dataCodeHandle, "symbol_size_min", 16); //码粒最小个数
//HOperatorSet.SetDataCode2dParam(dataCodeHandle, "symbol_size_max", 30); //码粒最大个数
if (i != 2)
{
HOperatorSet.SetDataCode2dParam(dataCodeHandle, "module_size_min", 3); //码粒最小像素
HOperatorSet.SetDataCode2dParam(dataCodeHandle, "module_size_max", 20); //码粒最大像素
}
HOperatorSet.FindDataCode2d(grayImage, out HObject symbolXLDs, dataCodeHandle, "stop_after_result_num", 5, out HTuple resultHandles, out HTuple decodedDataStrings);
//码粒的个数
HOperatorSet.GetDataCode2dResults(dataCodeHandle, "all_results", "symbol_rows", out HTuple _rows);
HOperatorSet.GetDataCode2dResults(dataCodeHandle, "all_results", "symbol_cols", out HTuple _cols);
//每个码粒的宽高
HOperatorSet.GetDataCode2dResults(dataCodeHandle, "all_results", "module_height", out HTuple _height);
HOperatorSet.GetDataCode2dResults(dataCodeHandle, "all_results", "module_width", out HTuple _width);
HOperatorSet.AreaCenterXld(symbolXLDs, out HTuple hv_Area, out HTuple hv_Row, out HTuple hv_Column, out HTuple hv_PointOrder);
//释放
HOperatorSet.ClearDataCode2dModel(dataCodeHandle);
Log.Info("Halcon Extract2DCode " + type[i] + " Count=" + decodedDataStrings.Length);
if (decodedDataStrings.Length > 0)
{
int n = decodedDataStrings.SArr.Length;
for (int j = 0; j < n; j++)
{
CodeInfo info = new()
{
Text = decodedDataStrings.SArr[j].Trim(),
CodeType = type[j],
Angle = 0,
Center = new PointF(Convert.ToSingle(hv_Column.DArr[j] / zoom), Convert.ToSingle(hv_Row.DArr[j] / zoom)),
Size = new SizeF(Convert.ToSingle(_cols.LArr[j] * _width.DArr[j]), Convert.ToSingle(_rows.LArr[j] * _height.DArr[j])),
Distance = 0
};
codeInfo.Add(info);
}
}
}
}
catch (Exception ex)
{
Log.Error("Extract2DCode", ex);
}
return codeInfo;
}
private unsafe List<CodeInfo> EyemExtractCode(string file, string codeType, int iBlockSize, int iRangeC, int iSymbolMin, int iSymbolMax)
{
List<CodeInfo> codeInfo = new();
EyemAPI.DataCodeHandle hObject = null;
EyemAPI.EyemImage tpImage;
tpImage.ucpImage = IntPtr.Zero;
try
{
int rtn = EyemAPI.eyemImageRead(file, 3, out tpImage);
EyemAPI.EyemRect tpRoi = new()
{
iXs = 0,
iYs = 0,
iWidth = tpImage.iWidth,
iHeight = tpImage.iHeight
};
string ext = System.IO.Path.GetExtension(file);
file = file.Substring(0, file.Length - ext.Length);
int result = EyemAPI.eyemDetectAndDecode(tpImage, tpRoi, file, codeType,
out hObject, out EyemAPI.EyemBarCode* tpResults, out int ipNum, false, iBlockSize, iRangeC, iSymbolMin, iSymbolMax, 1d);
if (result != 0 || ipNum == 0)
{
Log.Info("EyemExtractCode " + codeType + " result=" + result + " ipNum=" + ipNum);
return codeInfo;
}
Log.Info("EyemExtractCode " + codeType + " Count=" + ipNum);
for (int i = 0; i < ipNum; i++)
{
CodeInfo info = new()
{
Text = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(tpResults[i].hText).Trim(),
CodeType = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(tpResults[i].hType).Trim(),
Angle = Convert.ToSingle(tpResults[i].dAngle) + 180,
Center = new PointF(tpResults[i].iCenterX, tpResults[i].iCenterY),
Size = new SizeF(0, 0)
};
double tan = Math.Tan(AngleToRadian(0 - info.Angle));
info.Distance = Convert.ToSingle(Math.Abs((tan * info.Center.X - info.Center.Y) / Math.Sqrt(tan * tan + 1)));
codeInfo.Add(info);
}
}
catch (Exception ex)
{
Log.Error("EyemExtractCode", ex);
}
finally
{
if (hObject != null)
hObject.Dispose();
if (file != null)
EyemAPI.eyemImageFree(tpImage.ucpImage);
}
return codeInfo;
}
private double AngleToRadian(float angle)
{
//角度转弧度
return angle * Math.PI / 180;
}
}
}