轮胎外观检测添加思谋语义分割模型检测工具
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
using HalconDotNet;
using LB_VisionControls;
using LB_VisionProcesses.Alogrithms;
using LB_VisionProcesses.Alogrithms.Halcon;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using SharpCompress.Common;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
 
namespace LB_VisionProcesses.Processes
{
    public class RecordTool : BaseProcess
    {
        public RecordTool()
        {
            strProcessClass = "LB_VisionProcesses.Processes.RecordTool";
            strProcessName = "创建绘制工具";
        }
 
        ConcurrentBag<UserRecord> dicRecords = new ConcurrentBag<UserRecord>();
        public override bool Run()
        {
            #region 初始化变量
            DateTime StartTime = DateTime.Now;
 
            InitRunParams();
            HOperatorSet.GenEmptyObj(out HObject EmptyObj);
            OutputImage = EmptyObj;
            #endregion
 
            try
            {
                //if (InputImage == null)
                //{
                //    Msg = "输入图片为空";
                //    Result = false;
                //    return Result;
                //}
 
                //if (!(InputImage is HObject))
                //{
                //    Msg = "输入图片格式不为HObject";
                //    Result = false;
                //    return Result;
                //}
 
                #region 裁剪区域
                //object DomainImage = null;
                //if (!ReduceDomainImage(InputImage, ref DomainImage))
                //{
                //    Msg = "裁剪区域失败";
                //    Result = false;
                //    return Result;
                //}
                #endregion
 
                #region 算子逻辑
                Record = new MsgRecord();
 
                foreach (var recordObj in dicRecords)
                {
                    if (recordObj is UserRecord record)
                    {
                        string Msg = "";
                        if (!record.MsgMap.Contains('{') || !record.MsgMap.Contains('}'))
                            Msg = record.MsgMap;
                        else
                        {
                            Msg = record.MsgMap;
 
                            // 使用正则表达式匹配所有 {key} 格式的内容
                            Msg = Regex.Replace(Msg, @"\{([^}]+)\}", match =>
                            {
                                string key = match.Groups[1].Value; // 获取花括号内的内容
                                if (Params.Inputs.ContainsKey(key))
                                {
                                    object value = Params.Inputs[key];
                                    if (value == null) return "";
 
                                    // 尝试解析为数值类型
                                    if (double.TryParse(value.ToString(), out double num))
                                        return num.ToString("F4");
 
                                    return value?.ToString();
                                }
                                return match.Value; // 如果找不到键,保留原文本
                            });
                        }
 
                        bool Result = false;
                        if (!record.ResultMap.StartsWith("{") || !record.ResultMap.EndsWith("}"))
                            Result = Convert.ToBoolean(record.ResultMap);
                        else
                        {
                            string Map = record.ResultMap;
                            Map = Map.Replace("{", "");
                            Map = Map.Replace("}", "");
                            if (Params.Inputs.ContainsKey(Map) && Params.Inputs[Map] is bool res)
                                Result = res;
                        }
 
                        ROI Obj = new ROI();
                        if (record.ShapeMap.StartsWith("{") && record.ShapeMap.EndsWith("}"))
                        {
                            string Map = record.ShapeMap;
                            Map = Map.Replace("{", "");
                            Map = Map.Replace("}", "");
                            if (Params.Inputs.ContainsKey(Map) && Params.Inputs[Map] is ROI roi)
                                Obj = roi;
                        }
 
                        double X = 0;
                        if (!record.XMap.StartsWith("{") || !record.XMap.EndsWith("}"))
                            X = Convert.ToDouble(record.XMap);
                        else
                        {
                            string Map = record.ResultMap;
                            Map = Map.Replace("{", "");
                            Map = Map.Replace("}", "");
                            if (Params.Inputs.ContainsKey(Map) && Params.Inputs[Map] is double val)
                                X = val;
                        }
 
                        double Y = 0;
                        if (!record.YMap.StartsWith("{") || !record.YMap.EndsWith("}"))
                            Y = Convert.ToDouble(record.YMap);
                        else
                        {
                            string Map = record.ResultMap;
                            Map = Map.Replace("{", "");
                            Map = Map.Replace("}", "");
                            if (Params.Inputs.ContainsKey(Map) && Params.Inputs[Map] is double val)
                                Y = val;
                        }
                        HPoint Pose = new HPoint(X, Y);
 
                        ((MsgRecord)Record).AddXld(Msg, Pose.Row, Pose.Column, Obj.GetXld(), Result);
                    }
                }
 
                #endregion
 
                #region 生成OutputImage给后续处理
                try
                {
                    //OutputImage = hoDomainImage;
                }
                catch (Exception ex)
                {
                    Msg = "生成OutputImage失败,原因是:" + ex.ToString();
                    Result = false;
                    return Result;
                }
                #endregion
 
                Msg = "运行成功";
                Result = true;
                return Result;
            }
            catch (Exception ex)
            {
                Msg = "运行失败,原因是:" + ex.ToString().TrimEnd();
                OutputImage = null;
                Result = false;
                return Result;
            }
            finally
            {
                RunTime = (DateTime.Now - StartTime).TotalMilliseconds;
            }
        }
 
