轮胎外观检测添加思谋语义分割模型检测工具
C3204
2026-03-30 06c627ec032b3f3876fd7db8a3ff0ff1a6614fa2
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
using HalconDotNet;
using LB_SmartVisionCommon;
using LB_VisionControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenCvSharp;
using SmartMore.ViMo;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Linq;
using System.Reflection;
using Point = OpenCvSharp.Point;
 
namespace LB_VisionProcesses.Alogrithms.BigModel.Segment
{
    public class SegmentTool : TAlgorithm
    {
        public Dictionary<string, SegmentParam> dicSegmentParam;
        /// <summary>
        /// 模型路径
        /// </summary>
        private string modelPath = string.Empty;
        /// <summary>
        /// 模型ID
        /// </summary>
        private string modelID = "0";
        /// <summary>
        /// 是否使用GPU
        /// </summary>
        private bool isUseGPU = false;
        /// <summary>
        /// GPUID
        /// </summary>
        private int deviceGPUID = 0;
        /// <summary>
        /// BatchSize
        /// </summary>
        private int batchSize = 1;
        /// <summary>
        /// DP解决方案
        /// </summary>
        private Solution solution;
        /// <summary>
        /// 分割模型
        /// </summary>
        private ISegmentationModule module;
        /// <summary>
        /// 分割参数
        /// </summary>
        private SegmentationParams segParams;
 
        public List<string> SegFeatures = new List<string>();
        public SegmentTool()
        {
            strProcessClass = "LB_VisionProcesses.Alogrithms.BigModel.Segment.SegmentTool";
            strProcessName = "语义分割工具";
 
            //模型输入
            Params.Inputs.Add("ModelPath", "");
            Params.Inputs.Add("ModuleId", "0");
            Params.Inputs.Add("UseGpu", false);
            Params.Inputs.Add("DeviceId", 0);
            Params.Inputs.Add("BatchSize", 1);
            Params.Inputs.Add("MaxTimeOut", 5000);
 
 
            //面积阈值
            Params.Inputs.Add("AreaThresholds", new Dictionary<string, double>());
 
            //长边过滤阈值
            Params.Inputs.Add("LongSideThresholds", new Dictionary<string, double>());
 
            //短边过滤阈值
            Params.Inputs.Add("ShortSideThresholds", new Dictionary<string, double>());
            //平均置信度阈值
            //Params.Inputs.Add("MeanScoreThresholds", 0.0f);
 
            //类别置信度阈值
            Params.Inputs.Add("ClassesScoreThresholds", new Dictionary<string, double>());
 
            //ROI
            //Params.Inputs.Add("ROIx1", 0);
            //Params.Inputs.Add("ROIy1", 0);
            //Params.Inputs.Add("ROIx2", 0);
            //Params.Inputs.Add("ROIy2", 0);
            Params.Inputs.Add("ROI", new List<double>());
 
            //筛选后输出输出
            Params.Outputs.Add("Count", 0);
            Params.Outputs.Add("ClassID", new List<int>());
            Params.Outputs.Add("Labels", new List<string>());
            Params.Outputs.Add("Area", new List<double>());
            Params.Outputs.Add("LongSide", new List<double>());
            Params.Outputs.Add("ShortSide", new List<double>());
 
            Params.Outputs.Add("MeanScore", new List<double>());
 
            //bbox
            Params.Outputs.Add("X", new List<double>());
            Params.Outputs.Add("Y", new List<double>());
            Params.Outputs.Add("Height", new List<double>());
            Params.Outputs.Add("Width", new List<double>());
            //轮廓线
            Params.Outputs.Add("OuterContours", new List<List<List<Point>>>());
        }
 
