■ 도형을 검출하는 방법을 보여준다.
▶ MainForm.cs
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 |
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Text; using System.Windows.Forms; using Emgu.CV; using Emgu.CV.CvEnum; using Emgu.CV.Structure; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); this.filePathTextBox.TextChanged += filePathTextBox_TextChanged; this.filePathButton.Click += filePathButton_Click; this.filePathTextBox.Text = "sample.png"; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 파일 경로 텍스트 박스 텍스트 변경시 처리하기 - filePathTextBox_TextChanged(sender, e) /// <summary> /// 파일 경로 텍스트 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void filePathTextBox_TextChanged(object sender, EventArgs e) { DetectShape(); } #endregion #region 파일 경로 버튼 클릭시 처리하기 - filePathButton_Click(sender, e) /// <summary> /// 파일 경로 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void filePathButton_Click(object sender, EventArgs e) { DialogResult result = this.openFileDialog.ShowDialog(); if(result == DialogResult.OK || result == DialogResult.Yes) { this.filePathTextBox.Text = this.openFileDialog.FileName; } } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 도형 검출하기 - DetectShape() /// <summary> /// 도형 검출하기 /// </summary> public void DetectShape() { if(this.filePathTextBox.Text != string.Empty) { StringBuilder stringBuilder = new StringBuilder("성능 : "); Image<Bgr, Byte> sourceImage = new Image<Bgr, byte>(this.filePathTextBox.Text).Resize(400, 400, INTER.CV_INTER_LINEAR, true); Image<Gray, Byte> grayscaleImage = sourceImage.Convert<Gray, Byte>().PyrDown().PyrUp(); Stopwatch stopwatch = Stopwatch.StartNew(); #region 원을 검출한다. double cannyThreshold = 180.0; double circleAccumulatorThreshold = 120; CircleF[][] circleArray = grayscaleImage.HoughCircles ( new Gray(cannyThreshold), new Gray(circleAccumulatorThreshold), 2.0, // 원 중심 검출에 사용되는 누산기 해상도 20.0, // 최소 거리 5, // 최소 반경 0 // 최대 반경 ); #endregion stopwatch.Stop(); stringBuilder.Append(String.Format("원 - {0} 밀리초; ", stopwatch.ElapsedMilliseconds)); stopwatch.Reset(); stopwatch.Start(); #region 선을 검출한다. double cannyThresholdLinking = 120.0; Image<Gray, Byte> cannyEdges = grayscaleImage.Canny(cannyThreshold, cannyThresholdLinking); LineSegment2D[][] lineArray = cannyEdges.HoughLinesBinary ( 1, // 거리 해상도 (픽셀 관련 단위) Math.PI / 45.0, // 라디안으로 측정되는 각도 해상도 20, // 한계점 30, // 최소 선 너비 10 // 선간 간격 ); #endregion stopwatch.Stop(); stringBuilder.Append(String.Format("선 - {0} 밀리초; ", stopwatch.ElapsedMilliseconds)); stopwatch.Reset(); stopwatch.Start(); #region 삼각형과 사각형을 검출한다. List<Triangle2DF> triangleList = new List<Triangle2DF>(); List<MCvBox2D> rectangleList = new List<MCvBox2D>(); using(MemStorage storage = new MemStorage()) { for(Contour<Point> pointContour = cannyEdges.FindContours(CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE, RETR_TYPE.CV_RETR_LIST, storage); pointContour != null; pointContour = pointContour.HNext) { Contour<Point> currentContour = pointContour.ApproxPoly(pointContour.Perimeter * 0.05, storage); if(currentContour.Area > 250) { if(currentContour.Total == 3) // 삼각형인 경우 { Point[] pointArray = currentContour.ToArray(); triangleList.Add(new Triangle2DF(pointArray[0], pointArray[1], pointArray[2])); } else if(currentContour.Total == 4) // 사각형인 경우 { #region 윤곽의 모든 각도가 [80, 100]도 이내인지 결정한다. bool isRectangle = true; Point[] pointArray = currentContour.ToArray(); LineSegment2D[] edgeArray = PointCollection.PolyLine(pointArray, true); for(int i = 0; i < edgeArray.Length; i++) { double angle = Math.Abs(edgeArray[(i + 1) % edgeArray.Length].GetExteriorAngleDegree(edgeArray[i])); if(angle < 80 || angle > 100) { isRectangle = false; break; } } #endregion if(isRectangle) { rectangleList.Add(currentContour.GetMinAreaRect()); } } } } } #endregion stopwatch.Stop(); stringBuilder.Append(String.Format("삼각형/사각형 - {0} 밀리초; ", stopwatch.ElapsedMilliseconds)); Text = stringBuilder.ToString(); this.originalImageBox.Image = sourceImage; #region 삼각형/사각형을 그린다. Image<Bgr, Byte> triangleRectangleImage = sourceImage.CopyBlank(); foreach(Triangle2DF triangle in triangleList) { triangleRectangleImage.Draw(triangle, new Bgr(Color.DarkBlue), 2); } foreach(MCvBox2D rectangle in rectangleList) { triangleRectangleImage.Draw(rectangle, new Bgr(Color.DarkOrange), 2); } this.triangleRectangleImageBox.Image = triangleRectangleImage; #endregion #region 원을 그린다. Image<Bgr, Byte> circleImage = sourceImage.CopyBlank(); foreach(CircleF circle in circleArray[0]) { circleImage.Draw(circle, new Bgr(Color.Brown), 2); } this.circleImageBox.Image = circleImage; #endregion #region 선을 그린다. Image<Bgr, Byte> lineImage = sourceImage.CopyBlank(); foreach(LineSegment2D line in lineArray[0]) { lineImage.Draw(line, new Bgr(Color.Green), 2); } this.lineImageBox.Image = lineImage; #endregion } } #endregion } } |