        public ConcurrentDictionary<int, UserRecord> GetRecords()
        {
            ConcurrentDictionary<int, UserRecord> dicRecords = new ConcurrentDictionary<int, UserRecord>();
 
            int index = 1;
            foreach (var userRecord in this.dicRecords)
            {
                dicRecords.TryAdd(index, userRecord);
                index++;
            }
            return dicRecords;
        }
 
        public override bool Load(string fullPath)
        {
            try
            {
                // 获取不带文件名的目录路径
                string directoryPath = Path.GetDirectoryName(fullPath);
                strProcessName = Path.GetFileNameWithoutExtension(fullPath);
                // 修正真实路径,工具其路径为一个文件夹,而不是一个文件
                string FilePath = directoryPath + "\\" + strProcessName;
                fullPath = FilePath + "\\" + strProcessName + ".json";
 
                if (!File.Exists(fullPath))
                {
                    Debug.WriteLine("文件不存在创建空文件");
                    Save(directoryPath);
                    return true;
                }
 
                string strJson = string.Empty;
                using (StreamReader streamReader = new StreamReader(fullPath, Encoding.UTF8))
                {
                    strJson = streamReader.ReadToEnd();
                    streamReader.Close();
                }
                Params = JsonConvert.DeserializeObject<ProcessParams>(strJson);
                if (Params == null)
                    return false;
 
                Params.FixDeserializedData();
 
                return LoadRecords(directoryPath + $"\\{strProcessName}\\{strProcessName}.rds");
            }
            catch { return false; }
        }
 
        /// <summary>
        /// 加载绘制流(带.json,实际路径)
        /// </summary>
        /// <param name="fullPath">完整路径带.json</param>
        /// <returns></returns>
        public bool LoadRecords(string fullPath)
        {
            try
            {
                // 获取不带文件名的目录路径
                string directoryPath = Path.GetDirectoryName(fullPath);
                if (!File.Exists(fullPath))
                {
                    Debug.WriteLine("文件不存在创建空文件");
                    SaveRecords(directoryPath);
                    return true;
                }
 
                string strJson = string.Empty;
                using (StreamReader streamReader = new StreamReader(fullPath, Encoding.UTF8))
                {
                    strJson = streamReader.ReadToEnd();
                    streamReader.Close();
                }
                ConcurrentDictionary<int, UserRecord> dicRecords = JsonConvert.DeserializeObject<ConcurrentDictionary<int, UserRecord>>(strJson);
                if (dicRecords == null)
                    return false;
 
                this.dicRecords.Clear();
                for (int i = 1; i <= dicRecords.Count; i++)
                {
                    if (dicRecords.ContainsKey(i))
                        this.dicRecords.Add(dicRecords[i]);
                }
 
                return true;
            }
            catch { return false; }
        }
 
        public override bool Save(string filePath)
        {
            try
            {
                if (string.IsNullOrEmpty(filePath) || filePath.Trim() == "")
                {
                    Debug.WriteLine("文件路径不完整");
                    return false;
                }
 
                // 修正真实路径,工具其路径为一个文件夹,而不是一个文件
                filePath += ("\\" + strProcessName);
 
                string strJson = string.Empty;
                var settings = new JsonSerializerSettings
                {
                    Formatting = Newtonsoft.Json.Formatting.Indented,
                    // 自定义缩进(4空格)
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }
                };
                strJson = JsonConvert.SerializeObject(Params, settings);
 
                //判断文件夹是否存在,防呆输入为文件名称
                if (!Directory.Exists(filePath))
                {
                    try
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    catch (Exception)
                    { }
                }
                // filePath 已经含了Name
                File.WriteAllText(filePath + $"\\{strProcessName}.json", strJson, Encoding.UTF8);
 
                return SaveRecords(filePath);
            }
            catch { return false; }
        }
 
