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
|
/*
* GNU AFFERO GENERAL PUBLIC LICENSE
* Version 3, 19 November 2007
* Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/
using System;
using System.Collections;
using Emgu.CV;
using Emgu.CV.Util;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using Emgu.CV.CvEnum;
using UVtools.Core.Extensions;
namespace UVtools.Core.EmguCV;
/// <summary>
/// Utility methods for contour handling.
/// Use only with Tree type
/// </summary>
public class EmguContours : IReadOnlyList<EmguContour>, IDisposable
{
private readonly EmguContour[] _contours;
public IEnumerator<EmguContour> GetEnumerator()
{
return ((IEnumerable<EmguContour>)_contours).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _contours.GetEnumerator();
}
public int Count => _contours.Length;
public readonly int[,] Hierarchy = new int[0,0];
public EmguContour this[int index] => _contours[index];
public EmguContours(VectorOfVectorOfPoint vectorOfPointsOfPoints)
{
_contours = new EmguContour[vectorOfPointsOfPoints.Size];
for (int i = 0; i < _contours.Length; i++)
{
_contours[i] = new EmguContour(vectorOfPointsOfPoints[i]);
}
}
public EmguContours(VectorOfVectorOfPoint vectorOfPointsOfPoints, int[,] hierarchy) : this(vectorOfPointsOfPoints)
{
Hierarchy = hierarchy;
}
public EmguContours(IInputOutputArray mat, RetrType mode = RetrType.List, ChainApproxMethod method = ChainApproxMethod.ChainApproxSimple, Point offset = default)
{
using var contours = mat.FindContours(out Hierarchy, mode, method, offset);
_contours = new EmguContour[contours.Size];
for (int i = 0; i < _contours.Length; i++)
{
_contours[i] = new EmguContour(contours[i]);
}
}
public (int Index, EmguContour Contour, double Distance)[][] CalculateCentroidDistances(bool includeOwn = false, bool sortByDistance = true)
{
var items = new (int Index, EmguContour Contour, double Distance)[Count][];
for (int i = 0; i < Count; i++)
{
items[i] = new (int Index, EmguContour Contour, double Distance)[Count-1];
int count = 0;
for (int x = 0; x < Count; x++)
{
if (x == i)
{
if (includeOwn)
{
items[i][count] = new(x, this[x], 0);
}
continue;
}
items[i][count] = new (x, this[x], PointExtensions.FindLength(this[i].Centroid, this[x].Centroid));
count++;
}
if(sortByDistance) items[i] = items[i].OrderBy(tuple => tuple.Distance).ToArray();
}
return items;
}
public void Dispose()
{
foreach (var contour in _contours)
{
contour.Dispose();
}
}
/// <summary>
/// Gets contours inside a point
/// </summary>
/// <param name="contours"></param>
/// <param name="hierarchy"></param>
/// <param name="location"></param>
/// <param name="includeLimitingArea">If true it will include all limiting area, otherwise only outer contour will be returned</param>
/// <returns></returns>
public static VectorOfVectorOfPoint GetContoursInside(VectorOfVectorOfPoint contours, int[,] hierarchy, Point location, bool includeLimitingArea = true)
{
var vector = new VectorOfVectorOfPoint();
var vectorSize = contours.Size;
for (var i = vectorSize - 1; i >= 0; i--)
{
if (CvInvoke.PointPolygonTest(contours[i], location, false) < 0) continue;
vector.Push(contours[i]);
if (!includeLimitingArea) break;
for (int n = i + 1; n < vectorSize; n++)
{
if (hierarchy[n, EmguContour.HierarchyParent] != i) continue;
vector.Push(contours[n]);
}
break;
}
return vector;
}
/// <summary>
/// Gets a contour given a location.
/// </summary>
/// <param name="contours"></param>
/// <param name="location"></param>
/// <param name="index">Contour index, -1 if not exists</param>
/// <returns>null if not exists</returns>
public static VectorOfPoint? GetContourInside(VectorOfVectorOfPoint contours, Point location, out int index)
{
index = -1;
var vectorSize = contours.Size;
for (int i = vectorSize - 1; i >= 0; i--)
{
if (CvInvoke.PointPolygonTest(contours[i], location, false) < 0) continue;
index = i;
return contours[i];
}
return null;
}
/// <summary>
/// Gets only the outer most external contours
/// Only compatible with Tree type of contour detection
/// </summary>
/// <param name="contours"></param>
/// <param name="hierarchy"></param>
/// <returns></returns>
public static VectorOfVectorOfPoint GetExternalContours(VectorOfVectorOfPoint contours, int[,] hierarchy)
{
var result = new VectorOfVectorOfPoint();
var vectorSize = contours.Size;
for (var i = 0; i < vectorSize; i++)
{
if (hierarchy[i, EmguContour.HierarchyParent] != -1) continue;
result.Push(contours[i]);
}
return result;
}
/// <summary>
/// Gets contours inside contours that are black pixels
/// </summary>
/// <param name="contours"></param>
/// <param name="hierarchy"></param>
/// <returns></returns>
public static VectorOfVectorOfPoint GetNegativeContours(VectorOfVectorOfPoint contours, int[,] hierarchy)
{
var result = new VectorOfVectorOfPoint();
var vectorSize = contours.Size;
for (var i = 0; i < vectorSize; i++)
{
if (hierarchy[i, EmguContour.HierarchyParent] == -1) continue;
result.Push(contours[i]);
}
return result;
}
/// <summary>
/// Gets contours that are positive and negative pixels and group them by areas
/// Only compatible with Tree type of contour detection
/// </summary>
/// <returns></returns>
public static List<VectorOfVectorOfPoint>[] GetContoursInGroups(VectorOfVectorOfPoint contours, int[,] hierarchy)
{
return new []{GetPositiveContoursInGroups(contours, hierarchy), GetNegativeContoursInGroups(contours, hierarchy)};
}
/// <summary>
/// Gets contours that are positive pixels and group them by areas
/// Only compatible with Tree type of contour detection
/// </summary>
/// <returns></returns>
public static List<VectorOfVectorOfPoint> GetPositiveContoursInGroups(VectorOfVectorOfPoint contours, int[,] hierarchy)
{
var result = new List<VectorOfVectorOfPoint>();
var vectorSize = contours.Size;
var processedContours = new bool[vectorSize];
for (int i = 0; i < vectorSize; i++)
{
if (processedContours[i]) continue;
processedContours[i] = true;
var index = result.Count;
result.Add(new VectorOfVectorOfPoint(contours[i]));
for (int n = i + 1; n < vectorSize; n++)
{
if (processedContours[n] || hierarchy[n, EmguContour.HierarchyParent] != i) continue;
processedContours[n] = true;
result[index].Push(contours[n]);
}
}
return result;
}
/// <summary>
/// Gets contours inside contours that are black pixels and group them by areas
/// Only compatible with Tree type of contour detection
/// </summary>
/// <returns></returns>
public static List<VectorOfVectorOfPoint> GetNegativeContoursInGroups(VectorOfVectorOfPoint contours, int[,] hierarchy)
{
var result = new List<VectorOfVectorOfPoint>();
var vectorSize = contours.Size;
var processedContours = new bool[vectorSize];
for (int i = 0; i < vectorSize; i++)
{
if (processedContours[i]) continue;
processedContours[i] = true;
if (hierarchy[i, EmguContour.HierarchyParent] == -1) continue;
var index = result.Count;
result.Add(new VectorOfVectorOfPoint(contours[i]));
for (int n = i + 1; n < vectorSize; n++)
{
if (processedContours[n] || hierarchy[n, EmguContour.HierarchyParent] != i) continue;
processedContours[n] = true;
result[index].Push(contours[n]);
}
}
return result;
}
/// <summary>
/// Gets contour real area for a limited area
/// </summary>
/// <param name="contours"></param>
/// <returns></returns>
public static double GetContourArea(VectorOfVectorOfPoint contours)
{
var vectorSize = contours.Size;
if (vectorSize == 0) return 0;
double result = CvInvoke.ContourArea(contours[0]);
for (var i = 1; i < vectorSize; i++)
{
result -= CvInvoke.ContourArea(contours[i]);
}
return result;
}
/// <summary>
/// Gets the largest contour area from a contour list
/// </summary>
/// <param name="contours">Contour list</param>
/// <returns></returns>
public static double GetLargestContourArea(VectorOfVectorOfPoint contours)
{
var vectorSize = contours.Size;
if (vectorSize == 0) return 0;
double result = 0;
for (var i = 0; i < vectorSize; i++)
{
result = Math.Max(result, CvInvoke.ContourArea(contours[i]));
}
return result;
}
/// <summary>
/// Gets contours real area for a group of contours
/// </summary>
/// <param name="contours">Grouped contours</param>
/// <param name="useParallel">True to run in parallel</param>
/// <returns>Array with same size with contours area</returns>
public static double[] GetContoursArea(List<VectorOfVectorOfPoint> contours, bool useParallel = false)
{
var result = new double[contours.Count];
if (useParallel)
{
Parallel.For(0, contours.Count, CoreSettings.ParallelOptions, i =>
{
result[i] = GetContourArea(contours[i]);
});
}
else
{
for (var i = 0; i < contours.Count; i++)
{
result[i] = GetContourArea(contours[i]);
}
}
return result;
}
/// <summary>
/// Checks if two contours intersects and return the intersecting pixel count
/// </summary>
/// <param name="contour1">Contour 1</param>
/// <param name="contour2">Contour 2</param>
/// <returns>Intersecting pixel count</returns>
public static int ContoursIntersectingPixels(VectorOfVectorOfPoint contour1, VectorOfVectorOfPoint contour2)
{
var contour1Rect = CvInvoke.BoundingRectangle(contour1[0]);
var contour2Rect = CvInvoke.BoundingRectangle(contour2[0]);
/* early exit if the bounding rectangles don't intersect */
if (!contour1Rect.IntersectsWith(contour2Rect)) return 0;
var totalRect = Rectangle.Union(contour1Rect, contour2Rect);
using var contour1Mat = EmguExtensions.InitMat(totalRect.Size);
using var contour2Mat = EmguExtensions.InitMat(totalRect.Size);
var inverseOffset = new Point(-totalRect.X, -totalRect.Y);
CvInvoke.DrawContours(contour1Mat, contour1, -1, EmguExtensions.WhiteColor, -1, LineType.EightConnected, null, int.MaxValue, inverseOffset);
CvInvoke.DrawContours(contour2Mat, contour2, -1, EmguExtensions.WhiteColor, -1, LineType.EightConnected, null, int.MaxValue, inverseOffset);
CvInvoke.BitwiseAnd(contour1Mat, contour2Mat, contour1Mat);
return CvInvoke.CountNonZero(contour1Mat);
}
/// <summary>
/// Checks if two contours intersects
/// </summary>
/// <param name="contour1">Contour 1</param>
/// <param name="contour2">Contour 2</param>
/// <returns></returns>
public static bool ContoursIntersect(VectorOfVectorOfPoint contour1, VectorOfVectorOfPoint contour2)
{
return ContoursIntersectingPixels(contour1, contour2) > 0;
}
}
|