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
using HalconDotNet;
using OpenCvSharp;
using Point = OpenCvSharp.Point;
 
namespace LB_VisionProcesses.Alogrithms.OpenCvSharp
{
    [Process("OpenCvSharp_斑点工具", Category = "OpenCvSharp工具", Description = "创建OpenCvSharp_斑点工具")]
    public class BlobTool : TAlgorithm
    {
        public BlobTool()
        {
            strProcessClass = "LB_VisionProcesses.Alogrithms.OpenCvSharp.BlobTool";
            strProcessName = "OpenCvSharp_斑点工具";
 
            Params.Inputs.Add("MinThreshold", 127);
            Params.Inputs.Add("MaxThreshold", 255);
            Params.Inputs.Add("MinArea", 0);
            Params.Inputs.Add("MaxArea", double.MaxValue);
            Params.Inputs.Add("MinRow", 0.0);
            Params.Inputs.Add("MaxRow", double.MaxValue);
            Params.Inputs.Add("MinColumn", 0.0);
            Params.Inputs.Add("MaxColumn", double.MaxValue);
            Params.Inputs.Add("MinCircularity", 0.0);
            Params.Inputs.Add("MaxCircularity", 1.0); ;
            Params.Inputs.Add("MinRectangularity", 0.0);
            Params.Inputs.Add("MaxRectangularity", 1.0);
            Params.Inputs.Add("MinCount", 0);
            Params.Inputs.Add("MaxCount", 9999);
 
            Params.Outputs.Add("CenterX", new List<double>());
            Params.Outputs.Add("CenterY", new List<double>());
            Params.Outputs.Add("Angle", new List<double>());
            Params.Outputs.Add("Width", new List<double>());
            Params.Outputs.Add("Height", new List<double>());
            Params.Outputs.Add("Area", new List<double>());
            Params.Outputs.Add("Count", 0);
        }
 