        /// <summary>
        /// 保存绘制流(不带.json,实际路径)
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public bool SaveRecords(string filePath)
        {
            try
            {
                if (string.IsNullOrEmpty(filePath) || filePath.Trim() == "")
                {
                    Debug.WriteLine("文件路径不完整");
                    return false;
                }
 
                var dicRecords = GetRecords();
 
                string strJson = string.Empty;
                var settings = new JsonSerializerSettings
                {
                    Formatting = Newtonsoft.Json.Formatting.Indented,
                    // 自定义缩进(4空格)
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }
                };
                strJson = JsonConvert.SerializeObject(dicRecords, settings);
 
                //判断文件夹是否存在,防呆输入为文件名称
                if (!Directory.Exists(filePath))
                {
                    try
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    catch (Exception)
                    { }
                }
                // filePath 已经含了Name
                File.WriteAllText(filePath + $"\\{strProcessName}.rds", strJson, Encoding.UTF8);
 
                return true;
            }
            catch { return false; }
        }
 
        public bool ClearRecord()
        {
            try
            {
                dicRecords.Clear();
                return true;
            }
            catch { return false; }
        }
 
        public bool AddRecord(UserRecord record)
        {
            try
            {
                dicRecords.Add(record);
                return true;
            }
            catch { return false; }
        }
 
        public bool RemoveLastRecord()
        {
            try
            {
                return dicRecords.TryTake(out _);
            }
            catch { return false; }
        }
 
        /// <summary>
        /// 获取脚本输入
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, object> GetInputs()
        {
            try
            {
                Dictionary<string, object> dicInputs = new Dictionary<string, object>();
 
                for (int i = 0; i <= Params.Inputs.Count - 1; i++)
                {
                    bool isFindKey = Params.Inputs.GetKey(i, out string key);
                    //忽略不需要的参数
                    if (!isFindKey || key == "Scrip" || key == "OtherDllPaths")
                        continue;
 
                    dicInputs.TryAdd(key, Params.Inputs[i]);
                }
 
                return dicInputs;
            }
            catch { return new Dictionary<string, object>(); }
        }
 
        /// <summary>
        /// 设置脚本输入
        /// </summary>
        /// <param name="dicInputs"></param>
        /// <returns></returns>
        public bool SetInputs(Dictionary<string, object> dicInputs)
        {
            try
            {
                //设置输入前将原先其他输入清除
                if (!ClearInputs())
                    return false;
 
                foreach (var kvp in dicInputs)
                {
                    string key = kvp.Key;
                    //忽略不需要的参数
                    if (key == "Scrip" || key == "OtherDllPaths")
                        continue;
 
                    Params.Inputs.Add(key, kvp.Value);
                }
                return true;
            }
            catch { return false; }
        }
 
        public bool ClearInputs()
        {
            try
            {
                //设置输入前将原先其他输入清除
                for (int i = 0; i <= Params.Inputs.Count - 1; i++)
                {
                    bool isFindKey = Params.Inputs.GetKey(i, out string key);
                    //忽略不需要的参数
                    if (!isFindKey || key == "Scrip" || key == "OtherDllPaths")
                        continue;
 
                    Params.Inputs.Remove(i);
                }
                return true;
            }
            catch { return false; }
        }
    }
 
    [Serializable]
    public class UserRecord
    {
        [JsonConstructor]
        public UserRecord() { }
 
        //public UserRecord(HPoint Pose, string Msg, bool Result = true)
        //{
        //    this.Pose = Pose;
        //    this.Msg = Msg;
        //    this.Result = Result;
        //}
 
        //public UserRecord(HPoint Pose, ROI Obj, bool Result = true, string Msg = "")
        //{
        //    this.Pose = Pose;
        //    this.Obj = Obj;
        //    this.Result = Result;
        //    this.Msg = Msg;
        //}
 
        [JsonProperty]
        public string MsgMap = "";
        [JsonProperty]
        public string ShapeMap = "";
        [JsonProperty]
        public string ResultMap = "True";
        [JsonProperty]
        public string XMap = "0";
        [JsonProperty]
        public string YMap = "0";
 
        //public bool Result = false;
 
        //public string Msg = "";
 
        //public HPoint Pose = new HPoint();
 
        //public ROI Obj = new ROI();
    }
 
    public class OrderedConcurrentDictionary
    {
        private readonly ConcurrentDictionary<int, object> _dictionary = new();
        private readonly ConcurrentQueue<int> _keyQueue = new();
        private int _currentMaxKey = 0;
        private readonly object _reorderLock = new();
 
        public int Count { get { return _dictionary.Count; } }
 
        public bool Add(object value)
        {
            lock (_reorderLock)
            {
                int newKey = GetNextKey();
                if (_dictionary.TryAdd(newKey, value))
                {
                    _keyQueue.Enqueue(newKey);
                    return true;
                }
            }
            return false;
        }
 
        public bool Remove(int key)
        {
            if (_dictionary.TryRemove(key, out _))
            {
                lock (_reorderLock)
                {
                    // 重新排序
                    ReorderDictionary();
                }
                return true;
            }
            return false;
        }
 
        public bool Clear()
        {
            try
            {
                while (Count > 0)
                    Remove(Count - 1);
 
                return true;
            }
            catch { return false; }
        }
 
        public bool TryGetValue(int key, out object value)
        {
            return _dictionary.TryGetValue(key, out value);
        }
 
        private int GetNextKey()
        {
            return Interlocked.Increment(ref _currentMaxKey);
        }
 
        private void ReorderDictionary()
        {
            // 获取当前所有值
            var values = _dictionary.Values.ToArray();
 
            // 清空字典和队列
            _dictionary.Clear();
            while (_keyQueue.TryDequeue(out _)) { }
 
            // 重新添加并更新键
            for (int i = 0; i < values.Length; i++)
            {
                int newKey = i + 1;
                _dictionary.TryAdd(newKey, values[i]);
                _keyQueue.Enqueue(newKey);
            }
 
            // 更新最大键值
            _currentMaxKey = values.Length;
        }
    }
}