프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

markus / Markus.ImageComparer / ImageCompareBase.cs @ master

이력 | 보기 | 이력해설 | 다운로드 (13.8 KB)

1 2007ecaa taeseongkim
using OpenCvSharp;
2
using System;
3 a860bafc taeseongkim
using System.Collections.Concurrent;
4 2007ecaa taeseongkim
using System.Collections.Generic;
5
using System.Drawing;
6
using System.Drawing.Imaging;
7
using System.IO;
8
using System.Linq;
9
using System.Net;
10
using System.Runtime.InteropServices;
11
using System.Text;
12 0c575433 taeseongkim
using System.Threading;
13 2007ecaa taeseongkim
using System.Threading.Tasks;
14 a860bafc taeseongkim
using System.Windows.Media.Imaging;
15 2007ecaa taeseongkim
using Point = System.Drawing.Point;
16
using Size = System.Drawing.Size;
17
18
namespace Markus.Image
19
{
20
    public class ImageCompareBase : IDisposable
21
    {
22
        double contoursLongCount = 0;
23 a860bafc taeseongkim
        int ComparisonCount = 0;
24 2007ecaa taeseongkim
        public CompareProgress Progress = new CompareProgress();
25
26
        private void SetStatus(string message,double percentage,CompareStatus status)
27
        {
28 a860bafc taeseongkim
            //System.Diagnostics.Debug.WriteLine(percentage);
29 2007ecaa taeseongkim
30
            Progress.Message = message;
31
            Progress.Percentage = percentage;
32
            Progress.Status = status;
33
        }
34
35
        /// <summary>
36
        /// Originalbitmap에서 TargatBitmap과 비교하여 틀린 부분의 데이터를 Emgu.CV.TDepth형식으로 반환한다.
37
        /// </summary>
38
        /// <param name="Originalbitmap">원본 이미지</param>
39
        /// <param name="TargatBitmap">비교대상 이미지</param>
40
        /// <returns>Emgu.CV.TDepth형식의 byte[,,]</returns>
41 0c575433 taeseongkim
        protected Mat MathchesImageData(System.Drawing.Bitmap Originalbitmap, System.Drawing.Bitmap TargatBitmap,Size resultSize)
42 2007ecaa taeseongkim
        {
43
            Mat result = new Mat();
44
45
            try
46
            {
47
                SetStatus("Image Load", 0, CompareStatus.Loading);
48 253c9730 taeseongkim
                OpenCvSharp.Size rSize = new OpenCvSharp.Size(resultSize.Width, resultSize.Height);
49 2007ecaa taeseongkim
50 253c9730 taeseongkim
                //Originalbitmap = ChangeBitmapFormatAndSize(Originalbitmap, resultSize, PixelFormat.Format24bppRgb);
51
                //TargatBitmap = ChangeBitmapFormatAndSize(TargatBitmap, resultSize, PixelFormat.Format24bppRgb);
52 2007ecaa taeseongkim
53
                // 원본이미지의 크키와 Format24bppRgb로 타켓 이미지를 변경
54
                // 크기가 틀린 경우 비교시 바이트배열 오류 발생
55 fc5ed14c taeseongkim
                using (Mat OriginalImageData = OpenCvSharp.Extensions.BitmapConverter.ToMat(Originalbitmap))
56 2007ecaa taeseongkim
                {
57 fc5ed14c taeseongkim
                    using (Mat TargatImageData = OpenCvSharp.Extensions.BitmapConverter.ToMat(TargatBitmap))
58
                    {
59 253c9730 taeseongkim
                        if (OriginalImageData.Size() != rSize)
60 fc5ed14c taeseongkim
                        {
61 253c9730 taeseongkim
                            Cv2.Resize(OriginalImageData, OriginalImageData, rSize);
62
                        }
63
64
                        if (TargatImageData.Size() != rSize)
65
                        {
66
                            Cv2.Resize(TargatImageData, TargatImageData, rSize);
67 fc5ed14c taeseongkim
                        }
68
69
                        Cv2.CvtColor(OriginalImageData, OriginalImageData, ColorConversionCodes.BGR2GRAY);
70
                        Cv2.CvtColor(TargatImageData, TargatImageData, ColorConversionCodes.BGR2GRAY);
71
72
                        using (Mat outputData = new Mat(new OpenCvSharp.Size(resultSize.Width, resultSize.Height), MatType.CV_8UC1))
73
                        {
74
                            Cv2.Absdiff(OriginalImageData, TargatImageData, outputData);
75
                            // 틀린부분을 반환
76
                            Cv2.BitwiseNot(outputData, result);
77
                        }
78
                    }
79 2007ecaa taeseongkim
                }
80
            }
81
            catch (Exception ex)
82
            {
83
                throw ex;
84
            }
85
            finally
86
            {
87
            }
88
            
89
            return result;
90
        }
91
92 253c9730 taeseongkim
        protected Mat MathchesImageData(Mat OriginalImageData, Mat TargatImageData, Size resultSize)
93
        {
94
            Mat result = new Mat();
95
96
            try
97
            {
98
                SetStatus("Image Load", 0, CompareStatus.Loading);
99
                OpenCvSharp.Size rSize = new OpenCvSharp.Size(resultSize.Width, resultSize.Height);
100
101
                // 크기가 틀린 경우 비교시 바이트배열 오류 발생
102
         
103
                if (OriginalImageData.Size() != rSize)
104
                {
105
                    Cv2.Resize(OriginalImageData, OriginalImageData, rSize);
106
                }
107
108
                if (TargatImageData.Size() != rSize)
109
                {
110
                    Cv2.Resize(TargatImageData, TargatImageData, rSize);
111
                }
112
113
                Cv2.CvtColor(OriginalImageData, OriginalImageData, ColorConversionCodes.BGR2GRAY);
114
                Cv2.CvtColor(TargatImageData, TargatImageData, ColorConversionCodes.BGR2GRAY);
115
116
                using (Mat outputData = new Mat(new OpenCvSharp.Size(resultSize.Width, resultSize.Height), MatType.CV_8UC1))
117
                {
118
                    Cv2.Absdiff(OriginalImageData, TargatImageData, outputData);
119
                    // 틀린부분을 반환
120
                    Cv2.BitwiseNot(outputData, result);
121
                }
122
            }
123
            catch (Exception ex)
124
            {
125
                throw ex;
126
            }
127
            finally
128
            {
129
            }
130
131
            return result;
132
        }
133
134 2007ecaa taeseongkim
135
        /// <summary>
136
        /// Image<TColor, TDepth>의 틀린 부분을 Rect로 반환
137
        /// </summary>
138
        /// <param name="data"></param>
139
        /// <param name="block"></param>
140
        /// <returns></returns>
141
        protected List<System.Windows.Rect> GetMatchPixels(Mat data, Size block)
142
        {
143
            SetStatus("Detection", 0, CompareStatus.Detection);
144
145
            int width = data.Cols;
146
            int height = data.Rows;
147
148
            List<System.Windows.Rect> results = new List<System.Windows.Rect>();
149
150
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
151
            stopwatch.Start();
152
153 fc5ed14c taeseongkim
            //Mat outputMat = new Mat(data.Size(), MatType.CV_8UC1);
154 2007ecaa taeseongkim
155
            HierarchyIndex[] hierarchy;
156
            OpenCvSharp.Point[][] contours;
157
158
            OpenCvSharp.Point testpoint = new OpenCvSharp.Point();
159
           
160 a860bafc taeseongkim
            Cv2.Threshold(data, data, 50, 255,ThresholdTypes.BinaryInv);
161 2007ecaa taeseongkim
162 a860bafc taeseongkim
            Cv2.FindContours(data, out contours, out hierarchy,RetrievalModes.List,ContourApproximationModes.ApproxSimple, testpoint);
163 2007ecaa taeseongkim
164
            SetStatus("Comparison", 0, CompareStatus.Comparison);
165
            contoursLongCount = contours.Sum(x => x.Count());
166
167 0c575433 taeseongkim
            //var rects = contours.AsParallel()
168
            //                    .Select(points => GetRectList(points, block))
169
            //                    .SelectMany(x => x);
170
171 fc5ed14c taeseongkim
            var rects = contours.SelectMany(points => GetRectList(points, block));
172 2007ecaa taeseongkim
173
            results.AddRange(rects);
174
             
175
            return results;
176
        }
177 16231f58 taeseongkim
        protected System.Drawing.Bitmap GetContoursImage(Mat data, Size resultSize, Color RectColor)
178
        {
179
            System.Drawing.Bitmap result = null;
180
181
            try
182
            {
183
                Mat transparentImage = new Mat(new OpenCvSharp.Size(resultSize.Width, resultSize.Height), MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
184
185
                // 컨투어를 찾기 위한 변수 선언
186
                HierarchyIndex[] hierarchy;
187
                OpenCvSharp.Point[][] contours;
188
                OpenCvSharp.Point testpoint = new OpenCvSharp.Point();
189 a860bafc taeseongkim
190 16231f58 taeseongkim
                Cv2.Threshold(data, data, 100, 255, ThresholdTypes.BinaryInv);
191
                // 이진화된 이미지에서 컨투어 찾기
192
                Cv2.FindContours(data, out contours, out hierarchy, RetrievalModes.List, ContourApproximationModes.ApproxNone, testpoint);
193
194
195
                // Scalar(B,G,R,A)
196
                // 컨투어 그리기
197
                Cv2.DrawContours(transparentImage, contours, -1, new Scalar(RectColor.B, RectColor.G, RectColor.R, RectColor.A), 10);
198
199
                // Mat을 Bitmap으로 변환
200
                result = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(transparentImage);
201
            }
202
            catch (Exception ex)
203
            {
204
                throw new Exception("GetContoursImage Error.", ex);
205
            }
206
            finally
207
            {
208
209
            }
210
211
            return result;
212
        }
213 fc5ed14c taeseongkim
        private List<System.Windows.Rect> GetRectListAsParallel(OpenCvSharp.Point[] points, Size block)
214 0c575433 taeseongkim
        {
215
            List<System.Windows.Rect> result = new List<System.Windows.Rect>();
216 a860bafc taeseongkim
            ConcurrentBag<System.Windows.Rect> rectBag = new ConcurrentBag<System.Windows.Rect>();
217 0c575433 taeseongkim
218
            Parallel.For(0, points.Length, i =>
219
            {
220 fc5ed14c taeseongkim
                if (i >= points.Length) return; // 배열 길이 확인
221
222 0c575433 taeseongkim
                var rect = new System.Windows.Rect
223
                {
224
                    X = points[i].X - block.Width / 2,
225
                    Y = points[i].Y - block.Height / 2,
226
                    Width = block.Width,
227
                    Height = block.Height
228
                };
229
230 a860bafc taeseongkim
                if (!rectBag.Any(r => r.IntersectsWith(rect)))
231 0c575433 taeseongkim
                {
232 a860bafc taeseongkim
                    rectBag.Add(rect);
233
                    result.Add(rect);
234 0c575433 taeseongkim
                }
235
236 a860bafc taeseongkim
                Interlocked.Increment(ref ComparisonCount);
237 0c575433 taeseongkim
238 a860bafc taeseongkim
                SetStatus("Comparison", (double)ComparisonCount / (double)contoursLongCount * 100, CompareStatus.Comparison);
239 0c575433 taeseongkim
            });
240
241
            return result;
242
        }
243 2007ecaa taeseongkim
244 a860bafc taeseongkim
        protected System.Drawing.Bitmap ChangeBitmapFormatAndSize(System.Drawing.Bitmap bitmap, Size newSize, PixelFormat pixelFormat)
245
        {
246
            Bitmap result = bitmap;
247
248
            if (pixelFormat != bitmap.PixelFormat)
249
            {
250
                Point originPoint = new Point(0, 0);
251
                Rectangle rect = new Rectangle(originPoint, bitmap.Size);
252
                result = bitmap.Clone(rect, pixelFormat);
253
            }
254
255
            if (bitmap.Size != newSize)
256
            {
257
                result = new Bitmap(newSize.Width, newSize.Height);
258
259
                using (Graphics g = Graphics.FromImage(result))
260
                {
261
                    g.DrawImage(bitmap, 0, 0, newSize.Width, newSize.Height);
262
                    g.Dispose();
263
                }
264
            }
265
266
            return result;
267
        }
268
269
270 fc5ed14c taeseongkim
        private List<System.Windows.Rect> GetRectList(OpenCvSharp.Point[] points,Size block)
271 2007ecaa taeseongkim
        {
272
            List<System.Windows.Rect> result = new List<System.Windows.Rect>();
273
274
            for (int i = 0; i < points.Count(); i++)
275
            {
276
                var rect = new System.Windows.Rect
277
                {
278
                    X = points[i].X - block.Width / 2,
279
                    Y = points[i].Y - block.Height / 2,
280
                    Width = block.Width,
281
                    Height = block.Height
282
                };
283
284
                if (result.Count(r => r.IntersectsWith(rect)) == 0)
285
                {
286
                    result.Add(rect);
287
                }
288
289
                ComparisonCount++;
290
291
                SetStatus("Comparison", ComparisonCount/contoursLongCount*100, CompareStatus.Comparison);
292
            }
293
294
            return result;
295
        }
296
297
        /// <summary>
298
        /// Image<TColor, TDepth>의 틀린 부분을 Rect로 반환
299
        /// </summary>
300
        /// <param name="data"></param>
301
        /// <param name="block"></param>
302
        /// <returns></returns>
303
        protected async Task<List<System.Windows.Rect>> GetMatchPixelsAsnc(Mat data, Size block)
304
        {
305
            return await Task.Factory.StartNew<List<System.Windows.Rect>>(() =>
306
            {
307
                return GetMatchPixels(data, block);
308
            });
309
        }
310
311
        protected Bitmap LoadPicture(string url)
312
        {
313
            HttpWebRequest wreq;
314
            HttpWebResponse wresp;
315
            Stream mystream;
316
            Bitmap bmp;
317
318
            bmp = null;
319
            mystream = null;
320
            wresp = null;
321
            try
322
            {
323
                wreq = (HttpWebRequest)WebRequest.Create(url);
324
                wreq.AllowWriteStreamBuffering = true;
325
326
                wresp = (HttpWebResponse)wreq.GetResponse();
327
328
                if ((mystream = wresp.GetResponseStream()) != null)
329
                    bmp = new Bitmap(mystream);
330
            }
331
            finally
332
            {
333
                if (mystream != null)
334
                {
335
                    mystream.Close();
336
                    mystream.Dispose();
337
                }
338
339
                if (wresp != null)
340
                {
341
                    wresp.Close();
342
                    wresp.Dispose();
343
                }
344
            }
345
            return (bmp);
346
        }
347
348
        #region  IDisposable Support 
349
350
        private bool disposedValue = false;
351
352
        // 중복 호출을 검색하려면 
353
        protected virtual void Dispose(bool disposing)
354
        {
355
            if (!disposedValue)
356
            {
357
                if (disposing)
358
                {
359
                    // TODO: 관리되는 상태(관리되는 개체)를 삭제합니다. 
360
                }
361
                // TODO: 관리되지 않는 리소스(관리되지 않는 개체)를 해제하고 아래의 종료자를 재정의합니다. 
362
                // TODO: 큰 필드를 null로 설정합니다. 
363
                disposedValue = true;
364
            }
365
        }
366
367
        // TODO: 위의 Dispose(bool disposing)에 관리되지 않는 리소스를 해제하는 코드가 포함되어 있는 경우에만 종료자를 재정의합니다.
368
        // 
369
        //~DisposeClass()
370
       // {
371
            // // 이 코드를 변경하지 마세요. 위의 Dispose(bool disposing)에 정리 코드를 입력하세요. 
372
            // Dispose(false); // 
373
       // } 
374
375
        // 삭제 가능한 패턴을 올바르게 구현하기 위해 추가된 코드입니다. 
376
        public void Dispose()
377
        {
378
            // 이 코드를 변경하지 마세요. 위의 Dispose(bool disposing)에 정리 코드를 입력하세요. 
379
            Dispose(true);
380
381
            // TODO: 위의 종료자가 재정의된 경우 다음 코드 줄의 주석 처리를 제거합니다. 
382
            //  GC.SuppressFinalize(this);
383
            GC.Collect();
384
            GC.SuppressFinalize(this);
385
            GC.Collect();
386
        } 
387
        #endregion
388
    }
389
}
클립보드 이미지 추가 (최대 크기: 500 MB)