■ 자동차 번호판을 인식하는 방법을 보여준다.
▶ LicensePlateDetector.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 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 |
using System; using System.Collections.Generic; using System.Drawing; using System.Text; using Emgu.CV; using Emgu.CV.CvEnum; using Emgu.CV.OCR; using Emgu.CV.Structure; using Emgu.Util; namespace TestProject { /// <summary> /// 자동차 번호판 검출기 /// </summary> public class LicensePlateDetector : DisposableObject { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// OCR /// </summary> private Tesseract ocr; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - LicensePlateDetector(dataPath) /// <summary> /// 생성자 /// </summary> /// <param name="dataPath">데이터 경로</param> public LicensePlateDetector(string dataPath) { this.ocr = new Tesseract(dataPath, "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED); this.ocr.SetVariable("tessedit_char_whitelist", "ABCDEFGHIJKLMNOPQRSTUVWXYZ-1234567890"); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 자동차 번호판 검출하기 - DetectLicensePlate(sourceImage, licensePlateImageList, filteredLicensePlateImageList, detectedLicensePlateRectangleList) /// <summary> /// 자동차 번호판 검출하기 /// </summary> /// <param name="sourceImage">소스 이미지</param> /// <param name="licensePlateImageList">자동차 번호판 이미지 리스트</param> /// <param name="filteredLicensePlateImageList">필터 자동차 번호판 이미지 리스트</param> /// <param name="detectedLicensePlateRectangleList">검출 자동차 번호판 사각형 리스트</param> /// <returns>자동차 번호 리스트</returns> public List<string> DetectLicensePlate ( Image<Bgr, byte> sourceImage, List<Image<Gray, Byte>> licensePlateImageList, List<Image<Gray, Byte>> filteredLicensePlateImageList, List<MCvBox2D> detectedLicensePlateRectangleList) { List<string> licenseList = new List<String>(); using(Image<Gray, byte> grayscaleImage = sourceImage.Convert<Gray, Byte>()) { using(Image<Gray, Byte> cannyImage = new Image<Gray, byte>(grayscaleImage.Size)) { using(MemStorage storage = new MemStorage()) { CvInvoke.cvCanny(grayscaleImage, cannyImage, 100, 50, 3); Contour<Point> pointContour = cannyImage.FindContours ( CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE, RETR_TYPE.CV_RETR_TREE, storage ); FindLicensePlate ( pointContour, grayscaleImage, cannyImage, licensePlateImageList, filteredLicensePlateImageList, detectedLicensePlateRectangleList, licenseList ); } } } return licenseList; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Public #region 흰색 픽셀 마스크 구하기 - GetWhitePixelMask(image) /// <summary> /// 흰색 픽셀 마스크 구하기 /// </summary> /// <param name="image">이미지</param> /// <returns>흰색 픽셀 마스크</returns> /// <remarks> /// 흰색 픽셀은 채도가 40보다 작거나 200보다 큰 경우에 해당한다. /// </remarks> private static Image<Gray, Byte> GetWhitePixelMask(Image<Bgr, byte> image) { using(Image<Hsv, Byte> hsvImage = image.Convert<Hsv, Byte>()) { Image<Gray, Byte>[] grayscaleImageArray = hsvImage.Split(); try { grayscaleImageArray[1]._ThresholdBinaryInv(new Gray(40), new Gray(255)); grayscaleImageArray[2]._ThresholdBinary(new Gray(200), new Gray(255)); CvInvoke.cvAnd(grayscaleImageArray[1], grayscaleImageArray[2], grayscaleImageArray[0], IntPtr.Zero); } finally { grayscaleImageArray[1].Dispose(); grayscaleImageArray[2].Dispose(); } return grayscaleImageArray[0]; } } #endregion #region 자식 카운트 구하기 - GetChildCount(contour) /// <summary> /// 자식 카운트 구하기 /// </summary> /// <param name="contour">윤곽</param> /// <returns>자식 카운트</returns> private static int GetChildCount(Contour<Point> contour) { Contour<Point> childContour = contour.VNext; if(childContour == null) { return 0; } int count = 0; while(childContour != null) { count++; childContour = childContour.HNext; } return count; } #endregion #region 자동차 번호판 찾기 - FindLicensePlate(pointContour, grayscaleImage, cannyImage, licensePlateImageList, filteredLicensePlateImageList, detectedLicensePlateRectangleList, licenseList) /// <summary> /// 자동차 번호판 찾기 /// </summary> /// <param name="pointContour">포인트 윤곽</param> /// <param name="grayscaleImage">회색조 이미지</param> /// <param name="cannyImage">캐니 이미지</param> /// <param name="licensePlateImageList">자동차 번호판 이미지 리스트</param> /// <param name="filteredLicensePlateImageList">필터 자동차 번호판 이미지 리스트</param> /// <param name="detectedLicensePlateRectangleList">검출 자동차 번호판 사각형 리스트</param> /// <param name="licenseList">자동차 번호 리스트</param> private void FindLicensePlate ( Contour<Point> pointContour, Image<Gray, Byte> grayscaleImage, Image<Gray, Byte> cannyImage, List<Image<Gray, Byte>> licensePlateImageList, List<Image<Gray, Byte>> filteredLicensePlateImageList, List<MCvBox2D> detectedLicensePlateRectangleList, List<String> licenseList ) { for(; pointContour != null; pointContour = pointContour.HNext) { int childCount = GetChildCount(pointContour); if(childCount == 0) { continue; } if(pointContour.Area > 400) { if(childCount < 3) { // 윤곽선에 자식 윤곽선이 3개 보다 작은 경우는 자동차 번호판이 아니디. // (자동차 번호판에 문자가 3자 이상 있다고 가정한다) // 그러나 윤곽선의 자식 윤곽선을 검색해 그 중 하나가 자동차 번호판인지 확인해야 한다. FindLicensePlate ( pointContour.VNext, grayscaleImage, cannyImage, licensePlateImageList, filteredLicensePlateImageList, detectedLicensePlateRectangleList, licenseList ); continue; } MCvBox2D rectangle = pointContour.GetMinAreaRect(); if(rectangle.angle < -45.0) { float temporaryWidth = rectangle.size.Width; rectangle.size.Width = rectangle.size.Height; rectangle.size.Height = temporaryWidth; rectangle.angle += 90.0f; } else if(rectangle.angle > 45.0) { float temporaryWidth = rectangle.size.Width; rectangle.size.Width = rectangle.size.Height; rectangle.size.Height = temporaryWidth; rectangle.angle -= 90.0f; } double ratio = (double)rectangle.size.Width / rectangle.size.Height; if(!(3.0 < ratio && ratio < 10.0)) { Contour<Point> childContour = pointContour.VNext; if(childContour != null) { FindLicensePlate ( childContour, grayscaleImage, cannyImage, licensePlateImageList, filteredLicensePlateImageList, detectedLicensePlateRectangleList, licenseList ); } continue; } using(Image<Gray, Byte> temporaryImage1 = grayscaleImage.Copy(rectangle)) { using(Image<Gray, Byte> temporaryImage2 = temporaryImage1.Resize(240, 180, INTER.CV_INTER_CUBIC, true)) { int edgePixelSize = 2; temporaryImage2.ROI = new Rectangle ( new Point(edgePixelSize, edgePixelSize), temporaryImage2.Size - new Size(2 * edgePixelSize, 2 * edgePixelSize) ); Image<Gray, Byte> plateImage = temporaryImage2.Copy(); Image<Gray, Byte> filteredPlateImage = FilterLicensePlateImage(plateImage); Tesseract.Charactor[] charactorArray; StringBuilder stringBuilder = new StringBuilder(); using(Image<Gray, Byte> temporaryImage3 = filteredPlateImage.Clone()) { this.ocr.Recognize(temporaryImage3); charactorArray = this.ocr.GetCharactors(); if(charactorArray.Length == 0) { continue; } for(int i = 0; i < charactorArray.Length; i++) { stringBuilder.Append(charactorArray[i].Text); } } licenseList.Add(stringBuilder.ToString()); licensePlateImageList.Add(plateImage); filteredLicensePlateImageList.Add(filteredPlateImage); detectedLicensePlateRectangleList.Add(rectangle); } } } } } #endregion #region 자동차 번호판 이미지 필터하기 - FilterLicensePlateImage(sourceImage) /// <summary> /// 자동차 번호판 이미지 필터하기 /// </summary> /// <param name="sourceImage">소스 이미지</param> /// <returns>필터 이미지</returns> private static Image<Gray, Byte> FilterLicensePlateImage(Image<Gray, Byte> sourceImage) { Image<Gray, Byte> threshImage = sourceImage.ThresholdBinaryInv(new Gray(120), new Gray(255)); using(Image<Gray, Byte> maskImage = new Image<Gray, byte>(sourceImage.Size)) { using(Image<Gray, Byte> cannyImage = sourceImage.Canny(100, 50)) { using(MemStorage storage = new MemStorage()) { maskImage.SetValue(255.0); for(Contour<Point> pointContour = cannyImage.FindContours(CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE, RETR_TYPE.CV_RETR_EXTERNAL, storage); pointContour != null; pointContour = pointContour.HNext) { Rectangle rectangle = pointContour.BoundingRectangle; if(rectangle.Height > (sourceImage.Height >> 1)) { rectangle.X -= 1; rectangle.Y -= 1; rectangle.Width += 2; rectangle.Height += 2; rectangle.Intersect(sourceImage.ROI); maskImage.Draw(rectangle, new Gray(0.0), -1); } } threshImage.SetValue(0, maskImage); } } } threshImage._Erode(1); threshImage._Dilate(1); return threshImage; } #endregion #region 객체 리소스 해제하기 - DisposeObject() /// <summary> /// 객체 리소스 해제하기 /// </summary> protected override void DisposeObject() { this.ocr.Dispose(); } #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 |
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 LicensePlateDetector licensePlateDetector; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); this.filePathButton.Click += filePathButton_Click; this.licensePlateDetector = new LicensePlateDetector(""); ProcessImage(new Image<Bgr, byte>("LicensePlate.jpg")); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #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) { Image<Bgr, Byte> image; try { image = new Image<Bgr, byte>(this.openFileDialog.FileName); } catch { MessageBox.Show(string.Format("무효한 파일 : {0}", this.openFileDialog.FileName)); return; } ProcessImage(image); } } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 레이블/이미지 추가하기 - AddLabelAndImage(startPoint, labelText, image) /// <summary> /// 레이블/이미지 추가하기 /// </summary> /// <param name="startPoint">시작 위치</param> /// <param name="labelText">레이블 텍스트</param> /// <param name="image">이미지</param> private void AddLabelAndImage(ref Point startPoint, string labelText, IImage image) { Label label = new Label(); this.resultPanel.Controls.Add(label); label.Width = 200; label.Height = 30; label.Location = startPoint; label.Text = labelText; 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>> licensePlateImageList = new List<Image<Gray, byte>>(); List<Image<Gray, Byte>> filteredLicensePlateImageList = new List<Image<Gray, byte>>(); List<MCvBox2D> licenseRectangleList = new List<MCvBox2D>(); List<string> licensePlateArray = this.licensePlateDetector.DetectLicensePlate ( image, licensePlateImageList, filteredLicensePlateImageList, licenseRectangleList ); stopwatch.Stop(); this.messageLabel.Text = string.Format("자동차 번호판 인식 시간 : {0} 밀리초", stopwatch.Elapsed.TotalMilliseconds); this.resultPanel.Controls.Clear(); Point startPoint = new Point(10, 10); for(int i = 0; i < licensePlateArray.Count; i++) { AddLabelAndImage ( ref startPoint, string.Format("자동차 번호 : {0}", licensePlateArray[i]), licensePlateImageList[i].ConcateVertical(filteredLicensePlateImageList[i]) ); image.Draw(licenseRectangleList[i], new Bgr(Color.Red), 2); } this.imageBox.Image = image; } #endregion } } |