        /// <summary>
        /// 算子逻辑
        /// </summary>
        public override void TAlgorithmMain()
        {
            #region 初始化变量
            HObject ho_Regions, ho_ConnectedRegions, ho_SelectedRegions;
            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;
                //判断是否为灰度图
                try
                {
                    if (hoDomainImage.Channels() != 1)
                        Cv2.CvtColor(hoDomainImage, hoDomainImage, ColorConversionCodes.RGB2GRAY);
 
                    //转换后再次检查是否为灰度图
                    if (hoDomainImage.Channels() != 1)
                    {
                        Msg = "输入图片不为灰度图";
                        Result = false;
                        return;
                    }
                }
                catch
                {
                    Msg = "输入图片不为灰度图且转换失败";
                    Result = false;
                    return;
                }
                #endregion
 
                #region 算子逻辑
                Record = new ObjectRecord();
                double MinThreshold = Convert.ToDouble(Params.Inputs["MinThreshold"]);
                double MaxThreshold = Convert.ToDouble(Params.Inputs["MaxThreshold"]);
                double MinArea = Convert.ToDouble(Params.Inputs["MinArea"]);
                double MaxArea = Convert.ToDouble(Params.Inputs["MaxArea"]);
                double MinRow = Convert.ToDouble(Params.Inputs["MinRow"]);
                double MaxRow = Convert.ToDouble(Params.Inputs["MaxRow"]);
                double MinColumn = Convert.ToDouble(Params.Inputs["MinColumn"]);
                double MaxColumn = Convert.ToDouble(Params.Inputs["MaxColumn"]);
                double MinCircularity = Convert.ToDouble(Params.Inputs["MinCircularity"]);
                double MaxCircularity = Convert.ToDouble(Params.Inputs["MaxCircularity"]);
                double MinRectangularity = Convert.ToDouble(Params.Inputs["MinRectangularity"]);
                double MaxRectangularity = Convert.ToDouble(Params.Inputs["MaxRectangularity"]);
                List<Blob> results = AnalyzeBlobs(hoDomainImage, MinArea, MaxArea, MinCircularity, MinRectangularity, MinThreshold, MaxThreshold);
                #endregion
 
                #region 结果处理
                //计数用于后续判断
                List<double> CenterX = new List<double>();
                List<double> CenterY = new List<double>();
                List<double> Angle = new List<double>();
                List<double> Width = new List<double>();
                List<double> Height = new List<double>();
                List<double> Area = new List<double>();
                for (int i = 0; i < results.Count; i++)
                {
                    // 填充为矩形
                    CenterX.Add(Convert.ToDouble(results[i].RotatedBoundingBox.Center.X));
                    CenterY.Add(Convert.ToDouble(results[i].RotatedBoundingBox.Center.Y));
                    Angle.Add(Convert.ToDouble(results[i].RotatedBoundingBox.Angle));
                    Width.Add(Convert.ToDouble(results[i].RotatedBoundingBox.Size.Width));
                    Height.Add(Convert.ToDouble(results[i].RotatedBoundingBox.Size.Height));
                    Area.Add(results[i].ContourArea);
 
                    //HOperatorSet.GenRectangle2(out HObject hRectangle, CenterY[i], CenterX[i], -1 * Angle[i] / 180 * Math.PI
                    //    , Width[i] / 2, Height[i] / 2);
                    //((ObjectRecord)Record).AddRecord(hRectangle);
 
                    var contourArray = results[i].Contour.ToArray();
                    int count = contourArray.Length;
 
                    int[] Xpoints = new int[count + 1];
                    int[] Ypoints = new int[count + 1];
 
                    Parallel.For(0, count, j =>
                    {
                        var point = contourArray[j];
                        Xpoints[j] = point.X;
                        Ypoints[j] = point.Y;
                    });
 
                    Xpoints[count] = Xpoints[0];
                    Ypoints[count] = Ypoints[0];
 
                    HOperatorSet.GenContourPolygonXld(out HObject contour, new HTuple(Ypoints), new HTuple(Xpoints));
                    ((ObjectRecord)Record).AddXld(contour);
                }
 
 
 
 
 
                Params.Outputs["CenterX"] = CenterX;
                Params.Outputs["CenterY"] = CenterY;
                Params.Outputs["Angle"] = Angle;
                Params.Outputs["Width"] = Width;
                Params.Outputs["Height"] = Height;
                Params.Outputs["Area"] = Area;
                Params.Outputs["Count"] = CenterX.Count;
                #endregion
 
                #region 生成OutputImage给后续处理
                try
                {
                    OutputImage = DomainImage;
                }
                catch (Exception ex)
                {
                    Msg = "生成OutputImage失败,原因是:" + ex.ToString();
                    Result = false;
                    return;
                }
                #endregion
 
                if (Msg == "运行超时")
                {
                    Result = false;
                    return;
                }
 
                int MinCount = ProcessParams.ConvertToInt32(Params.Inputs["MinCount"]);
                int MaxCount = ProcessParams.ConvertToInt32(Params.Inputs["MaxCount"]);
 
                if (CenterX.Count < MinCount || CenterX.Count > MaxCount)
                {
                    Msg = string.Format("结果个数超出范围({0},{1})", MinCount, MaxCount);
                    Record.ChangeAll2False();
                    Result = false;
                    return;
                }
 
                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 class BlobRotatedRect
        {
            public Point2f Center { get; set; }
            public Size2f Size { get; set; }
            public float Angle { get; set; }
            public Point2f[] Points { get; set; }
 
            public BlobRotatedRect() { }
 
            public BlobRotatedRect(RotatedRect rect)
            {
                Center = rect.Center;
                Size = rect.Size;
                Angle = rect.Angle;
                Points = Cv2.BoxPoints(rect);
            }
        }
 
        public class Blob
        {
            public int Id { get; set; }
            //public Rect BoundingBox { get; set; }
            public BlobRotatedRect RotatedBoundingBox { get; set; }
            //public Point2f Centroid { get; set; }
            //public double Area { get; set; }
            public double Perimeter { get; set; }
            public double Circularity { get; set; }
            public double Rectangularity { get; set; }
            public double AspectRatio { get; set; }
            public List<Point> Contour { get; set; }
            public double ContourArea { get; set; }
            //public double RotatedRectArea { get; set; }
        }
 
        public static List<Blob> AnalyzeBlobs(Mat image,
            double minArea = 50,
            double maxArea = 10000,
            double minCircularity = 0.1,
            double minRectangularity = 0.5,
            double minThreshold = 0,
            double maxThreshold = 255,
            ThresholdTypes thresholdType = ThresholdTypes.Binary)
        {
            var blobs = new List<Blob>();
 
            // 转换为灰度图
            Mat gray = new Mat();
            if (image.Channels() == 3)
                Cv2.CvtColor(image, gray, ColorConversionCodes.BGR2GRAY);
            else
                image.CopyTo(gray);
 
            // 阈值分割
            Mat binary = new Mat();
            Cv2.Threshold(gray, binary, minThreshold, maxThreshold, thresholdType);
 
            // 查找轮廓
            Point[][] contours;
            HierarchyIndex[] hierarchy;
            Cv2.FindContours(binary, out contours, out hierarchy,
                RetrievalModes.External, ContourApproximationModes.ApproxSimple);
 
            // 处理每个轮廓
            for (int i = 0; i < contours.Length; i++)
            {
                var contour = contours[i];
                if (contour.Length < 5) continue; // 至少需要5个点才能拟合旋转矩形
 
                double area = Cv2.ContourArea(contour);
 
                // 面积过滤
                if (area < minArea || area > maxArea)
                    continue;
 
                // 计算周长
                double perimeter = Cv2.ArcLength(contour, true);
 
                // 计算圆形度
                double circularity = (4 * Math.PI * area) / (perimeter * perimeter);
 
                // 圆形度过滤
                if (circularity < minCircularity)
                    continue;
 
                // 计算外接矩形
                Rect boundingBox = Cv2.BoundingRect(contour);
 
                // 计算最小外接矩形(带角度)
                RotatedRect rotatedRect = Cv2.MinAreaRect(contour);
                BlobRotatedRect rotatedBoundingBox = new BlobRotatedRect(rotatedRect);
 
                // 计算质心
                Moments moments = Cv2.Moments(contour);
                Point2f centroid = new Point2f(
                    (float)(moments.M10 / moments.M00),
                    (float)(moments.M01 / moments.M00)
                );
 
                // 计算矩形度
                double rectangularity = CalculateRectangularity(contour, rotatedRect);
 
                // 矩形度过滤
                if (rectangularity < minRectangularity)
                    continue;
 
                // 计算宽高比
                double aspectRatio = CalculateAspectRatio(rotatedRect);
 
                blobs.Add(new Blob
                {
                    Id = i,
                    //Area = area,
                    Perimeter = perimeter,
                    Circularity = circularity,
                    Rectangularity = rectangularity,
                    AspectRatio = aspectRatio,
                    //BoundingBox = boundingBox,
                    RotatedBoundingBox = rotatedBoundingBox,
                    //Centroid = centroid,
                    Contour = new List<Point>(contour),
                    ContourArea = area
                    //RotatedRectArea = rotatedRect.Size.Width * rotatedRect.Size.Height
                });
            }
 
            gray.Dispose();
            binary.Dispose();
 
            return blobs;
        }
 
        /// <summary>
        /// 计算矩形度(轮廓面积与最小外接矩形面积的比值)
        /// </summary>
        private static double CalculateRectangularity(Point[] contour, RotatedRect rotatedRect)
        {
            double contourArea = Cv2.ContourArea(contour);
            double rotatedRectArea = rotatedRect.Size.Width * rotatedRect.Size.Height;
 
            if (rotatedRectArea == 0) return 0;
 
            return contourArea / rotatedRectArea;
        }
 
        /// <summary>
        /// 计算宽高比
        /// </summary>
        private static double CalculateAspectRatio(RotatedRect rotatedRect)
        {
            double width = rotatedRect.Size.Width;
            double height = rotatedRect.Size.Height;
 
            if (height == 0) return double.MaxValue;
 
            // 确保宽高比始终 >= 1
            return width >= height ? width / height : height / width;
        }
 
        /// <summary>
        /// 根据矩形度过滤Blob
        /// </summary>
        public static List<Blob> FilterByRectangularity(List<Blob> blobs, double minRectangularity, double maxRectangularity = 1.0)
        {
            return blobs.Where(b => b.Rectangularity >= minRectangularity && b.Rectangularity <= maxRectangularity).ToList();
        }
 
        /// <summary>
        /// 根据宽高比过滤Blob
        /// </summary>
        public static List<Blob> FilterByAspectRatio(List<Blob> blobs, double minAspectRatio, double maxAspectRatio)
        {
            return blobs.Where(b => b.AspectRatio >= minAspectRatio && b.AspectRatio <= maxAspectRatio).ToList();
        }
 
        /// <summary>
        /// 根据方向角度过滤Blob
        /// </summary>
        public static List<Blob> FilterByAngle(List<Blob> blobs, double minAngle, double maxAngle)
        {
            return blobs.Where(b =>
            {
                double angle = Math.Abs(b.RotatedBoundingBox.Angle);
                // 处理角度周期性
                if (angle > 90) angle = 180 - angle;
                return angle >= minAngle && angle <= maxAngle;
            }).ToList();
        }
    }
}