■ STOP 표지판을 인식하는 방법을 보여준다.
▶ StopSignDetector.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 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 |
using System; using System.Collections.Generic; using System.Drawing; using Emgu.CV; using Emgu.CV.CvEnum; using Emgu.CV.Features2D; using Emgu.CV.Structure; using Emgu.Util; namespace TestProject { /// <summary> /// STOP 표지판 검출기 /// </summary> public class StopSignDetector : DisposableObject { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 추적기 /// </summary> private Features2DTracker<float> tracker; /// <summary> /// 검출기 /// </summary> private SURFDetector detector; /// <summary> /// 팔각형 저장소 /// </summary> private MemStorage octagonStorage; /// <summary> /// 팔각형 윤곽선 /// </summary> private Contour<Point> octagonContour; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - StopSignDetector(modelImage) /// <summary> /// 생성자 /// </summary> /// <param name="modelImage">모델 이미지</param> public StopSignDetector(Image<Bgr, Byte> modelImage) { this.detector = new SURFDetector(500, false); using(Image<Gray, Byte> maskImage = GetRedPixelMaskImage(modelImage)) { ImageFeature<float>[] imageFeatureArray = this.detector.DetectFeatures(maskImage, null); if(imageFeatureArray.Length == 0) { throw new Exception("No image feature has been found in the stop sign model"); } this.tracker = new Features2DTracker<float>(imageFeatureArray); } this.octagonStorage = new MemStorage(); this.octagonContour = new Contour<Point>(this.octagonStorage); this.octagonContour.PushMulti ( new Point[] { new Point(1, 0), new Point(2, 0), new Point(3, 1), new Point(3, 2), new Point(2, 3), new Point(1, 3), new Point(0, 2), new Point(0, 1) }, BACK_OR_FRONT.FRONT ); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region STOP 표지판 검출하기 - DetectStopSign(sourceImage, imageList, rectangleList) /// <summary> /// STOP 표지판 검출하기 /// </summary> /// <param name="sourceImage">소스 이미지</param> /// <param name="imageList">이미지 리스트</param> /// <param name="rectangleList">사각형 리스트</param> public void DetectStopSign(Image<Bgr, byte> sourceImage, List<Image<Gray, Byte>> imageList, List<Rectangle> rectangleList) { Image<Bgr, Byte> smoothImage = sourceImage.SmoothGaussian(5, 5, 1.5, 1.5); Image<Gray, Byte> maskImage = GetRedPixelMaskImage(smoothImage); maskImage._Dilate(1); maskImage._Erode(1); using(Image<Gray, Byte> cannyImage = maskImage.Canny(100, 50)) { using(MemStorage storage = new MemStorage()) { Contour<Point> pointContour = cannyImage.FindContours ( CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE, RETR_TYPE.CV_RETR_TREE, storage ); FindStopSign(sourceImage, imageList, rectangleList, pointContour); } } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 객체 리소스 해제하기 - DisposeObject() /// <summary> /// 객체 리소스 해제하기 /// </summary> protected override void DisposeObject() { this.tracker.Dispose(); this.octagonStorage.Dispose(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 빨간색 픽셀 마스크 이미지 구하기 - GetRedPixelMaskImage(sourceImage) /// <summary> /// 빨간색 픽셀 마스크 이미지 구하기 /// </summary> /// <param name="sourceImage">소스 이미지</param> /// <returns>빨간색 픽셀 마스크 이미지</returns> private Image<Gray, Byte> GetRedPixelMaskImage(Image<Bgr, byte> sourceImage) { using(Image<Hsv, Byte> hsvImage = sourceImage.Convert<Hsv, Byte>()) { Image<Gray, Byte>[] channelImageArray = hsvImage.Split(); try { CvInvoke.cvInRangeS ( channelImageArray[0], new MCvScalar(20), new MCvScalar(160), channelImageArray[0] ); channelImageArray[0]._Not(); channelImageArray[1]._ThresholdBinary(new Gray(10), new Gray(255.0)); CvInvoke.cvAnd(channelImageArray[0], channelImageArray[1], channelImageArray[0], IntPtr.Zero); } finally { channelImageArray[1].Dispose(); channelImageArray[2].Dispose(); } return channelImageArray[0]; } } #endregion #region STOP 표지판 찾기 - FindStopSign(sourceImage, imageList, rectangleList, pointContour) /// <summary> /// STOP 표지판 찾기 /// </summary> /// <param name="sourceImage">소스 이미지</param> /// <param name="imageList">이미지 리스트</param> /// <param name="rectangleList">사각형 리스트</param> /// <param name="pointContour">포인트 윤곽선</param> private void FindStopSign(Image<Bgr, byte> sourceImage, List<Image<Gray, Byte>> imageList, List<Rectangle> rectangleList, Contour<Point> pointContour) { for(; pointContour != null; pointContour = pointContour.HNext) { pointContour.ApproxPoly(pointContour.Perimeter * 0.02, 0, pointContour.Storage); if(pointContour.Area > 200) { double ratio = CvInvoke.cvMatchShapes ( this.octagonContour, pointContour, CONTOURS_MATCH_TYPE.CV_CONTOURS_MATCH_I3, 0 ); if(ratio > 0.1) { Contour<Point> childPointContour = pointContour.VNext; if(childPointContour != null) { FindStopSign(sourceImage, imageList, rectangleList, childPointContour); } continue; } Rectangle rectangle = pointContour.BoundingRectangle; Image<Gray, Byte> candidateImage; using(Image<Bgr, Byte> temporaryImage = sourceImage.Copy(rectangle)) { candidateImage = temporaryImage.Convert<Gray, byte>(); } using(Image<Gray, Byte> maskImage = new Image<Gray, byte>(rectangle.Size)) { maskImage.Draw ( pointContour, new Gray(255), new Gray(255), 0, -1, new Point(-rectangle.X, -rectangle.Y) ); double mean = CvInvoke.cvAvg(candidateImage, maskImage).v0; candidateImage._ThresholdBinary(new Gray(mean), new Gray(255.0)); candidateImage._Not(); maskImage._Not(); candidateImage.SetValue(0, maskImage); } ImageFeature<float>[] imageFeatureArray = this.detector.DetectFeatures(candidateImage, null); int minimumMatchCount = 10; if(imageFeatureArray != null && imageFeatureArray.Length >= minimumMatchCount) { Features2DTracker<float>.MatchedImageFeature[] matchedImageFeatureArray = this.tracker.MatchFeature(imageFeatureArray, 2); int goodMatchCount = 0; foreach(Features2DTracker<float>.MatchedImageFeature matchedImageFeature in matchedImageFeatureArray) { if(matchedImageFeature.SimilarFeatures[0].Distance < 0.5) { goodMatchCount++; } } if(goodMatchCount >= minimumMatchCount) { rectangleList.Add(rectangle); imageList.Add(candidateImage); } } } } } #endregion } } |
▶ 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 |
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using Emgu.CV; using Emgu.CV.Structure; using Emgu.CV.UI; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 검출기 /// </summary> private StopSignDetector detector; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); using(Image<Bgr, Byte> modelImage = new Image<Bgr, Byte>("stop-sign-model.png")) { using (Image<Bgr, Byte> image = new Image<Bgr, byte>("stop-sign.jpg")) { this.detector = new StopSignDetector(modelImage); ProcessImage(image); } } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 이미지 로드 버튼 클릭시 처리하기 - loadImageButton_Click(sender, e) /// <summary> /// 이미지 로드 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void loadImageButton_Click(object sender, EventArgs e) { DialogResult result = openFileDialog.ShowDialog(); if(result == DialogResult.OK) { Image<Bgr, Byte> image; try { image = new Image<Bgr, byte>(openFileDialog.FileName); } catch { MessageBox.Show("지원하는 파일 포맷이 아닙니다."); return; } ProcessImage(image); } } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 레이블 및 이미지 추가하기 - AddLabelAndImage(startPoint, text, image) /// <summary> /// 레이블 및 이미지 추가하기 /// </summary> /// <param name="startPoint">시작 위치</param> /// <param name="text">텍스트</param> /// <param name="image">이미지</param> private void AddLabelAndImage(ref Point startPoint, string text, IImage image) { Label label = new Label(); this.resultPanel.Controls.Add(label); label.Width = 100; label.Height = 30; label.Location = startPoint; label.Text = text; startPoint.Y += label.Height; ImageBox imageBox = new ImageBox(); this.resultPanel.Controls.Add(imageBox); imageBox.ClientSize = image.Size; imageBox.Location = startPoint; imageBox.Image = image; startPoint.Y += imageBox.Height + 10; } #endregion #region 이미지 처리하기 - ProcessImage(image) /// <summary> /// 이미지 처리하기 /// </summary> /// <param name="image">이미지</param> private void ProcessImage(Image<Bgr, byte> image) { Stopwatch stopwatch = Stopwatch.StartNew(); List<Image<Gray, Byte>> imageList = new List<Image<Gray, byte>>(); List<Rectangle> rectangleList = new List<Rectangle>(); this.detector.DetectStopSign(image, imageList, rectangleList); stopwatch.Stop(); this.messageLabel.Text = String.Format("STOP 표지판 검출 시간 : {0} 밀리초", stopwatch.Elapsed.TotalMilliseconds); this.resultPanel.Controls.Clear(); Point startPoint = new Point(10, 10); for(int i = 0; i < imageList.Count; i++) { Rectangle rectangle = rectangleList[i]; AddLabelAndImage ( ref startPoint, string.Format ( "STOP 표지판 [{0}, {1}]", rectangle.Location.Y + rectangle.Width / 2, rectangle.Location.Y + rectangle.Height / 2 ), imageList[i] ); image.Draw(rectangle, new Bgr(Color.Aquamarine), 2); } this.imageBox.Image = image; } #endregion } } |