        private void VisualizeSegmentationResult(SegmentationResponse rsp, Mat image, Dictionary<string, double> AreaThresholds, Dictionary<string, double> LongSideThresholds, Dictionary<string, double> ShortSideThresholds, Dictionary<string, double> ClassesScoreThresholds)
        {
            // 预定义类别颜色映射表(支持最多20个类别)
            var classColors = new List<Scalar>
            {
                new Scalar(0, 0, 255),    // 0: 红色
                new Scalar(0, 255, 0),    // 1: 绿色
                new Scalar(255, 0, 0),    // 2: 蓝色
                new Scalar(255, 255, 0),  // 3: 青色
                new Scalar(255, 0, 255),  // 4: 品红
                new Scalar(0, 255, 255),  // 5: 黄色
                new Scalar(128, 0, 0),    // 6: 深红
                new Scalar(0, 128, 0),    // 7: 深绿
                new Scalar(0, 0, 128),    // 8: 深蓝
                new Scalar(128, 128, 0),  // 9: 橄榄色
                new Scalar(128, 0, 128),  // 10: 紫色
                new Scalar(0, 128, 128),  // 11: 靛蓝
                new Scalar(255, 165, 0),  // 12: 橙色
                new Scalar(255, 192, 203),// 13: 粉红色
                new Scalar(147, 112, 219),// 14: 紫罗兰
                new Scalar(255, 99, 71),  // 15: 番茄红
                new Scalar(255, 20, 147), // 16: 紫色
                new Scalar(30, 144, 255), // 17: 道奇蓝
                new Scalar(255, 69, 0),   // 18: 橙红色
                new Scalar(0, 206, 209)   // 19: 碧绿色
            };
            Record = new ObjectRecord();
            int Count = 0;
            var ClassIDList = new List<int>();
            var LabelsList = new List<string>();
            var AreaList = new List<double>();
            var LongSideList = new List<double>();
            var ShortSideList = new List<double>();
            var MeanScoreList = new List<double>();
            var XList = new List<double>();
            var YList = new List<double>();
            var HeightList = new List<double>();
            var WidthList = new List<double>();
 
            var OuterContourList = new List<List<Point>>();
            rsp.LabelMap = null;
            // 使用 RegionInfo 信息可视化
            foreach (var info in rsp.RegionInfos)
            {
                var r_area = info.Area;
                var r_label = info.Label;
                var r_shortSide = info.ShortSide;
                var r_longSide = info.LongSide;
                var r_Id = info.Id;
                var r_MeanScore = info.MeanScore;
 
                var bbox = info.BoundingRect;
                // 提取轮廓
                var contours = new List<List<Point>> { info.OuterContour.Select(x => new Point(x.X, x.Y)).ToList() };
 
                List<Point> contour = info.OuterContour.Select(x => new Point((int)x.X, (int)x.Y)).ToList();  // 浮点→整数
 
                if (r_area >= AreaThresholds[r_label] && r_longSide >= LongSideThresholds[r_label] && r_shortSide >= ShortSideThresholds[r_label] /*&& r_MeanScore >= ClassesScoreThresholds[r_label]*/)
                {
                    AreaList.Add(r_area);
                    ClassIDList.Add(r_Id);
                    LongSideList.Add(r_longSide);
                    ShortSideList.Add(r_shortSide);
                    MeanScoreList.Add(r_MeanScore);
                    LabelsList.Add(r_label);
 
                    XList.Add(bbox.X);
                    YList.Add(bbox.Y);
                    HeightList.Add(bbox.Height);
                    WidthList.Add(bbox.Width);
 
                    OuterContourList.Add(contour);
 
                    // 获取类别颜色(自动循环使用预定义颜色)
                    int colorIndex = info.Id % classColors.Count;
                    var color = classColors[colorIndex];
                    //Cv2.DrawContours(image, contours, -1, color, 2);
 
                    //Cv2.PutText(image, $"{info.Label}, area = {info.Area}", new Point(bbox.X, bbox.Y), HersheyFonts.HersheySimplex, 1, color, 2);
 
                    if (contour == null || contour.Count == 0)
                    {
                        throw new ArgumentException("轮廓点集合不能为空或无数据");
                    }
 
                    HTuple rowTuple = new HTuple();  // Halcon中row对应Y坐标
                    HTuple colTuple = new HTuple();  // Halcon中column对应X坐标
                    foreach (Point p in contour)
                    {
                        rowTuple.Append(p.Y);
                        colTuple.Append(p.X);
                    }
 
                    HOperatorSet.GenContourPolygonXld(out HObject contour1, rowTuple, colTuple);
 
                    ((ObjectRecord)Record).AddXld(contour1);
                }
            }
 
            Count = AreaList.Count();
            if (Count > 0)
            {
                Msg = "检测到缺陷,NG:" + Count;
                Result = false;
            }
            else
            {
                Msg = "运行成功";
                Result = true;
            }
            Params.Outputs["Count"] = Count;
            Params.Outputs["ClassID"] = ClassIDList;
            Params.Outputs["Area"] = AreaList;
            Params.Outputs["LongSideList"] = LongSideList;
            Params.Outputs["ShortSideList"] = ShortSideList;
            Params.Outputs["MeanScore"] = MeanScoreList;
            Params.Outputs["X"] = XList;
            Params.Outputs["Y"] = YList;
            Params.Outputs["Height"] = HeightList;
            Params.Outputs["Width"] = WidthList;
            Params.Outputs["OuterContours"] = OuterContourList;
 
        }
 
 
        private void VisualizeSegmentationResult(SegmentationResponse rsp, Dictionary<string, double> AreaThresholds, Dictionary<string, double> LongSideThresholds, Dictionary<string, double> ShortSideThresholds, Dictionary<string, double> ClassesScoreThresholds)
        {
            // 预定义类别颜色映射表(支持最多20个类别)
            var classColors = new List<Scalar>
            {
                new Scalar(0, 0, 255),    // 0: 红色
                new Scalar(0, 255, 0),    // 1: 绿色
                new Scalar(255, 0, 0),    // 2: 蓝色
                new Scalar(255, 255, 0),  // 3: 青色
                new Scalar(255, 0, 255),  // 4: 品红
                new Scalar(0, 255, 255),  // 5: 黄色
                new Scalar(128, 0, 0),    // 6: 深红
                new Scalar(0, 128, 0),    // 7: 深绿
                new Scalar(0, 0, 128),    // 8: 深蓝
                new Scalar(128, 128, 0),  // 9: 橄榄色
                new Scalar(128, 0, 128),  // 10: 紫色
                new Scalar(0, 128, 128),  // 11: 靛蓝
                new Scalar(255, 165, 0),  // 12: 橙色
                new Scalar(255, 192, 203),// 13: 粉红色
                new Scalar(147, 112, 219),// 14: 紫罗兰
                new Scalar(255, 99, 71),  // 15: 番茄红
                new Scalar(255, 20, 147), // 16: 紫色
                new Scalar(30, 144, 255), // 17: 道奇蓝
                new Scalar(255, 69, 0),   // 18: 橙红色
                new Scalar(0, 206, 209)   // 19: 碧绿色
            };
            Record = new ObjectRecord();
            int Count = 0;
            var ClassIDList = new List<int>();
            var LabelsList = new List<string>();
            var AreaList = new List<double>();
            var LongSideList = new List<double>();
            var ShortSideList = new List<double>();
            var MeanScoreList = new List<double>();
            var XList = new List<double>();
            var YList = new List<double>();
            var HeightList = new List<double>();
            var WidthList = new List<double>();
 
            var OuterContourList = new List<List<Point>>();
            rsp.LabelMap = null;
            // 使用 RegionInfo 信息可视化
            foreach (var info in rsp.RegionInfos)
            {
                var r_area = info.Area;
                var r_label = info.Label;
                var r_shortSide = info.ShortSide;
                var r_longSide = info.LongSide;
                var r_Id = info.Id;
                var r_MeanScore = info.MeanScore;
 
                var bbox = info.BoundingRect;
                // 提取轮廓
                var contours = new List<List<Point>> { info.OuterContour.Select(x => new Point(x.X, x.Y)).ToList() };
 
                List<Point> contour = info.OuterContour.Select(x => new Point((int)x.X, (int)x.Y)).ToList();  // 浮点→整数
 
                if (r_area >= AreaThresholds[r_label] && r_longSide >= LongSideThresholds[r_label] && r_shortSide >= ShortSideThresholds[r_label] /*&& r_MeanScore >= ClassesScoreThresholds[r_label]*/)
                {
                    AreaList.Add(r_area);
                    ClassIDList.Add(r_Id);
                    LongSideList.Add(r_longSide);
                    ShortSideList.Add(r_shortSide);
                    MeanScoreList.Add(r_MeanScore);
                    LabelsList.Add(r_label);
 
                    XList.Add(bbox.X);
                    YList.Add(bbox.Y);
                    HeightList.Add(bbox.Height);
                    WidthList.Add(bbox.Width);
 
                    OuterContourList.Add(contour);
 
                    // 获取类别颜色(自动循环使用预定义颜色)
                    int colorIndex = info.Id % classColors.Count;
                    var color = classColors[colorIndex];
                    //Cv2.DrawContours(image, contours, -1, color, 2);
 
                    //Cv2.PutText(image, $"{info.Label}, area = {info.Area}", new Point(bbox.X, bbox.Y), HersheyFonts.HersheySimplex, 1, color, 2);
 
                    if (contour == null || contour.Count == 0)
                    {
                        throw new ArgumentException("轮廓点集合不能为空或无数据");
                    }
 
                    HTuple rowTuple = new HTuple();  // Halcon中row对应Y坐标
                    HTuple colTuple = new HTuple();  // Halcon中column对应X坐标
                    foreach (Point p in contour)
                    {
                        rowTuple.Append(p.Y);
                        colTuple.Append(p.X);
                    }
 
                    HOperatorSet.GenContourPolygonXld(out HObject contour1, rowTuple, colTuple);
 
                    ((ObjectRecord)Record).AddXld(contour1);
                }
            }
 
            Count = AreaList.Count();
            if (Count > 0)
            {
                Msg = "检测到缺陷,NG:" + Count;
                Result = false;
            }
            else
            {
                Msg = "运行成功";
                Result = true;
            }
            Params.Outputs["Count"] = Count;
            Params.Outputs["ClassID"] = ClassIDList;
            Params.Outputs["Area"] = AreaList;
            Params.Outputs["LongSideList"] = LongSideList;
            Params.Outputs["ShortSideList"] = ShortSideList;
            Params.Outputs["MeanScore"] = MeanScoreList;
            Params.Outputs["X"] = XList;
            Params.Outputs["Y"] = YList;
            Params.Outputs["Height"] = HeightList;
            Params.Outputs["Width"] = WidthList;
            Params.Outputs["OuterContours"] = OuterContourList;
 
        }
        public override bool Run()
        {
            DateTime StartTime = DateTime.Now;
 
            InitRunParams();
            HOperatorSet.GenEmptyObj(out HObject EmptyObj);
            OutputImage = EmptyObj;
 
            // 创建并启动任务
            TAlgorithmMain();
            RunTime = (DateTime.Now - StartTime).TotalMilliseconds;
            return Result;
        }
 
