C3204
2025-12-18 d85cbf0ccd61d95b96695756e0c90db8b7679545
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
using HalconDotNet;
using LB_VisionControl;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace LB_VisionProcesses.Alogrithms.Halcon
{
 
    public class HCaltab : IDisposable
    {
        public HCaltab() { }
 
        public HCaltab(HCaltab HCaltab)
        {
            CameraInner = HCaltab.CameraInner.Clone();
            CameraPose = HCaltab.CameraPose.Clone();
            CameraInner_Adaptive = HCaltab.CameraInner_Adaptive.Clone();
            Map = HCaltab.Map.Clone();
            Xld = HCaltab.Xld.Clone();
 
            CaltbImages = new List<HObject>(HCaltab.CaltbImages);
            Params.XNum = HCaltab.Params.XNum;
            Params.YNum = HCaltab.Params.YNum;
            Params.MarkDist = HCaltab.Params.MarkDist;
            Params.DiameterRatio = HCaltab.Params.DiameterRatio;
            Params.Focus = HCaltab.Params.Focus;
            Params.Kappa = HCaltab.Params.Kappa;
            Params.Sx = HCaltab.Params.Sx;
            Params.Sy = HCaltab.Params.Sy;
            Params.Width = HCaltab.Params.Width;
            Params.Height = HCaltab.Params.Height;
        }
 
        public void Dispose()
        {
            try
            {
                ClearCaltbImages();
 
                if (Map != null && Map.IsInitialized())
                    Map.Dispose();
 
                if (Xld != null && Xld.IsInitialized())
                    Xld.Dispose();
            }
            catch { }
        }
 
        /// <summary>
        /// 名称
        /// </summary>
        public string Name = "Calibration_0";
 
        /// <summary>
        /// 信息
        /// </summary>
        public string Msg = "";
 
        /// <summary>
        /// 结果
        /// </summary>
        public bool Result
        {
            get
            {
                if (Map == null || !Map.IsInitialized())
                    return false;
 
                if (CameraInner_Adaptive == null || CameraInner_Adaptive.Length == 0
                    || CameraPose == null || CameraPose.Length == 0)
                    return false;
 
                return false;
            }
        }
 
        /// <summary>
        /// 文件路径
        /// </summary>
        public string FilePath = $"C://Name//";
 
        /// <summary>
        /// 标定参数文件
        /// </summary>
        public HCalibrationParam Params = new HCalibrationParam();
 
        List<HObject> CaltbImages = new List<HObject>();
 
        public HObject Image
        {
            get
            {
                if (CaltbImages.Count > 0)
                    return CaltbImages[0];
                else
                    return null;
            }
        }
 
        public HObject Xld = new HObject();
 
        /// <summary>
        /// 相机内参
        /// </summary>
        HTuple CameraInner = new HTuple();
 
        /// <summary>
        /// 相机外参
        /// </summary>
        HTuple CameraPose = new HTuple();
 
        /// <summary>
        /// 无畸变的相机内参
        /// </summary>
        HTuple CameraInner_Adaptive = new HTuple();
 
        /// <summary>
        /// 畸变变换图
        /// </summary>
        HObject Map = new HObject();
 
        #region 矫正结果
        public bool GetCaltbImage(HObject OriImage, out HObject CaltbImage)
        {
            CaltbImage = OriImage;
 
            try
            {
                if (OriImage == null || !OriImage.IsInitialized()
                || Map == null || !Map.IsInitialized())
                    return false;
 
                HOperatorSet.MapImage(OriImage, Map, out CaltbImage);
                return true;
            }
            catch { return false; }
        }
 
        public bool GetCaltbPoint(HPoint OriPoint, out HPoint CaltbPoint)
        {
            CaltbPoint = new HPoint(OriPoint);
 
            try
            {
                if (CameraInner_Adaptive == null || CameraInner_Adaptive.Length == 0
                    || CameraPose == null || CameraPose.Length == 0)
                    return false;
 
                HOperatorSet.ImagePointsToWorldPlane(CameraInner_Adaptive, CameraPose
                    , OriPoint.Row, OriPoint.Column, "mm", out HTuple row, out HTuple col);
 
                if (row.Length == 0 || col.Length == 0)
                    return false;
 
                CaltbPoint.Row = row.D;
                CaltbPoint.Column = col.D;
                return true;
            }
            catch { return false; }
        }
        #endregion
 
        public bool LoadCaltbImages()
        {
            try
            {
                ClearCaltbImages();
 
                for (int i = 0; i < 999; i++)
                {
                    string ImagePath = FilePath + $"//CaltbImages_{i}.bmp";
                    if (!File.Exists(ImagePath))
                        break;
 
                    HOperatorSet.ReadImage(out HObject ho_Image, ImagePath);
                }
 
                return true;
            }
            catch { return false; }
        }
 
        public bool SaveCaltbImages()
        {
            //判断文件夹是否存在,防呆输入为文件名称
            if (!Directory.Exists(FilePath))
            {
                try
                {
                    Directory.CreateDirectory(FilePath);
                }
                catch { }
            }
 
            try
            {
                for (int i = 0; i <= CaltbImages.Count; i++)
                {
                    string ImagePath = FilePath + $"//CaltbImages_{i}.bmp";
                    var Image = CaltbImages[i];
                    if (Image != null && Image.IsInitialized())
                    {
                        HOperatorSet.CountChannels(Image, out HTuple hv_Channels);
 
                        if (hv_Channels.TupleInt() != 1)
                            HOperatorSet.Rgb1ToGray(Image, out Image);
 
                        //Halcon存图需要用斜杠
                        ImagePath.Replace("\\", "/");
                        HOperatorSet.WriteImage(Image, "bmp", 0, ImagePath);
                    }
                }
            }
            catch { return false; }
 
            return true;
        }
 
        public void ClearCaltbImages()
        {
            foreach (var image in CaltbImages)
            {
                if (image != null && image.IsInitialized())
                    image.Dispose();
            }
            CaltbImages.Clear();
            CaltbImages = new List<HObject>();
        }
 
        public bool CheckCaltbImage(List<HObject> lst_Images = null, int Width = 0, int Height = 0)
        {
            if (lst_Images == null)
                lst_Images = CaltbImages;
 
            if (Width == 0 || Height == 0)
            {
                Width = Params.Width;
                Height = Params.Height;
            }
 
            foreach (var imge in lst_Images)
            {
                if (imge == null || !imge.IsInitialized())
                    return false;
 
                HOperatorSet.GetImageSize(imge, out HTuple hv_Width, out HTuple hv_Height);
                if (hv_Width.Length == 0 || hv_Height.Length == 0
                    || hv_Width.I != Width || hv_Height.I != Height)
                    return false;
            }
            return true;
        }
 
        public bool Caltb(List<HObject> lst_Images)
        {
            try
            {
                if (!CheckCaltbImage(lst_Images))
                    return false;
 
                BaseCalib.CreateCaltab(FilePath, Params.XNum, Params.YNum, Params.MarkDist, Params.DiameterRatio);
 
                BaseCalib.gen_cam_par_area_scan_division(Params.Focus / 1000.0, Params.Kappa
                    , Params.Sx / 1000000.0, Params.Sy / 1000000.0
                    , Params.Width / 2.0, Params.Height / 2.0, Params.Width, Params.Height, out HTuple CameraParam);
 
                string CalPlateDescr = Params.CalPlateDescr;
                string CameraInnerPath = FilePath + "//CameraInner_Adaptive.tup";
                string CameraPosePath = FilePath + "//CameraPose.tup";
 
                CalPlateDescr.Replace("\\", "/");
                CameraInnerPath.Replace("\\", "/");
                CameraPosePath.Replace("\\", "/");
 
                BaseCalib.CaltabCalib(CameraParam, lst_Images
                    , out HTuple hv_CameraInner, out HTuple hv_CameraPose, out HTuple hv_CameraInner_Adaptive
                    , out HObject ho_Map, out Xld
                    , CalPlateDescr, CameraInnerPath, CameraPosePath);
 
                if (hv_CameraInner == null || hv_CameraPose == null || hv_CameraInner_Adaptive == null
                    || ho_Map == null || !ho_Map.IsInitialized())
                    return false;
 
                CameraInner = hv_CameraInner.Clone();
                CameraPose = hv_CameraPose.Clone();
                CameraInner_Adaptive = hv_CameraInner_Adaptive.Clone();
                Map = ho_Map.Clone();
 
                CaltbImages = lst_Images;
                return SaveCaltbImages();
            }
            catch { return false; }
        }
 
        public bool Caltb(List<HObject> lst_Images, int XNum, int YNum, int MarkDist, double DiameterRatio
            , int Focus, int Kappa, double Sx, double Sy, int Width, int Height)
        {
            if (!CheckCaltbImage(lst_Images, Width, Height))
                return false;
 
            BaseCalib.CreateCaltab(FilePath, XNum, YNum, MarkDist, DiameterRatio);
 
            BaseCalib.gen_cam_par_area_scan_division(Focus / 1000.0, Kappa
                , Sx / 1000000.0, Sy / 1000000.0
                , Width / 2.0, Height / 2.0, Width, Height, out HTuple CameraParam);
 
            string CalPlateDescr = Params.CalPlateDescr;
            string CameraInnerPath = FilePath + "//CameraInner_Adaptive.tup";
            string CameraPosePath = FilePath + "//CameraPose.tup";
 
            CalPlateDescr.Replace("\\", "/");
            CameraInnerPath.Replace("\\", "/");
            CameraPosePath.Replace("\\", "/");
 
            BaseCalib.CaltabCalib(CameraParam, CaltbImages
                , out HTuple hv_CameraInner, out HTuple hv_CameraPose, out HTuple hv_CameraInner_Adaptive
                , out HObject ho_Map, out Xld
                , CalPlateDescr, CameraInnerPath, CameraPosePath);
 
            if (hv_CameraInner == null || hv_CameraPose == null || hv_CameraInner_Adaptive == null
                || ho_Map == null || !ho_Map.IsInitialized())
                return false;
 
            CameraInner = hv_CameraInner.Clone();
            CameraPose = hv_CameraPose.Clone();
            CameraInner_Adaptive = hv_CameraInner_Adaptive.Clone();
            Map = ho_Map.Clone();
 
            CaltbImages = lst_Images;
            Params.XNum = XNum;
            Params.YNum = YNum;
            Params.MarkDist = MarkDist;
            Params.DiameterRatio = DiameterRatio;
            Params.Focus = Focus;
            Params.Kappa = Kappa;
            Params.Sx = Sx;
            Params.Sy = Sy;
            Params.Width = Width;
            Params.Height = Height;
 
            return SaveCaltbImages();
        }
 
        public bool Load(string fullPath)
        {
            try
            {
                // 获取不带文件名的目录路径
                Name = Path.GetFileNameWithoutExtension(fullPath);
                // 修正真实路径,工具其路径为一个文件夹,而不是一个文件
                FilePath = Path.GetDirectoryName(fullPath) + Name;
 
                if (!File.Exists(fullPath))
                {
                    Debug.WriteLine("文件不存在创建空文件");
                    Save(FilePath);
                    return true;
                }
 
                string strJson = string.Empty;
                using (StreamReader streamReader = new StreamReader(fullPath, Encoding.UTF8))
                {
                    strJson = streamReader.ReadToEnd();
                    streamReader.Close();
                }
                Params = JsonConvert.DeserializeObject<HCalibrationParam>(strJson);
                if (Params == null)
                    return false;
 
                Params.Name = Name;
                Params.FilePath = FilePath;
 
                string CalPlateDescr = Params.CalPlateDescr;
                string CameraInnerPath = FilePath + "//CameraInner_Adaptive.tup";
                string CameraPosePath = FilePath + "//CameraPose.tup";
 
                //相机内参
                HOperatorSet.ReadTuple(CameraInnerPath, out CameraInner_Adaptive);
                //相机外参
                HOperatorSet.ReadTuple(CameraPosePath, out CameraPose);
 
                //BaseCalib.CreateCaltab(FilePath, Params.XNum, Params.YNum, Params.MarkDist, Params.DiameterRatio);
 
                //BaseCalib.gen_cam_par_area_scan_division(Params.Focus / 1000.0, Params.Kappa
                //    , Params.Sx / 1000000.0, Params.Sy / 1000000.0
                //    , Params.Width / 2.0, Params.Height / 2.0, Params.Width, Params.Height, out HTuple CameraParam);
 
                //CalPlateDescr.Replace("\\", "/");
                //CameraInnerPath.Replace("\\", "/");
                //CameraPosePath.Replace("\\", "/");
 
                //BaseCalib.CaltabCalib(CameraParam, CaltbImages
                //    , out CameraInner, out CameraPose, out CameraInner_Adaptive, out Map, out _
                //    , CalPlateDescr, CameraInnerPath, CameraPosePath);
 
                return LoadCaltbImages();
            }
            catch { return false; }
        }
 
        public bool Save(string filePath)
        {
            try
            {
                if (string.IsNullOrEmpty(filePath) || filePath.Trim() == "")
                {
                    Debug.WriteLine("文件路径不完整");
                    return false;
                }
 
                // 修正真实路径,工具其路径为一个文件夹,而不是一个文件
                filePath += ("//" + Name);
 
                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);
 
                Params = JsonConvert.DeserializeObject<HCalibrationParam>(strJson);
                //判断文件夹是否存在,防呆输入为文件名称
                if (!Directory.Exists(filePath))
                {
                    try
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    catch (Exception)
                    { }
                }
                // filePath 已经含了Name
                File.WriteAllText(filePath + "//Params.json", strJson, Encoding.UTF8);
 
                // filePath 已经含了Name
                FilePath = filePath;
                try
                {
                    string CameraInnerPath = FilePath + "//CameraInner_Adaptive.tup";
                    string CameraPosePath = FilePath + "//CameraPose.tup";
                    //相机内参
                    HOperatorSet.WriteTuple(CameraInner_Adaptive, CameraInnerPath);
                    //相机外参
                    HOperatorSet.WriteTuple(CameraPose, CameraPosePath);
                }
                catch { }
 
                return SaveCaltbImages();
            }
            catch { return false; }
        }
    }
 
    /// <summary>
    /// 畸变标定参数类
    /// </summary>
    [Serializable]
    public class HCalibrationParam
    {
        public HCalibrationParam() { }
 
        /// <summary>
        /// 名称
        /// </summary>
        public string Name = "Params";
 
        /// <summary>
        /// 文件路径
        /// </summary>
        public string FilePath = @"C://";
 
        /// <summary>
        /// 圆点行数
        /// </summary>
        public int XNum { get; set; } = 7;
 
        /// <summary>
        /// 圆点行数
        /// </summary>
        public int YNum { get; set; } = 7;
 
        /// <summary>
        /// 两个圆之间的距离, 单位mm
        /// </summary>
        public double MarkDist { get; set; } = 1.25;
 
        /// <summary>
        /// 比例值, Mark直径比上Mark中心距离
        /// </summary>
        public double DiameterRatio { get; set; } = 0.5;
 
        /// <summary>
        /// 用于标定的描述文件
        /// </summary>
        public string CalPlateDescr { get { return FilePath + $"//Caltab_{XNum}*{YNum}_{DiameterRatio}.descr"; } }
 
        /// <summary>
        /// 制作标定板的PS文件
        /// </summary>
        public string CalPlatePSFile { get { return FilePath + $"//Caltab_{XNum}*{YNum}_{DiameterRatio}.ps"; } }
 
        /// <summary>
        /// 厚度
        /// </summary>
        public int Thickness { get; set; } = 1;
 
        /// <summary>
        /// 相机类型(面扫描(除法))
        /// </summary>
        public string CamType { get; set; } = "area_scan_division";
 
        /// <summary>
        /// 单个相机像元的宽
        /// </summary>
        public double Sx { get; set; } = 8.3;
 
        /// <summary>
        /// 单个相机像元的高
        /// </summary>
        public double Sy { get; set; } = 8.3;
 
        /// <summary>
        /// 图像宽
        /// </summary>
        public int Width { get; set; } = 1120;
 
        /// <summary>
        /// 图像高
        /// </summary>
        public int Height { get; set; } = 1120;
 
        /// <summary>
        /// 镜头的焦距
        /// </summary>
        public double Focus { get; set; } = 8;
 
        public double Kappa { get; set; } = 0;
 
        /// <summary>
        /// 标定效果, 越接近0越越好
        /// </summary>
        public double RMS { get; set; } = 999.9;
    }
}