Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Contour.cs « EmguCV « UVtools.Core - github.com/sn4k3/UVtools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 20d216e1d8448d80150ea480dcaefc83d6e1d70d (plain)
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
/*
 *                     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 System.Collections.Generic;
using System.Drawing;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using UVtools.Core.Extensions;

namespace UVtools.Core.EmguCV
{
    /// <summary>
    /// A contour cache for OpenCV
    /// </summary>
    public class Contour : IReadOnlyCollection<Point>, IDisposable
    {
        #region Members

        private VectorOfPoint _points;
        private Rectangle? _bounds;
        private RotatedRect? _boundsBestFit;
        private CircleF? _minEnclosingCircle;
        private bool? _isConvex;
        private double _area = double.NaN;
        private double _perimeter = double.NaN;
        private Moments _moments;
        private Point? _centroid;

        #endregion

        #region Properties
        public int XMin => Bounds.X;

        public int YMin => Bounds.Y;

        public int XMax => Bounds.Right;

        public int YMax => Bounds.Bottom;

        public Rectangle Bounds => _bounds ??= CvInvoke.BoundingRectangle(_points);

        public RotatedRect BoundsBestFit => _boundsBestFit ??= CvInvoke.MinAreaRect(_points);

        public CircleF MinEnclosingCircle => _minEnclosingCircle ??= CvInvoke.MinEnclosingCircle(_points);

        public bool IsConvex => _isConvex ??= CvInvoke.IsContourConvex(_points);

        /// <summary>
        /// Gets the area of the contour
        /// </summary>
        public double Area
        {
            get
            {
                if (double.IsNaN(_area))
                {
                    _area = CvInvoke.ContourArea(_points);
                }
                
                return _area;
            }
        }

        /// <summary>
        /// Gets the perimeter of the contours
        /// </summary>
        public double Perimeter
        {
            get
            {
                if (double.IsNaN(_perimeter))
                {
                    _perimeter = CvInvoke.ArcLength(_points, true);
                }
                return _perimeter;
            }
        }

        public Moments Moments => _moments ??= CvInvoke.Moments(_points);

        /// <summary>
        /// Gets the centroid of the contour
        /// </summary>
        public Point Centroid => _centroid ??= Moments.M00 == 0 ? Point.Empty : 
            new Point(
            (int)Math.Round(_moments.M10 / _moments.M00),
            (int)Math.Round(_moments.M01 / _moments.M00));

        /// <summary>
        /// Gets or sets the contour <see cref="Point"/>
        /// </summary>
        public VectorOfPoint Points
        {
            get => _points;
            set
            {
                Dispose();
                _points = value ?? throw new ArgumentNullException(nameof(Points));
            }
        }


        /// <summary>
        /// Gets if this contour have any point
        /// </summary>
        public bool IsEmpty => _points.Size == 0;
        #endregion

        #region Constructor
        public Contour(VectorOfPoint points) : this(points.ToArray())
        { }

        public Contour(Point[] points)
        {
            Points = new VectorOfPoint(points);
        }
        #endregion

        #region Methods

        /// <summary>
        /// Checks if a given <see cref="Point"/> is inside the contour rectangle bounds
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>
        public bool IsInsideBounds(Point point) => Bounds.Contains(point);

        /// <summary>
        /// Gets if a given <see cref="Point"/> is inside the contour
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>
        public bool IsInside(Point point)
        {
            if (!IsInsideBounds(point)) return false;
            return CvInvoke.PointPolygonTest(_points, point, false) >= 0;
        }

        public double MeasureDist(Point point)
        {
            if (!IsInsideBounds(point)) return -1;
            return CvInvoke.PointPolygonTest(_points, point, true);
        }

        public IOutputArray ContourApproximation(double epsilon = 0.1)
        {
            var mat = new Mat();
            CvInvoke.ApproxPolyDP(_points, mat, epsilon*Perimeter, true);
            return mat;
        }

        /*
        /// <summary>
        /// Calculate the X/Y min/max boundary
        /// </summary>
        private void CalculateMinMax()
        {
            Bounds = Rectangle.Empty;

            if (_contourPoints.Length == 0)
            {
                _xMin = -1;
                _yMin = -1;
                _xMax = -1;
                _yMax = -1;
                return;
            }

            _xMin = int.MaxValue;
            _yMin = int.MaxValue;
            _xMax = int.MinValue;
            _yMax = int.MinValue;

            for (int i = 0; i < _contourPoints.Length; i++)
            {
                _xMin = Math.Min(_xMin, _contourPoints[i].X);
                _yMin = Math.Min(_yMin, _contourPoints[i].Y);

                _xMax = Math.Max(_xMax, _contourPoints[i].X);
                _yMax = Math.Max(_yMax, _contourPoints[i].Y);
            }

            Bounds = new Rectangle(_xMin, _yMin, _xMax - _xMin, _yMax - _yMin);
        }
        */

        public void FitCircle(Mat src, MCvScalar color, int thickness = 1, LineType lineType = LineType.EightConnected, int shift = 0)
        {
            CvInvoke.Circle(src, 
                MinEnclosingCircle.Center.ToPoint(), 
                (int) Math.Round(MinEnclosingCircle.Radius), 
                color, 
                thickness, 
                lineType, 
                shift);
        }

        /*public void FitEllipse(Mat src, MCvScalar color, int thickness = 1, LineType lineType = LineType.EightConnected, int shift = 0)
        {
            var ellipse = CvInvoke.FitEllipse(_points);
            CvInvoke.Ellipse(src, ellipse.Center.ToPoint(), ellipse.Size.ToSize(), ellipse.Angle, 0, 0);
        }*/
        #endregion

        #region Implementations

        public IEnumerator<Point> GetEnumerator()
        {
            return (IEnumerator<Point>) _points.ToArray().GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public int Count => _points.Size;

        public Point this[int index] => _points[index];
        public Point this[uint index] => _points[(int) index];
        public Point this[long index] => _points[(int) index];
        public Point this[ulong index] => _points[(int) index];

        public void Dispose()
        {
            _points?.Dispose();
            _moments?.Dispose();
        }
        #endregion
    }
}