        /// <summary>
        /// 算子逻辑
        /// </summary>
        public override void TAlgorithmMain()
        {
            //InitRunParams();
            #region 初始化变量
            HObject ho_Regions, ho_ConnectedRegions;
            HOperatorSet.GenEmptyObj(out ho_Regions);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            #endregion
 
            try
            {
                if (InputImage == null)
                {
                    Msg = "输入图片为空";
                    Result = false;
                    return;
                }
                if (!(InputImage is Mat))
                {
                    Msg = "输入图片格式不为Mat";
                    Result = false;
                    return;
                }
 
                #region 裁剪区域
                object DomainImage = null;
                if (!ReduceDomainImage(InputImage, ref DomainImage))
                {
                    Msg = "裁剪区域失败";
                    Result = false;
                    return;
                }
                Mat hoDomainImage = DomainImage as Mat;
                #endregion
 
                if (module == null)
                {
                    LoadModel();
                    Debug.WriteLine("运行逻辑加载模型");
                }
 
                #region 算子逻辑
                //var ModelPath = ProcessParams.ConvertToString(Params.Inputs["ModelPath"]);
                //var ModuleId = ProcessParams.ConvertToString(Params.Inputs["ModuleId"]);
                //var UseGpu = Convert.ToBoolean(Params.Inputs["UseGpu"]);
                //var DeviceId = Convert.ToInt32(Params.Inputs["DeviceId"]);
                //var BatchSize = Convert.ToInt32(Params.Inputs["BatchSize"]);
 
                //Dictionary<string, double> AreaThresholds = Params.Inputs["AreaThresholds"] as Dictionary<string, double> ?? new Dictionary<string, double>();
                //Dictionary<string, double> LongSideThresholds = Params.Inputs["LongSideThresholds"] as Dictionary<string, double> ?? new Dictionary<string, double>();
                //Dictionary<string, double> ShortSideThresholds = Params.Inputs["ShortSideThresholds"] as Dictionary<string, double> ?? new Dictionary<string, double>();
                //Dictionary<string, double> ClassesScoreThresholds = Params.Inputs["ClassesScoreThresholds"] as Dictionary<string, double> ?? new Dictionary<string, double>();
 
                Dictionary<string, double> AreaThresholds = null;
                Dictionary<string, double> LongSideThresholds = null;
                Dictionary<string, double> ShortSideThresholds = null;
                Dictionary<string, double> ClassesScoreThresholds = null;
 
                // 获取SegmentTool中的阈值字典
                var areaThresholdsObj = Params.Inputs["AreaThresholds"];
 
                if (areaThresholdsObj is JObject jObject)
                {
                    // 最终转换为目标字典类型
                    AreaThresholds = jObject.ToObject<Dictionary<string, double>>();
 
                }
                else if (areaThresholdsObj is Object)
                {
                    AreaThresholds = areaThresholdsObj as Dictionary<string, double>;
                    if (AreaThresholds == null)
                    {
                        AreaThresholds = new Dictionary<string, double>();
                        foreach (var kvp in areaThresholdsObj as Dictionary<string, object>)
                        {
                            try
                            {
                                // 尝试将object转为double
                                double value = Convert.ToDouble(kvp.Value);
                                AreaThresholds.Add(kvp.Key, value);
                            }
                            catch (Exception ex)
                            {
                                // 处理转换失败的情况(可选,比如打印日志、抛自定义异常)
                                Debug.WriteLine($"转换键 {kvp.Key} 失败:{ex.Message}");
                            }
                        }
                    }
                }
                else
                {
                    //// 处理类型不符的异常情况(可选,增强健壮性)
                    //throw new System.Exception("AreaThresholds的实际类型不是JObject,转换失败");
                    AreaThresholds = new Dictionary<string, double>();
                }
 
                var longSideThresholdsObj = Params.Inputs["LongSideThresholds"];
 
                if (longSideThresholdsObj is JObject jObjectL)
                {
                    // 最终转换为目标字典类型
                    LongSideThresholds = jObjectL.ToObject<Dictionary<string, double>>();
 
                }
                else if (longSideThresholdsObj is Object)
                {
                    LongSideThresholds = longSideThresholdsObj as Dictionary<string, double>;
                    if (LongSideThresholds == null)
                    {
                        LongSideThresholds = new Dictionary<string, double>();
                        foreach (var kvp in longSideThresholdsObj as Dictionary<string, object>)
                        {
                            try
                            {
                                // 尝试将object转为double
                                double value = Convert.ToDouble(kvp.Value);
                                LongSideThresholds.Add(kvp.Key, value);
                            }
                            catch (Exception ex)
                            {
                                // 处理转换失败的情况(可选,比如打印日志、抛自定义异常)
                                Debug.WriteLine($"转换键 {kvp.Key} 失败:{ex.Message}");
                            }
                        }
                    }
                }
                else
                {
                    //// 处理类型不符的异常情况(可选,增强健壮性)
                    //throw new System.Exception("LongSideThresholds的实际类型不是JObject,转换失败");
                    LongSideThresholds = new Dictionary<string, double>();
                }
 
 
                var shortSideThresholdsObj = Params.Inputs["ShortSideThresholds"];
 
                if (shortSideThresholdsObj is JObject jObjectS)
                {
                    // 最终转换为目标字典类型
                    ShortSideThresholds = jObjectS.ToObject<Dictionary<string, double>>();
 
                }
                else if (shortSideThresholdsObj is Object)
                {
                    ShortSideThresholds = shortSideThresholdsObj as Dictionary<string, double>;
                    if (ShortSideThresholds == null)
                    {
                        ShortSideThresholds = new Dictionary<string, double>();
                        foreach (var kvp in shortSideThresholdsObj as Dictionary<string, object>)
                        {
                            try
                            {
                                // 尝试将object转为double
                                double value = Convert.ToDouble(kvp.Value);
                                ShortSideThresholds.Add(kvp.Key, value);
                            }
                            catch (Exception ex)
                            {
                                // 处理转换失败的情况(可选,比如打印日志、抛自定义异常)
                                Debug.WriteLine($"转换键 {kvp.Key} 失败:{ex.Message}");
                            }
                        }
                    }
                }
                else
                {
                    //// 处理类型不符的异常情况(可选,增强健壮性)
                    //throw new System.Exception("shortSideThresholds的实际类型不是JObject,转换失败");
                    ShortSideThresholds = new Dictionary<string, double>();
                }
 
                var classesScoreThresholdsObj = Params.Inputs["ClassesScoreThresholds"];
 
                if (classesScoreThresholdsObj is JObject jObjectC)
                {
                    // 最终转换为目标字典类型
                    ClassesScoreThresholds = jObjectC.ToObject<Dictionary<string, double>>();
 
                }
                else if (classesScoreThresholdsObj is Object)
                {
                    ClassesScoreThresholds = classesScoreThresholdsObj as Dictionary<string, double>;
                    if (ClassesScoreThresholds == null)
                    {
                        ClassesScoreThresholds = new Dictionary<string, double>();
                        foreach (var kvp in classesScoreThresholdsObj as Dictionary<string, object>)
                        {
                            try
                            {
                                // 尝试将object转为double
                                double value = Convert.ToDouble(kvp.Value);
                                ClassesScoreThresholds.Add(kvp.Key, value);
                            }
                            catch (Exception ex)
                            {
                                // 处理转换失败的情况(可选,比如打印日志、抛自定义异常)
                                Debug.WriteLine($"转换键 {kvp.Key} 失败:{ex.Message}");
                            }
                        }
                    }
                }
                else
                {
                    //// 处理类型不符的异常情况(可选,增强健壮性)
                    //throw new System.Exception("classesScoreThresholds的实际类型不是JObject,转换失败");
                    ClassesScoreThresholds = new Dictionary<string, double>();
                }
 
                //判断和加载模型
                try
                {
                    //// create an empty solution
                    //{
                    //    AsyncLogHelper.Info($"load solution from: {Params.Inputs["MinThreshold"]}");
                    //    solution.LoadFromFile(modelPath);  // load solution from model.vimosln
 
                    //    AsyncLogHelper.Info($"create Module: {modelID}, use gpu: {isUseGPU}, device id: {deviceGPUID}");
                    //    module = solution.CreateModule<ISegmentationModule>(modelID, isUseGPU, deviceGPUID, batchSize); // create module
                    //    {
 
                    //        var segParams = module.Params;   // 读取模型参数
                    //        segParams.WithMask = false;      // 可选,关闭 mask 输出
                    //        segParams.WithRegionInfo = true; // 开启 RegionInfo 输出,以便可视化
                    //        segParams.RegionInfoFlag = SegRegionInfoFlag.Area
                    //            | SegRegionInfoFlag.InnerContours
                    //            | SegRegionInfoFlag.OuterContour
                    //            | SegRegionInfoFlag.LongSide
                    //            | SegRegionInfoFlag.ShortSide;
 
                    //        module.Params = segParams; // 设置模型参数
 
 
                    //        AsyncLogHelper.Info($"create request from image:  " + "imagePath");
 
                    //        using (Mat visImage = hoDomainImage.Clone())   // clone request image for visualize
                    //        {
                    //            var req = new Request(hoDomainImage);   // create request from image
 
                    //            AsyncLogHelper.Info("run pipelines");
                    //            module.Run(req, out SegmentationResponse rsp);
                    //            AsyncLogHelper.Info("inference done");
 
                    //            AsyncLogHelper.Info("do visualize");
 
                    //            VisualizeSegmentationResult(rsp, visImage, AreaThresholds, LongSideThresholds, ShortSideThresholds, ClassesScoreThresholds); // visualize
                    //            OutputImage = visImage;
                    //            //Console.WriteLine("save vis image to: vis_image.png");
                    //            //Cv2.ImWrite("vis_image.png", visImage); // save visualize image
                    //            //Console.WriteLine("save vis image done");
                    //        }
                    //    }
                    //}
 
                    //using (Mat visImage = hoDomainImage.Clone())   // clone request image for visualize
                    //{
                    //    Request req = new Request(hoDomainImage);   // create request from image
 
                    //    AsyncLogHelper.Info("run pipelines");
                    //    module.Run(req, out SegmentationResponse rsp);
                    //    AsyncLogHelper.Info("inference done");
 
                    //    AsyncLogHelper.Info("do visualize");
 
                    //    //VisualizeSegmentationResult(rsp, visImage, AreaThresholds, LongSideThresholds, ShortSideThresholds, ClassesScoreThresholds); // visualize
                    //    VisualizeSegmentationResult(rsp, AreaThresholds, LongSideThresholds, ShortSideThresholds, ClassesScoreThresholds); // visualize
                    //    OutputImage = DomainImage;
                    //    //Console.WriteLine("save vis image to: vis_image.png");
                    //    //Cv2.ImWrite("vis_image.png", visImage); // save visualize image
                    //    //Console.WriteLine("save vis image done");
                    //}
 
                    Request req = new Request(hoDomainImage);   // create request from image
 
                    AsyncLogHelper.Info("run pipelines");
                    module.Run(req, out SegmentationResponse rsp);
                    AsyncLogHelper.Info("inference done");
 
                    AsyncLogHelper.Info("do visualize");
 
                    //VisualizeSegmentationResult(rsp, visImage, AreaThresholds, LongSideThresholds, ShortSideThresholds, ClassesScoreThresholds); // visualize
                    VisualizeSegmentationResult(rsp, AreaThresholds, LongSideThresholds, ShortSideThresholds, ClassesScoreThresholds); // visualize
                    OutputImage = DomainImage;
                    //hoDomainImage.Dispose();
                }
                catch (Exception ex)
                {
                    Msg = "生成OutputImage失败,原因是:" + ex.ToString();
                    Result = false;
                    return;
                }
 
                #endregion
 
                //Msg = "运行成功";
                //Result = true;
                return;
            }
            catch (Exception ex)
            {
                Msg = "运行失败,原因是:" + ex.ToString().TrimEnd();
                OutputImage = null;
                Result = false;
                return;
            }
            finally
            {
                bCompleted = true;
                #region 内存释放
                ho_Regions.Dispose();
                ho_ConnectedRegions.Dispose();
                #endregion
            }
        }
 
