■ 텐서플로우를 사용해 물체를 인식하는 방법을 보여준다.
▶ 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 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 |
using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; using AForge.Video.DirectShow; using TensorFlow; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 타이머 /// </summary> private Timer timer = null; /// <summary> /// 필터 정보 컬렉션 /// </summary> private FilterInfoCollection filterInfoCollection = null; /// <summary> /// 모델 배열 /// </summary> private byte[] modelArray; /// <summary> /// 레이블 배열 /// </summary> private string[] labelArray = null; /// <summary> /// 텐서플로우 세션 /// </summary> private TFSession session = null; /// <summary> /// 텐서플로우 그래프 /// </summary> private TFGraph graph = null; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); #region 타이머를 설정한다. this.timer = new Timer(); this.timer.Interval = 1000; #endregion #region 이벤트를 설정한다. Load += Form_Load; FormClosing += Form_FormClosing; this.startButton.Click += startButton_Click; this.timer.Tick += timer_Tick; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 폼 로드시 처리하기 - Form_Load(sender, e) /// <summary> /// 폼 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_Load(object sender, EventArgs e) { #region 카메라 장치 콤보 박스를 설정한다. this.filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice); for(int i = 0; i < this.filterInfoCollection.Count; i++) { this.cameraDeviceComboBox.Items.Add(this.filterInfoCollection[i].Name); } if(this.cameraDeviceComboBox.Items.Count > 0) { this.cameraDeviceComboBox.SelectedIndex = 0; } #endregion #region 시작 버튼을 설정한다. this.startButton.Enabled = (this.cameraDeviceComboBox.Items.Count > 0); #endregion #region 모델 배열을 설정한다. this.modelArray = File.ReadAllBytes("DATA\\tensorflow_inception_graph.pb"); #endregion #region 레이블 배열을 설정한다. this.labelArray = File.ReadAllLines("DATA\\imagenet_comp_graph_label_strings.txt"); #endregion this.graph = new TFGraph(); this.session = new TFSession(graph); this.graph.Import(this.modelArray, ""); } #endregion #region 폼 닫을 경우 처리하기 - Form_FormClosing(sender, e) /// <summary> /// 폼 닫을 경우 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_FormClosing(object sender, FormClosingEventArgs e) { this.timer.Stop(); StopCameraCaoture(); } #endregion #region 시작 버튼 클릭시 처리하기 - startButton_Click(sender, e) /// <summary> /// 시작 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void startButton_Click(object sender, EventArgs e) { if(this.startButton.Text == "시작") { this.startButton.Text = "중지"; StartCameraCapture(); this.timer.Start(); } else { this.timer.Stop(); StopCameraCaoture(); this.startButton.Text = "시작"; } } #endregion #region 타이머 틱 처리하기 - timer_Tick(sender, e) /// <summary> /// 타이머 틱 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void timer_Tick(object sender, EventArgs e) { Bitmap bitmap = this.videoSourcePlayer.GetCurrentVideoFrame(); if(bitmap == null) { return; } MemoryStream memoryStream = new MemoryStream(); bitmap.Save(memoryStream, ImageFormat.Jpeg); TFTensor tensor = GetTensor(memoryStream.GetBuffer()); TFSession.Runner runner = this.session.GetRunner(); runner.AddInput(graph["input"][0], tensor).Fetch(graph["output"][0]); TFTensor[] outputTensorArray = runner.Run(); TFTensor outputTensor = outputTensorArray[0]; long[] shapeArray = outputTensor.Shape; if(outputTensor.NumDims != 2 || shapeArray[0] != 1) { string shapeString = string.Empty; foreach(long shape in shapeArray) { shapeString += $"{shape} "; } shapeString = shapeString.Trim(); Console.WriteLine($"에러 : [1 N] 차원 텐서의 생성을 기대했는데(여기서 N은 라벨의 개수), [{shapeString}] 차원 텐서를 생성했습니다."); Environment.Exit(1); } bool jagged = true; int bestIndex = 0; float best = 0; if(jagged) { float[] probabilityArray = ((float[][])outputTensor.GetValue(jagged : true))[0]; for(int i = 0; i < probabilityArray.Length; i++) { if(probabilityArray[i] > best) { bestIndex = i; best = probabilityArray[i]; } } } else { float[,] valueArray = (float[,])outputTensor.GetValue(jagged : false); for(int i = 0; i < valueArray.GetLength(1); i++) { if(valueArray[0, i] > best) { bestIndex = i; best = valueArray[0, i]; } } } this.informationLabel.Text = $"판정 : [{bestIndex}] {best * 100.0}% {this.labelArray[bestIndex]}"; Console.WriteLine($"판정 : [{bestIndex}] {best * 100.0}% {this.labelArray[bestIndex]}"); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 카메라 캡처 시작하기 - StartCameraCapture() /// <summary> /// 카메라 캡처 시작하기 /// </summary> private void StartCameraCapture() { FilterInfo filterInfo; filterInfo = this.filterInfoCollection[this.cameraDeviceComboBox.SelectedIndex]; VideoCaptureDevice videoCaptureDevice = new VideoCaptureDevice(filterInfo.MonikerString); this.videoSourcePlayer.VideoSource = videoCaptureDevice; this.videoSourcePlayer.AutoSizeControl = true; this.videoSourcePlayer.Start(); } #endregion #region 카메라 캡처 중단하기 - StopCameraCaoture() /// <summary> /// 카메라 캡처 중단하기 /// </summary> private void StopCameraCaoture() { this.videoSourcePlayer.SignalToStop(); this.videoSourcePlayer.WaitForStop(); } #endregion #region 값 설정하기 - SetValue(graph, input, output) /// <summary> /// 값 설정하기 /// </summary> /// <param name="graph">그래프</param> /// <param name="input">입력</param> /// <param name="output">출력</param> private void SetValue(out TFGraph graph, out TFOutput input, out TFOutput output) { const int IMAGE_WIDTH = 224; const int IMAGE_HEIGHT = 224; const float MEAN = 117; const float SCALE = 1; graph = new TFGraph(); input = graph.Placeholder(TFDataType.String); output = graph.Div ( x : graph.Sub ( x : graph.ResizeBilinear ( images : graph.ExpandDims ( input : graph.Cast ( graph.DecodeJpeg(contents : input, channels : 3), DstT : TFDataType.Float ), dim : graph.Const(0, "make_batch") ), size : graph.Const(new int[] { IMAGE_WIDTH, IMAGE_HEIGHT }, "size")), y : graph.Const(MEAN, "mean") ), y : graph.Const(SCALE, "scale") ); } #endregion #region 텐서 구하기 - GetTensor(sourceArray) /// <summary> /// 텐서 구하기 /// </summary> /// <param name="sourceArray">소스 배열</param> /// <returns>텐서</returns> private TFTensor GetTensor(byte[] sourceArray) { TFTensor tensor = TFTensor.CreateString(sourceArray); TFGraph graph; TFOutput input; TFOutput output; SetValue(out graph, out input, out output); using(TFSession session = new TFSession(graph)) { TFTensor[] normalizedTensorArray = session.Run ( inputs : new[] { input }, inputValues : new[] { tensor }, outputs : new[] { output } ); return normalizedTensorArray[0]; } } #endregion } } |
※ 닷넷 프레임워크 4.7.1 버전을 사용해야 한다.
※ 프로젝트 속성의 빌드 탭에서 “32비트 기본 사용”을 체크 해제해야 한다.