领胜LDS 键盘AOI检测项目
wells.liu
2020-07-06 b016e35f170a6e1a98d39f125762f97af677fd20
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
628
629
630
631
632
633
634
635
636
637
using Bro.Common.Helper;
using Bro.UI.Config.Helper;
using Bro.UI.Config.MenuForms;
using Bro.UI.Model.Winform;
using HalconDotNet;
using HDisplay;
using HDisplay.ViewROI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace Bro.UI.Config
{
    [MenuNode("EditModel", "模板编辑", 4, "View2", true)]
    public partial class FrmEditModel : MenuFrmBase
    {
        CanvasImage canvas = new CanvasImage();
        HTuple modelId = null;
        HalconDisplay hDisplay = new HalconDisplay();
 
        CreateShapeModelConfig modelConfig = new CreateShapeModelConfig();
        FindShapeModelConfig findConfig = new FindShapeModelConfig();
        public FrmEditModel()
        {
            InitializeComponent();
 
            //canvas.Dock = DockStyle.Fill;
            //plImage.Controls.Clear();
            //plImage.Controls.Add(canvas);
 
            hDisplay.Dock = DockStyle.Fill;
            plImage.Controls.Clear();
            plImage.Controls.Add(hDisplay);
 
            pgCreateModel.SelectedObject = modelConfig;
            pgFindConfig.SelectedObject = findConfig;
 
            dgvImages.AutoGenerateColumns = false;
        }
 
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 1)
            {
                canvas.Elements.Clear();
            }
        }
 
        private void btnLoadImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;
            ofd.Filter = "图片文件|*.bmp;*.png;*.jpg;*.jpeg;*.tif|所有文件|*.*";
 
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //Bitmap map = (Bitmap)Bitmap.FromFile(ofd.FileName);
                //canvas.LoadImage(map);
 
                LoadImage(ofd.FileName);
            }
        }
 
        private void LoadImage(string imgFileName)
        {
            hDisplay.ClearDisplay();
 
            hDisplay.Image?.Dispose();
            HImage hImage = new HImage();
            hImage.ReadImage(imgFileName);
            hDisplay.Image = hImage;
            hDisplay.Refresh();
        }
 
        private void btnCreateModel_Click(object sender, EventArgs e)
        {
            if (hDisplay.Image == null)
            {
                MessageBox.Show("请先载入产品图片");
                return;
            }
 
            if (hDisplay.ROIController.ROIList.Count != 1)
            {
                MessageBox.Show("请仅设置一个矩阵ROI");
                return;
            }
 
            HOperatorSet.ClearAllShapeModels();
            modelId = null;
 
            HObject rectObj = null;
            HOperatorSet.HomMat2dIdentity(out HTuple identityMatrix);
            HTuple transformMatrix = null;
 
            if (hDisplay.ROIController.ROIList[0] is ROIRectangle1 rect1)
            {
                HOperatorSet.GenRectangle1(out rectObj, rect1.Row1, rect1.Col1, rect1.Row2, rect1.Col2);
                HOperatorSet.HomMat2dTranslate(identityMatrix, (rect1.Row1 + rect1.Row2) / 2.0, (rect1.Col1 + rect1.Col2) / 2.0, out transformMatrix);
            }
            else if (hDisplay.ROIController.ROIList[0] is ROIRectangle2 rect2)
            {
                HOperatorSet.GenRectangle2(out rectObj, rect2.MidR, rect2.MidC, rect2.Phi, rect2.Length1, rect2.Length2);
                HOperatorSet.HomMat2dTranslate(identityMatrix, rect2.MidR, rect2.MidC, out transformMatrix);
            }
            else
            {
                MessageBox.Show("请仅设置一个矩阵ROI");
                return;
            }
 
            HOperatorSet.ReduceDomain(hDisplay.Image, rectObj, out HObject imageReduced);
 
            HTuple config = modelConfig.GetHTuple();
            HOperatorSet.CreateShapeModel(imageReduced, config[0], config[1], config[2], config[3], config[4], config[5], config[6], config[7], out modelId);
 
            HOperatorSet.GetShapeModelContours(out HObject modelContours, modelId, 1);
            HOperatorSet.AffineTransContourXld(modelContours, out HObject countoursAffinTrans, transformMatrix);
 
            hDisplay.ClearGraphicStack();
            hDisplay.AddObjectToGraphicStack(hDisplay.Image);
            hDisplay.AddObjectToGraphicStack(countoursAffinTrans);
            hDisplay.Refresh();
 
            MessageBox.Show("模板创建成功");
        }
 
        private void btnSaveModel_Click(object sender, EventArgs e)
        {
            if (modelId == null)
            {
                MessageBox.Show("模板句柄为空,无法保存");
                return;
            }
 
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.SupportMultiDottedExtensions = false;
            sfd.Filter = "模板文件|*.shm";
            sfd.DefaultExt = "shm";
 
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                HOperatorSet.WriteShapeModel(modelId, sfd.FileName);
                MessageBox.Show("模板保存完成");
            }
        }
 
        private void btnLoadModel_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "模板文件|*.shm";
            ofd.Multiselect = false;
 
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                lblModel.Text = "";
 
                HOperatorSet.ReadShapeModel(ofd.FileName, out modelId);
                lblModel.Text = ofd.FileName;
            }
        }
 
        private void btnLoadImageFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = false;
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                lblImageFolder.Text = fbd.SelectedPath;
                DirectoryInfo dir = new DirectoryInfo(fbd.SelectedPath);
                List<string> suffixList = new List<string>() { "bmp", "png", "jpg", "jpeg", "tif" };
                var imgFileNames = dir.GetFiles().ToList().Where(u => suffixList.Any(s => u.Name.ToLower().EndsWith(s)))
                    .Select(u =>
                    {
                        TestCase tc = new TestCase();
                        tc.Name = u.Name;
                        tc.FullName = u.FullName;
                        tc.ModelMatchNum = 0;
                        return tc;
                    }).ToList();
 
                dgvImages.DataSource = imgFileNames;
            }
        }
 
        private void dgvImages_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvImages.Rows[e.RowIndex].DataBoundItem is TestCase tc)
            {
                LoadImage(tc.FullName);
            }
        }
 
        private void btnTestCurrent_Click(object sender, EventArgs e)
        {
            if (!CheckBeforeTest())
            {
                return;
            }
 
            RunSelected();
        }
 
        private bool RunSelected(int step = 0)
        {
            int selectedIndex = dgvImages.SelectedRows[0].Index;
            if (step != 0)
            {
                int afterIndex = selectedIndex + step;
 
                if (afterIndex < 0)
                {
                    //MessageBox.Show("当前已经是第一项");
                    return false;
                }
 
                if (afterIndex >= dgvImages.Rows.Count)
                {
                    //MessageBox.Show("当前已经是最后一项");
                    return false;
                }
 
                dgvImages.Rows[selectedIndex].Selected = false;
                dgvImages.Rows[afterIndex].Selected = true;
                dgvImages.FirstDisplayedScrollingRowIndex = afterIndex;
            }
 
            TestCase tc = dgvImages.SelectedRows[0].DataBoundItem as TestCase;
            LoadImage(tc.FullName);
 
            HTuple findConfigTuple = findConfig.GetHTuple();
            HOperatorSet.FindShapeModel(hDisplay.Image, modelId, findConfigTuple[0], findConfigTuple[1], findConfigTuple[2], findConfigTuple[3], findConfigTuple[4], findConfigTuple[5], findConfigTuple[6], findConfigTuple[7], out HTuple rows, out HTuple cols, out HTuple angles, out HTuple scores);
 
            tc.ModelMatchNum = scores.Length;
            HOperatorSet.GetShapeModelContours(out HObject modelContours, modelId, 1);
            HOperatorSet.CountObj(modelContours, out HTuple objCount);
            HOperatorSet.HomMat2dIdentity(out HTuple identityMatrix);
            for (int i = 0; i < tc.ModelMatchNum; i++)
            {
                HOperatorSet.CopyObj(modelContours, out HObject model, 1, objCount);
 
                HOperatorSet.HomMat2dRotate(identityMatrix, angles[i], 0, 0, out HTuple transformMatrix);
                HOperatorSet.HomMat2dTranslate(transformMatrix, rows[i], cols[i], out transformMatrix);
                HOperatorSet.AffineTransContourXld(model, out HObject affinedContour, transformMatrix);
 
                hDisplay.AddObjectToGraphicStack(affinedContour);
            }
            hDisplay.Refresh();
            dgvImages.Invalidate();
 
            return true;
        }
 
        private bool CheckBeforeTest()
        {
            if (modelId == null)
            {
                MessageBox.Show("当前未编辑或者载入模板,请创建模板或者选择模板文件载入");
                return false;
            }
 
            if (dgvImages.SelectedRows.Count == 0)
            {
                MessageBox.Show("当前图片列表未选择测试项,请选择需要测试的图片");
                return false;
            }
 
            return true;
        }
 
        private void btnTestNext_Click(object sender, EventArgs e)
        {
            if (!CheckBeforeTest())
            {
                return;
            }
 
            if (!RunSelected(1))
            {
                MessageBox.Show("当前已经是最后一项");
            }
        }
 
        private void btnTestAll_Click(object sender, EventArgs e)
        {
            if (dgvImages.Rows.Count <= 0)
            {
                MessageBox.Show("当前无待检测图片");
                return;
            }
 
            dgvImages.FirstDisplayedScrollingRowIndex = 0;
            dgvImages.Rows[0].Selected = true;
 
            bool flag = RunSelected(0);
            while (flag)
            {
                flag = RunSelected(1);
            }
            MessageBox.Show("检测完成");
        }
    }
 
    public class TestCase
    {
        public string Name { get; set; }
        public string FullName { get; set; }
        public int ModelMatchNum { get; set; } = 0;
    }
 
    #region Halcon Model
    public abstract class StrictedListConvert : StringConverter
    {
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }
 
        public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
        {
            return true;
        }
 
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            List<string> portNames = GetSupportedValueList();
            return new StandardValuesCollection(portNames);
        }
 
        protected abstract List<string> GetSupportedValueList();
    }
 
    public abstract class ModelConfig
    {
        public abstract HTuple GetHTuple();
 
        protected void IntCheck(ref ArrayList list, string desc)
        {
            if (int.TryParse(desc, out int convertValue))
            {
                list.Add(convertValue);
            }
            else
            {
                list.Add(desc);
            }
        }
 
        protected void DoubleCheck(ref ArrayList list, string desc)
        {
            if (double.TryParse(desc, out double convertValue))
            {
                list.Add(convertValue);
            }
            else
            {
                list.Add(desc);
            }
        }
 
    }
 
    #region Create Model
    public class NumLevelsConvert : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "auto", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
        }
    }
 
    public class AngleStartConvert : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "-3.14", "-1.57", "-0.79", "-0.39", "-0.20", "0.0" };
        }
    }
 
    public class AngleExtentConvert : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "6.29", "3.14", "1.57", "0.79", "0.39" };
        }
    }
 
    public class AngleStepConvert : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "auto", "0.0175", "0.0349", "0.0524", "0.0698", "0.0873" };
        }
    }
 
    public enum Optimization
    {
        auto,
        no_pregeneration,
        none,
        point_reduction_high,
        point_reduction_low,
        point_reduction_medium,
        pregeneration,
    }
 
    public enum Metric
    {
        use_polarity,
        ignore_color_polarity,
        ignore_global_polarity,
        ignore_local_polarity,
    }
 
    public class ContrastConvert : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "auto", "auto_contrast", "auto_contrast_hyst", "auto_min_size", "10", "20", "30", "40", "60", "80", "100", "120", "140", "160" };
        }
    }
 
    public class MinContrastConvert : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "auto", "1", "2", "3", "5", "7", "10", "20", "30", "40" };
        }
    }
 
    public class CreateShapeModelConfig : ModelConfig
    {
        [Category("建立模板配置")]
        [DisplayName("层次数量")]
        [TypeConverter(typeof(NumLevelsConvert))]
        public string NumLevles { get; set; } = "auto";
 
        [Category("建立模板配置")]
        [DisplayName("起始角度")]
        [TypeConverter(typeof(AngleStartConvert))]
        public string AngleStart { get; set; } = "-0.39";
 
        [Category("建立模板配置")]
        [DisplayName("角度范围")]
        [TypeConverter(typeof(AngleExtentConvert))]
        public string AngleExtent { get; set; } = "0.79";
 
        [Category("建立模板配置")]
        [DisplayName("角度步长")]
        [TypeConverter(typeof(AngleStepConvert))]
        public string AngleStep { get; set; } = "auto";
 
        [Category("建立模板配置")]
        [DisplayName("最优化选择")]
        public Optimization Optimization { get; set; } = Optimization.auto;
 
        [Category("建立模板配置")]
        [DisplayName("极性")]
        public Metric Metric { get; set; } = Metric.use_polarity;
 
        [Category("建立模板配置")]
        [DisplayName("对比度")]
        [TypeConverter(typeof(ContrastConvert))]
        public string Contrast { get; set; } = "auto";
 
        [Category("建立模板配置")]
        [DisplayName("最小对比度")]
        [TypeConverter(typeof(MinContrastConvert))]
        public string MinContrast { get; set; } = "auto";
 
        public override HTuple GetHTuple()
        {
            ArrayList list = new ArrayList();
            IntCheck(ref list, NumLevles);
            DoubleCheck(ref list, AngleStart);
            DoubleCheck(ref list, AngleExtent);
            DoubleCheck(ref list, AngleStep);
 
            list.Add(Optimization.ToString());
            list.Add(Metric.ToString());
 
            IntCheck(ref list, Contrast);
            IntCheck(ref list, MinContrast);
 
            HTuple hTuple = new HTuple(list.ToArray());
            return hTuple;
        }
 
    }
    #endregion
 
    #region Find Model
    public class AngleStartConvert_Find : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "-3.14", "-1.57", "-0.78", "-0.39", "-0.20", "0.0" };
        }
    }
 
    public class AngleExtentConvert_Find : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "6.29", "3.14", "1.57", "0.78", "0.39", "0.0" };
        }
    }
 
    public class MinScoreConvert : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1.0" };
        }
    }
 
    public class NumMatchesConvert : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "0", "1", "2", "3", "4", "5", "10", "20" };
        }
    }
 
    public class MaxOverlapConvert : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "0.0", "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1.0" };
        }
    }
 
    public enum SubPixel
    {
        interpolation,
        least_squares,
        least_squares_high,
        least_squares_very_high,
        [Description("max_deformation 1")]
        max_deformation_1,
        [Description("max_deformation 2")]
        max_deformation_2,
        [Description("max_deformation 3")]
        max_deformation_3,
        [Description("max_deformation 4")]
        max_deformation_4,
        [Description("max_deformation 5")]
        max_deformation_5,
        [Description("max_deformation 6")]
        max_deformation_6,
        none,
    }
 
    public class NumLevelsConvert_Find : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
        }
    }
 
    public class GreedinessConvert : StrictedListConvert
    {
        protected override List<string> GetSupportedValueList()
        {
            return new List<string>() { "0.0", "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1.0" };
        }
    }
 
    public class FindShapeModelConfig : ModelConfig
    {
        [Category("定位模板配置")]
        [DisplayName("起始角度")]
        [TypeConverter(typeof(AngleStartConvert_Find))]
        public string AngleStart { get; set; } = "-0.39";
 
        [Category("定位模板配置")]
        [DisplayName("角度范围")]
        [TypeConverter(typeof(AngleExtentConvert_Find))]
        public string AngleExtent { get; set; } = "0.78";
 
        [Category("定位模板配置")]
        [DisplayName("最小得分")]
        [TypeConverter(typeof(MinScoreConvert))]
        public string MinScore { get; set; } = "0.7";
 
        [Category("定位模板配置")]
        [DisplayName("匹配数量")]
        [TypeConverter(typeof(NumMatchesConvert))]
        public string NumMatches { get; set; } = "0";
 
        [Category("定位模板配置")]
        [DisplayName("最大重叠设置")]
        [TypeConverter(typeof(MaxOverlapConvert))]
        public string MaxOverlap { get; set; } = "0.5";
 
        [Category("定位模板配置")]
        [DisplayName("亚像素设置")]
        public SubPixel SubPixel { get; set; } = SubPixel.least_squares;
 
        [Category("定位模板配置")]
        [DisplayName("层次数量")]
        [TypeConverter(typeof(NumLevelsConvert_Find))]
        public string NumLevles { get; set; } = "0";
 
        [Category("定位模板配置")]
        [DisplayName("Greediness")]
        [TypeConverter(typeof(GreedinessConvert))]
        public string Greediness { get; set; } = "0.9";
 
        public override HTuple GetHTuple()
        {
            ArrayList list = new ArrayList();
            DoubleCheck(ref list, AngleStart);
            DoubleCheck(ref list, AngleExtent);
            DoubleCheck(ref list, MinScore);
            IntCheck(ref list, NumMatches);
            DoubleCheck(ref list, MaxOverlap);
            list.Add(SubPixel.GetEnumDescription());
            IntCheck(ref list, NumLevles);
            DoubleCheck(ref list, Greediness);
 
            HTuple hTuple = new HTuple(list.ToArray());
            return hTuple;
        }
    }
    #endregion
    #endregion
}