        public override bool Save(string filePath = "")
        {
            return base.Save(filePath);
        }
 
        public override bool Load(string fullPath = "")
        {
            if (base.Load(fullPath))
            {
                return LoadModel();
            }
            else
            {
                return false;
            }
        }
 
        public bool LoadModel(string fullPath = "")
        {
            if (!string.IsNullOrEmpty(fullPath) && fullPath.Trim() != "")
            {
                this.modelPath = fullPath;
                Params.Inputs.Add("ModelPath", fullPath);
            }
            SegFeatures.Clear();
            this.modelID = Params.Inputs["ModuleId"]?.ToString();//(JArray.FromObject(Params.Inputs["标签"]))?.ToObject<List<string>>();
            this.isUseGPU = Convert.ToBoolean(Params.Inputs["UseGpu"]?.ToString());
            this.deviceGPUID = Convert.ToInt32(Params.Inputs["DeviceId"]?.ToString());
            this.batchSize = Convert.ToInt32(Params.Inputs["BatchSize"]?.ToString());
            this.modelPath = Params.Inputs["ModelPath"]?.ToString();
            if (System.IO.File.Exists(modelPath))
            {
                try
                {
                    if (module != null)
                    {
                        module.Dispose();
                        module = null;
                    }
                    if (solution != null)
                    {
                        solution.Dispose();
                        solution = null;
                    }
 
                    if (solution == null)
                    {
                        solution = new Solution();
                        AsyncLogHelper.Info($"load solution from: {Params.Inputs["ModelPath"]}");
                        solution.LoadFromFile(modelPath);  // load solution from model.vimosln
                    }
                    else
                    {
                        solution.Dispose();
                        AsyncLogHelper.Info($"load solution from: {Params.Inputs["ModelPath"]}");
                        solution.LoadFromFile(modelPath);  // load solution from model.vimosln
                    }
                    if (module == null)
                    {
                        AsyncLogHelper.Info($"create Module: {modelID}, use gpu: {isUseGPU}, device id: {deviceGPUID}");
                        module = solution.CreateModule<ISegmentationModule>(modelID, isUseGPU, deviceGPUID, batchSize); // create module
                    }
                    else
                    {
                        module.Dispose();
                        AsyncLogHelper.Info($"create Module: {modelID}, use gpu: {isUseGPU}, device id: {deviceGPUID}");
                        module = solution.CreateModule<ISegmentationModule>(modelID, isUseGPU, deviceGPUID, batchSize); // create module
                    }
                    segParams = module.Params;   // 读取模型参数
                    segParams.WithMask = false;      // 可选,关闭 mask 输出
                    segParams.WithRegionInfo = true; // 开启 RegionInfo 输出,以便可视化
                    segParams.RegionInfoFlag = SegRegionInfoFlag.Area
                        | SegRegionInfoFlag.InnerContours
                        | SegRegionInfoFlag.OuterContour
                        | SegRegionInfoFlag.LongSide
                        | SegRegionInfoFlag.ShortSide;
 
                    module.Params = segParams; // 设置模型参数
                    foreach (var item in solution.ModuleInfoList)
                    {
                        foreach (var item1 in item.Features.ToList())
                        {
                            SegFeatures.Add(item1);
                        }
                    }
                    // 加载模型后先运行下空图片进行缓存 下次运行时提速[无效]
                    //image_predict(new Mat(1920, 1080, MatType.CV_16UC3));
                }
                catch (Exception ex)
                {
                    Msg = $"创建分割模型接口失败,请检查参数,{ex.Message}";
                    return false;
                }
            }
            else
            {
                Msg = "模型路径不存在";
                return false;
            }
            return true;
        }
 
    }
 
}