-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.xml
3926 lines (2662 loc) · 264 KB
/
index.xml
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Medipixel</title>
<link>/</link>
<description>Recent content on Medipixel</description>
<generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator>
<language>en-us</language>
<lastBuildDate>Tue, 30 Jun 2020 10:20:00 +0900</lastBuildDate>
<atom:link href="/index.xml" rel="self" type="application/rss+xml" />
<item>
<title>[Tutorial] Multi-scale</title>
<link>/post/2020-06-30-multi_scale/</link>
<pubDate>Tue, 30 Jun 2020 10:20:00 +0900</pubDate>
<guid>/post/2020-06-30-multi_scale/</guid>
<description>
<h1 id="multi-scale">Multi-scale</h1>
<hr />
<ul>
<li>이번 장 에서는 다해상도(Multi-scale)에 대한 개념과 전통적인 Computer Vision에서 Multi-scale Image 처리를 하는 방법을 알아보겠습니다.</li>
<li>일반적으로 하나의 해상도에 최적화된 Computer Vision Model보다 다해상도를 처리할 수 있는 Computer Vision Model이 더 좋은 성능을 낼 가능성이 높기 때문에 Multi-scale 문제는 꼭 해결해야만 하는 문제입니다.</li>
<li>여기에서는 가장 단순하고 오래된 기법인 Image Pyramid기법만을 알아보겠습니다. 단순하게 요약하면 피라미드로 쌓은 것 같이 다양한 크기의 Image를 많이 준비하는 방법 입니다.
<ul>
<li><a href="#imagenbspPyramid">Image pyramid</a></li>
</ul></li>
</ul>
<h3 id="import-libraries">Import Libraries</h3>
<pre><code class="language-python">import os
import sys
import math
from platform import python_version
import cv2
import matplotlib.pyplot as plt
import matplotlib
import imutils
import numpy as np
print(f&quot;Python version : {python_version()}&quot;, )
print(f&quot;Opencv version : {cv2.__version__}&quot;, )
</code></pre>
<pre><code>Python version : 3.6.9
Opencv version : 4.1.2
</code></pre>
<h3 id="data-load">Data load</h3>
<pre><code class="language-python">sample_image_path = '../image/'
sample_image = 'kitten.jpg'
img = cv2.imread(os.path.join(sample_image_path, sample_image), cv2.IMREAD_GRAYSCALE)
h, w = img.shape
matplotlib.rcParams['figure.figsize'] = (8.0, 8.0)
</code></pre>
<h2 id="image-nbsp-pyramid">Image&nbsp;Pyramid</h2>
<hr />
<ul>
<li>전통적인 Computer Vision이나 Deep Learning 모두 공통적으로 크기 변화에 취약하다는 단점을 가지고 있습니다.
<ul>
<li>즉, 같은 모델로 더 크거나 작은 Image를 분석할 경우 결과가 전혀 달라질 수 있다는 말 입니다.</li>
</ul></li>
<li>이에 대응하기 위해 하여 Feature추출, 추론 등에서 다양한 해상도의 Image를 사용하는 것이 보통입니다.</li>
<li>Image Pyramid<a href="https://docs.opencv.org/3.4/dc/dff/tutorial_py_pyramids.html" target="_blank">[2]</a>란, Image를 다양한 해상도의 Image로 변환하고 쌓아올려서 마치 피라미드와 같은 형상을 띄도록 준비하는 전처리 기법입니다.</li>
<li>이는 Multi-scale 문제를 해결해야 할 때 자주 쓰이던 기법이며, Deep Learning에서 쓰이는 FPN 등의 방법들이 이 Image Pyramid 기법을 개선하는 과정에서 고안된 것임을 감안할 때, Image Pyramid기법은 Multi-scale 문제 해결의 시작점 이라고 할 수 있습니다.</li>
</ul>
<h3 id="다해상도-처리">다해상도 처리</h3>
<ul>
<li>Image Pyramid에서 결국 관건은 다양한 해상도의 Image를 어떻게 준비할 것이냐 인데, 크기가 작은 Image라면 Upsampling을 해서 더 큰 해상도로 만들어야 하고, 크기가 큰 Image라면 Downsampling을 해서 Image 크기를 줄여야 합니다.</li>
<li>그러나 두 방법 모두 단순히 적용하면 정보량의 변화로 인해 원래 Image보다 다소 부자연스러워 보이게 되는 Aliasing이라는 문제가 발생하게 되는데, 이를 보완하는 방법에 대해 간단히 알아보겠습니다.</li>
</ul>
<h3 id="upsample">Upsample</h3>
<ul>
<li>Upsample에서 발생하는 Aliasing문제는 대부분의 경우 지난 장에서 확인한 Interpolation 방법으로 해결합니다.</li>
<li>생성모델이나 한층 더 높은 정교함을 요구하는 모델의경우 데이터에 맞게 학습된 Filter를 이용하는 Deconvolution 등이 사용되기도 합니다.</li>
</ul>
<h3 id="downsample">Downsample</h3>
<ul>
<li>Downsample의 경우 특정 화소를 선택적으로 제거해야 하므로 문제가 발생합니다.</li>
<li>단순히 짝수번째나 홀수번째 화소를 제거하는 방식을 사용할 경우, 제거되는 화소만큼 그대로 손실이 되기 때문에 Image의 품질이 빠르게 나빠지는 것을 확인할 수 있습니다.</li>
</ul>
<pre><code class="language-python">img_half = cv2.resize(img, (w // 2, h // 2))
img_quard = cv2.resize(img, (w // 4, h // 4))
img_eight = cv2.resize(img, (w // 8, h // 8))
plt.subplot(221)
plt.imshow(img, cmap='gray')
plt.title('Original image')
plt.subplot(222)
plt.imshow(img_half, cmap='gray')
plt.title('1/2 sized')
plt.subplot(223)
plt.imshow(img_quard, cmap='gray')
plt.title('1/4 sized')
plt.subplot(224)
plt.imshow(img_eight, cmap='gray')
plt.title('8/1 sized')
plt.suptitle('Kitten with many size', size=15)
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.5/2019-12-16-multi_scale_10_0.png" />
</figure>
<ul>
<li>이러한 문제를 해결하기 위한 대안은 원본 Image에 Smoothing을 적용한 후 Downsampling을 적용하는 것 입니다. 선택적으로 제거되는 픽셀의 정보를 주변 픽셀들에 조금씩 반영해주는 원리입니다.</li>
<li>아래 예제는 교재에서 사용된 커널 함수로 Smoothing을 적용한 결과입니다.</li>
</ul>
<pre><code class="language-python">kernel = np.array([[0.05, 0.25, 0.4, 0.25, 0.05]])
kernel = np.dot(kernel.T, kernel)
blur_img_half = cv2.resize(cv2.filter2D(img, -1, kernel), (w // 2, h // 2))
blur_img_quard = cv2.resize(
cv2.filter2D(blur_img_half, -1, kernel), (w // 4, h // 4))
blur_img_eight = cv2.resize(
cv2.filter2D(blur_img_quard, -1, kernel), (w // 8, h // 8))
plt.subplot(221)
plt.imshow(img, cmap='gray')
plt.title('Original')
plt.subplot(222)
plt.imshow(blur_img_half, cmap='gray')
plt.title('Blur_half')
plt.subplot(223)
plt.imshow(blur_img_quard, cmap='gray')
plt.title('Blur_quard')
plt.subplot(224)
plt.imshow(blur_img_eight, cmap='gray')
plt.title('Blur_eight')
plt.suptitle('Soft Kitten with many size', size=15)
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.5/2019-12-16-multi_scale_12_0.png" />
</figure>
<h2 id="conclusion">Conclusion</h2>
<hr />
<ul>
<li>Multi-scale Image를 생성할 때 발생하는 문제와 이에 대응하기 위해 필요한 작업들을 살펴보았습니다.</li>
<li>여기에서 Smoothing 작업을 진행할 때, 다양한 커널을 이용할 수 있는데, Image에 따라 목적에 따라 최적의 커널이 따로 존재합니다.
<ul>
<li>이 말은 그때 그때 알맞은 커널을 직접 찾아서 사용해야 한다는 뜻이기도 합니다. 이러한 부분이 전통적인 방식의 Computer Vision이 가지고 있었던 고질적인 약점입니다.</li>
</ul></li>
</ul>
<h2 id="reference">Reference</h2>
<hr />
<ul>
<li>[1] 오일석, &ldquo;다해상도,&rdquo; in 컴퓨터 비전, vol.4, Republic of Korea:한빛아카데미, 2014, pp. 93-96</li>
<li>[2] Accessed: &lsquo;Image Pyramids&rsquo;, opencv official, [Online] Avaliable: <a href="https://docs.opencv.org/3.4/dc/dff/tutorial_py_pyramids.html" target="_blank">https://docs.opencv.org/3.4/dc/dff/tutorial_py_pyramids.html</a></li>
</ul>
</description>
</item>
<item>
<title>[Tutorial] Morphology</title>
<link>/post/2020-06-30-morphology/</link>
<pubDate>Tue, 30 Jun 2020 10:10:00 +0900</pubDate>
<guid>/post/2020-06-30-morphology/</guid>
<description>
<h2 id="morphology">Morphology</h2>
<hr />
<ul>
<li>이번 장 에서는 Morphology Operation<a href="https://en.wikipedia.org/wiki/Mathematical_morphology" target="_blank">[2]</a>에 대하여 알아보겠습니다.
<ul>
<li>Morphology Operation이란, Image의 형태를 조작하는 연산의 종류를 통칭합니다.</li>
<li>적용 대상이 어떤 Image냐에 따라 Binary, Grayscale로 나눌 수 있고, 연산 방식에 따라 Dilation(확산)과 Erosion(침식)으로 나눌 수 있습니다.</li>
<li>두 연산 모두 공통적으로 Source Image Kernel을 통해 Target Image를 생성하는 과정을 갖습니다.</li>
<li>Morphology Operation을 응용하면 Edge Detection이나 Image Denoising 등의 작업을 할 수 있습니다.</li>
</ul></li>
<li>목차는 아래와 같습니다.</li>
<li><a href="#binarynbspmorphology">Binary Morphology</a></li>
<li><a href="#grayscalenbspmorphology">Grayscale Morphology</a></li>
<li><a href="#compositednbspmorphologicalnbspoperations">Composited Morphological Operations</a></li>
</ul>
<h3 id="import-libraries">Import Libraries</h3>
<pre><code class="language-python">import os
import sys
import math
from platform import python_version
import cv2
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
print(&quot;Python version : &quot;, python_version())
print(&quot;Opencv version : &quot;, cv2.__version__)
</code></pre>
<pre><code>Python version : 3.6.9
Opencv version : 4.1.2
</code></pre>
<h3 id="data-load">Data load</h3>
<pre><code class="language-python">sample_image_path = '../image/'
sample_image = 'kitten.jpg'
img = cv2.imread(os.path.join(sample_image_path, sample_image), cv2.IMREAD_GRAYSCALE)
h, w = [int(x) for x in img.shape]
matplotlib.rcParams['figure.figsize'] = (8.0, 8.0)
</code></pre>
<h2 id="binary-nbsp-morphology">Binary&nbsp;Morphology</h2>
<hr />
<ul>
<li>전체 Image가 0 또는 1로 이루어진 Image를 Binary Image라고 합니다. 아래 설명은 모두 Binary Image를 기준으로 하겠습니다.</li>
<li>이러한 Image는 보통 Image 자체로 이용되기보다 RoI(Region of Interest)를 선택하기 위한 Mask로서 이용됩니다.</li>
<li>Binary Image에 Morphology를 적용하면 자잘한 Noise를 제거하는데 도움이 됩니다.</li>
<li>Erosion 연산은 침식이라는 말 뜻이 의미하듯이 1에 해당하는 밝은 영역이 조금씩 줄어드는 모습을 보입니다.
<ul>
<li>RoI 바깥에 1의 값을 갖는 Noise가 발생하는 경우에 Erosion 연산을 통해 Noise를 보정할 수 있습니다.</li>
</ul></li>
<li>Dilation 연산은 팽창이라는 뜻인데, 흰색 영역이 조금 커지는 모습을 보입니다.
<ul>
<li>RoI 중간에 0의 값을 갖는 Noise가 발생하는 경우에 Dilation 연산으로 보정할 수 있습니다.</li>
</ul></li>
<li>한 번의 호출로 몇 번씩 연산을 반복할지를 인자 &lsquo;iterations&rsquo;로 조절할 수 있습니다.</li>
</ul>
<pre><code class="language-python">ret, th = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
kernel = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=np.uint8)
erosion = cv2.erode(th, kernel, iterations=1)
dilation = cv2.dilate(th, kernel, iterations=1)
th = cv2.cvtColor(th, cv2.COLOR_GRAY2RGB)
erosion = cv2.cvtColor(erosion, cv2.COLOR_GRAY2RGB)
dilation = cv2.cvtColor(dilation, cv2.COLOR_GRAY2RGB)
th = cv2.rectangle(th, (200, 140), (400, 340), (255, 0, 0), 3)
erosion = cv2.rectangle(erosion, (200, 140), (400, 340), (255, 0, 0), 3)
dilation = cv2.rectangle(dilation, (200, 140), (400, 340), (255, 0, 0), 3)
plt.subplot(221)
plt.imshow(th, cmap='gray')
plt.title('Binary Kitten')
plt.subplot(223)
plt.imshow(erosion, cmap='gray')
plt.title('Erosed Kitten')
plt.subplot(224)
plt.imshow(dilation, cmap='gray')
plt.title('Dilated Kitten')
plt.suptitle('Binary Kitten with morphology', size=15)
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.6/2019-12-16-morphology_6_1.png" />
</figure>
<h2 id="grayscale-nbsp-morphology">Grayscale&nbsp;Morphology</h2>
<hr />
<ul>
<li>Morphology Operation을 Grayscale Image에 적용하게 되면 기본 원리는 동일하지만 결과가 아주 달라집니다.</li>
<li>1, 0의 값을 사용하는 것이 아니라 Dilation의 경우 Max값을, Erosion의 경우 Min 값을 사용한다는 점이 다른 점 입니다.</li>
<li>자세한 것은 아래 수식을 통해 확인할 수 있습니다.
<ul>
<li>grayscale dilation : $ (I\oplus k)(j,i)=max_{(y,x)\subseteq k} (I(j-y,i-x)+k(y,x))$</li>
<li>grayscale erosion : $ (I\ominus k)(j,i)=min_{(y,x)\subseteq k} (I(j+y,i+x)-k(y,x))$
<ul>
<li>I = Image, k = kernel</li>
</ul></li>
</ul></li>
<li>수식에서 알 수 있듯 Min, Max연산이 적용됩니다. Dilation의 경우 큰 값을 더 크게, 작은 값을 더 작게 하여 픽셀값간의 차이를 극대화하는 연산이고, Erosion의 경우 큰 값을 작게, 작은 값을 크게 하여 전체적으로 평평하게 만드는 연산입니다.</li>
</ul>
<pre><code class="language-python">kernel = np.array([[1, 2, 1]])
gray_kernel = np.dot(kernel.T, kernel)
gray_erosion = cv2.erode(img, gray_kernel, iterations=1)
gray_dilation = cv2.dilate(img, gray_kernel, iterations=1)
plt.subplot(221)
plt.imshow(img, cmap='gray')
plt.title('Gray Kitten')
plt.subplot(223)
plt.imshow(gray_erosion, cmap='gray')
plt.title('Gray Erosed Kitten')
plt.subplot(224)
plt.imshow(gray_dilation, cmap='gray')
plt.title('Gray Dilated Kitten')
plt.suptitle('Gray Kitten with morphology', size=15)
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.6/2019-12-16-morphology_9_0.png" />
</figure>
<ul>
<li>어떤 Image에 커널을 적용하느냐가 Morphology Operation 의 핵심입니다. 물론 어떤 커널을 설계하느냐도 중요하지만, 어떤 연산을 어떤 순서로 몇 번 씩 적용할 것인가 또한 결과물에 많은 영향을 끼칩니다.
<ul>
<li>위 결과물을 얻는데 사용한 kernel은 가운데쪽에 더 많은 가중치를 주게 되어 주변과의 명암 차이를 더 크게 하는 효과가 있습니다.</li>
</ul></li>
<li>Morphology연산은 Heuristic한 특성이 크게 드러나는 연산입니다.
<ul>
<li>다양한 특성이 존재하는 Image 전체에 일괄적으로 동일한 Morphology Operation을 적용하는 것은 대부분 의미가 없고, 동일한 특성을 가진 부분에 특정한 목적 위해 적용하는 편이 좋습니다.</li>
<li>이러한 작업을 잘 하기 위해서는 결국 다양한 Image에 다양한 방법으로 다양한 커널을 적용해보면서 감을 잡아야 합니다.</li>
</ul></li>
</ul>
<h2 id="composited-nbsp-morphological-nbsp-operations">Composited&nbsp;Morphological&nbsp;Operations</h2>
<hr />
<ul>
<li>앞서 소개한 두 Morphology Operation을 번갈아 한 번 씩 적용하는 작업 또한 상당히 빈번하게 사용됩니다.
<ul>
<li>한 번 변형한 Mask를 원래 크기로 되돌리기 위해서인데, 이러한 작업을 통해 원하는 노이즈만 제거된 결과를 얻을 수 있습니다.</li>
</ul></li>
<li>작업을 진행하는 순서에 따라 아래 두 가지로 나눌 수 있습니다.
<ul>
<li>Erosion&rarr;Dilation의 경우 Open(열기)</li>
<li>Dilation의&rarr;Erosion 경우 Close(닫기)</li>
</ul></li>
<li>Open은 1 값을 갖는 노이즈를 줄이고, Close는 0값을 갖는 노이즈를 줄이는데 사용됩니다.</li>
</ul>
<pre><code class="language-python">ret, th = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
erosion = cv2.erode(th, kernel, iterations=1)
dilation = cv2.dilate(th, kernel, iterations=1)
opened = cv2.dilate(erosion, kernel, iterations=1)
closed = cv2.erode(dilation, kernel, iterations=1)
plt.subplot(221)
plt.imshow(th, cmap='gray')
plt.title('Binary Kitten')
plt.subplot(223)
plt.imshow(opened, cmap='gray')
plt.title('Opened Kitten')
plt.subplot(224)
plt.imshow(closed, cmap='gray')
plt.title('Closed Kitten')
plt.suptitle('Binary Kitten with double morphology', size=15)
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.6/2019-12-16-morphology_12_0.png" />
</figure>
<ul>
<li>Gray Scale Image에도 동일한 작업을 진행할 수 있습니다.</li>
</ul>
<pre><code class="language-python">gray_open = cv2.dilate(gray_erosion, kernel, iterations=2)
gray_close = cv2.erode(gray_dilation, kernel, iterations=2)
plt.subplot(221)
plt.imshow(img, cmap='gray')
plt.title('Gray Kitten')
plt.subplot(223)
plt.imshow(gray_open, cmap='gray')
plt.title('Gray opened Kitten')
plt.subplot(224)
plt.imshow(gray_close, cmap='gray')
plt.title('Gray closed Kitten')
plt.suptitle('Gray Kitten with double morphology', size=15)
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.6/2019-12-16-morphology_14_0.png" />
</figure>
<h2 id="conclusion">Conclusion</h2>
<hr />
<ul>
<li>Morphology Operation은 주로 Binary Image로 생성한 RoI Mask를 다루는데 많이 쓰입니다.</li>
<li>개인적으로 RoI Mask의 Denoising에 매우 유용하게 사용하고 있고, Edge Detection 등의 연산과 연계하는 등 활용 방안이 아주 많으니 꼭 익혀두시는 것을 추천드립니다.</li>
</ul>
<h2 id="reference">Reference</h2>
<hr />
<ul>
<li>[1] 오일석, &ldquo;모폴로지,&rdquo; in 컴퓨터 비전, vol.4, Republic of Korea:한빛아카데미, 2014, pp. 97-103</li>
<li>[2] Accessed: &lsquo;Mathematical morphology&rsquo;, Wikipedia. [Online]. Available: <a href="https://en.wikipedia.org/wiki/Mathematical_morphology" target="_blank">https://en.wikipedia.org/wiki/Mathematical_morphology</a></li>
</ul>
</description>
</item>
<item>
<title>[Tutorial] Basic Image Operation</title>
<link>/post/2020-06-30-basic_image_operation/</link>
<pubDate>Tue, 30 Jun 2020 10:00:00 +0900</pubDate>
<guid>/post/2020-06-30-basic_image_operation/</guid>
<description>
<h2 id="basic-image-operation">Basic image operation</h2>
<hr />
<ul>
<li>이번 장 에서는 이미지에 다양한 효과를 줄 수 있는 이미지 연산 방법에 대하여 알아보겠습니다.</li>
<li>이미지로 할 수 있는 기본 연산을 총 네 가지로 나누어서 설명하겠습니다. 각각의 기본 연산들을 조합해서 훨씬 더 많은 효과를 낼 수 있습니다.</li>
<li>네 가지 기본 연산은 아래와 같습니다.
<ul>
<li><a href="#dotnbspoperation">Dot Operation</a></li>
<li><a href="#areanbspoperation">Area Operation</a></li>
<li><a href="#geometricnbspoperation">Geometric Operation</a></li>
<li><a href="#interpolation">Interpolation</a></li>
</ul></li>
</ul>
<h3 id="import-libraries">Import Libraries</h3>
<pre><code class="language-python">import os
import sys
import math
from platform import python_version
import cv2
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
print(&quot;Python version : &quot;, python_version())
print(&quot;Opencv version : &quot;, cv2.__version__)
matplotlib.rcParams['figure.figsize'] = (4.0, 4.0)
</code></pre>
<pre><code>Python version : 3.6.9
Opencv version : 4.1.2
</code></pre>
<h3 id="data-load">Data load</h3>
<pre><code class="language-python">sample_image_path = '../image/'
sample_image = 'kitten.jpg'
img = cv2.imread(os.path.join(sample_image_path, sample_image), cv2.IMREAD_GRAYSCALE)
h, w = img.shape
</code></pre>
<h3 id="data-description">Data description</h3>
<ul>
<li>본 예제에서 사용할 데이터는 아래와 같습니다.
<ul>
<li>귀여운 아기 고양이 입니다<a href="https://patch.com/maryland/annearundel/free-cat-kitten-adoptions-anne-arundel" target="_blank">[7]</a>.</li>
</ul></li>
</ul>
<pre><code class="language-python">plt.imshow(img, cmap='gray')
plt.title('Kitten')
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.4/2019-12-16-Basic_Image_Operation_6.png" />
</figure>
<h2 id="dot-nbsp-operation">Dot&nbsp;operation</h2>
<hr />
<ul>
<li>Dot Operation이란, Source Image의 Pixel과 Target Image의 Pixel간의 1:1 연산을 말합니다.</li>
<li>이것을 수식으로는 아래와 같이 표현할 수도 있습니다.
<ul>
<li>$pixel(i, j)_{after} = f(pixel(i, j)_{before})$</li>
<li>여기에서 다시 함수 $f$에 따라 <strong>Affine</strong><a href="https://en.wikipedia.org/wiki/Affine_transformation" target="_blank">[2]</a> , <strong>Gamma</strong><a href="https://en.wikipedia.org/wiki/Gamma_correction" target="_blank">[3]</a> 연산으로 나눌 수 있습니다.</li>
</ul></li>
<li>아래 코드는 몇 가지 Affine Operation 예시 입니다.</li>
</ul>
<pre><code class="language-python">bright_img = img + 50
bright_img[img &gt; 155] = 255
dark_img = img - 50
dark_img[img &lt; 100] = 0
reverse_img = 255 - img
plt.figure(figsize=(8, 8))
plt.subplot(2, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Gray Kitten')
plt.subplot(2, 2, 2)
plt.imshow(bright_img, cmap='gray')
plt.title('Bright Kitten')
plt.subplot(2, 2, 3)
plt.imshow(dark_img, cmap='gray')
plt.title('Dark Kitten')
plt.subplot(2, 2, 4)
plt.imshow(reverse_img, cmap='gray')
plt.title('Reversed Kitten')
plt.suptitle('Kitten with affine transform.', size=15)
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.4/2019-12-16-Basic_Image_Operation_10.png" />
</figure>
<ul>
<li>아래 코드는 Gamma Correlation Operation 예시 입니다.</li>
</ul>
<pre><code class="language-python">bright_gamma = 0.5
dark_gamma = 1.5
bright_gamma_image = np.uint8(255 * np.power(img / 255, bright_gamma))
dark_gamma_image = np.uint8(255 * np.power(img / 255, dark_gamma))
plt.figure(figsize=(8, 8))
plt.subplot(2, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Gray Kitten')
plt.subplot(2, 2, 3)
plt.imshow(bright_gamma_image, cmap='gray')
plt.title('Gamma Bright Kitten')
plt.subplot(2, 2, 4)
plt.imshow(dark_gamma_image, cmap='gray')
plt.title('Gamma Dark Kitten')
plt.suptitle('Kitten with gamma correlation transform.', size=15)
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.4/2019-12-16-Basic_Image_Operation_12.png" />
</figure>
<ul>
<li>Gamma Correlation Transform과 Affine Transform이 각각 Image에 끼치는 영향이 어떤 차이가 있을까요?</li>
<li>변환된 각 Image의 Histogram을 확인해보면 차이를 확실히 알 수 있습니다.</li>
</ul>
<pre><code class="language-python">def histogram_cv(img):
h, w = img.shape[:2]
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
hist = hist / (h * w)
return hist
</code></pre>
<pre><code class="language-python">plt.figure(figsize=(12, 8))
plt.subplot(2, 3, 1)
plt.imshow(img, cmap='gray')
plt.title('Kitten')
plt.subplot(2, 3, 2)
plt.imshow(bright_img, cmap='gray')
plt.title('Affine bright Kitten')
plt.subplot(2, 3, 3)
plt.imshow(bright_gamma_image, cmap='gray')
plt.title('Gamma bright Kitten ')
plt.subplot(2, 3, 4)
plt.plot(histogram_cv(img))
plt.title('Kitten Histogram')
plt.subplot(2, 3, 5)
plt.plot(histogram_cv(bright_img))
plt.title('Affine bright Kitten Histogram')
plt.subplot(2, 3, 6)
plt.plot(histogram_cv(bright_gamma_image))
plt.title('Gamma bright Kitten Histogram')
plt.suptitle('Histogram comparison', size=15)
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.4/2019-12-16-Basic_Image_Operation_15.png" />
</figure>
<ul>
<li>원래 Image와 변환된 Image들의 Histogram 입니다.</li>
<li>Affine 변환의 경우 픽셀값에 상수를 더하여 밝게 만들고, 픽셀값의 최대치인 255에 도달하면 그냥 255에 놔두는 반면,</li>
<li>Gamma Correlation 변환의 경우 히스토그램의 분포 형태를 어느 정도 유지하며 밝아지는 모습을 확인할 수 있습니다.
<ul>
<li>이 두 연산의 차이는 그림과 히스토그램을 같이 볼 때 더 크게 체감이 됩니다. Affine Operation을 적용한 경우, 가장 밝은 부분부터 뭉개지는 듯한 모습인 반면, Gamma Operation을 적용할 경우 원래 형태를 유지하며 밝아지는 모습입니다.</li>
</ul></li>
</ul>
<h2 id="area-nbsp-operation">Area&nbsp;operation</h2>
<hr />
<ul>
<li>Area Operation이란, Target Image의 한 Pixel값을 결정하기 위해 Source Image의 여러 개의 Pixel값을 필요로 하는 연산을 말합니다.</li>
<li>Source Image의 여러 Pixel값들에 특정 가중치를 부여하고, Source Image와 가중치의 곱의 합을 구하여 Target Image를 구하는 방법이 일반적 입니다.
<ul>
<li>여기에서 특정 가중치를 구할 때, 일정한 크기의 Mask에만 유효한 값을 부여하고 나머지 영역에는 0을 부여하곤 합니다.</li>
<li>이러한 연산을 Correlation, 혹은 Convolution이라고 합니다.
<ul>
<li>Correlation과 Convolution은 엄밀히 말하면 서로 다른 연산이나, Image Processing의 특성상 <em>거의 같은</em> 연산인 것으로 생각하고 넘어가겠습니다.</li>
</ul></li>
</ul></li>
<li>OpenCV에서 <strong>&lsquo;cv2.filter2D()&rsquo;</strong> 를 통해 쉽게 적용할 수 있고, 몇몇 자주 쓰이거나 특별한 연산의 경우 따로 정의된 함수가 존재하기도 합니다.
<ul>
<li>(e.g)Median Filter<a href="https://en.wikipedia.org/wiki/Median_filter" target="_blank">[4]</a> 는 <strong>&lsquo;cv2.medianBlur(img,kernel)&rsquo;</strong> 을 통해 제공되는데, 엣지 정보를 잘 남겨두면서 노이즈를 제거하는 방법으로 알려져 있습니다.</li>
</ul></li>
<li>어떠한 Mask를 사용하느냐에 따라 결과 영상의 특성이 천차 만별로 달라질 수 있습니다.
<ul>
<li>아래 예시중 수평, 수직방향 Edge를 각각 구한 결과가 있습니다. 예시에서 사용된 Mask가 Sobel Filter의 초기 모델이며, Edge Detection에서 자세히 다루겠습니다.</li>
<li>Sharpen이라는 기법은 물체의 Edge를 강하게 드러내는 방법중 하나 입니다.</li>
<li>위 연산들은 앞서 말했다시피 완전히 다른 결과를 만들지만, 적용하는 Mask만 다를 뿐 같은 함수 호출을 통해 만들어낸 결과임을 주목합시다.</li>
</ul></li>
</ul>
<pre><code class="language-python">blur_mask = np.ones((3, 3), dtype=np.uint8) / 9
horiz_edge_mask = np.array([[1, 1, 1],
[0, 0, 0],
[-1, -1, -1]])
vert_edge_mask = np.array([[1, 0, -1],
[1, 0, -1],
[1, 0, -1]])
sharp_mask = np.array([[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]])
dst1 = cv2.filter2D(img, -1, blur_mask)
dst2 = cv2.filter2D(img, -1, horiz_edge_mask)
dst3 = cv2.filter2D(img, -1, vert_edge_mask)
dst4 = cv2.filter2D(img, -1, sharp_mask)
dst4_blur = cv2.medianBlur(dst4, 3)
plt.figure(figsize=(12,8))
plt.subplot(231)
plt.imshow(dst1, cmap='gray')
plt.title('Blurring')
plt.subplot(232)
plt.imshow(dst4, cmap='gray')
plt.title('Sharpen')
plt.subplot(233)
plt.imshow(dst4_blur, cmap='gray')
plt.title('Sharpen with Median')
plt.subplot(234)
plt.imshow(dst2, cmap='gray')
plt.title('Horizontal edge')
plt.subplot(235)
plt.imshow(dst3, cmap='gray')
plt.title('Vertical edge')
plt.suptitle('Kitten with different operation', size=15)
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.4/2019-12-16-Basic_Image_Operation_18.png" />
</figure>
<h2 id="geometric-nbsp-operation">Geometric&nbsp;operation</h2>
<hr />
<ul>
<li>세 번째 Geometric Operation은 영상에 이동, 크기, 회전, 기울임 등의 효과를 주는 것을 말합니다.</li>
<li>물체의 기하학적 특징이 <strong>탄력적으로</strong> 보존되는 변환입니다.
<ul>
<li>찢거나 구기거나 흐릿하게 만들거나 하지 않고, 눈 두개 사이에 코가 있다는 등의 특성이 기울어지든, 회전하든 그대로 유지된다는 의미로 받아들이시면 됩니다.</li>
</ul></li>
<li>4가지 기본적인 연산을 순차적으로 조합하여 수 많은 변환을 수행할 수 있습니다<a href="https://en.wikipedia.org/wiki/Denavit%E2%80%93Hartenberg_parameters" target="_blank">[5]</a>.
<ul>
<li>e.g. 특정 점을 기준으로 회전, 좌우 반전(Flip), 시점 변환(Perspective transform) 등</li>
</ul></li>
<li>OpenCV에서 지원하는 <strong>&lsquo;cv2.getAffineTransform()&rsquo;</strong>, <strong>&lsquo;cv2.warpAffine()&rsquo;</strong> 함수를 통해 Geometric Operation을 적용할 수 있습니다.
<ul>
<li>여기에서 함수 이름에 들어가는 Affine 때문에 헷갈리는 경우가 있을 수 있을 것 같습니다.</li>
<li>Dot Operation에서 소개한 Affine Operation은 개별 픽셀값 하나에 대한 Affine연산이며, 여기에서 나온 Affine의 의미는 Image의 전체 픽셀들에 대하여 지역적으로 적용하는 Affine 연산입니다.</li>
<li>이 둘의 차이는, 어떤 픽셀에 대하여 그 &lsquo;값&rsquo;을 바꾸느냐, 혹은 그 &lsquo;위치&rsquo;를 바꾸느냐에 따라 나뉘는 것으로 생각하시면 되겠습니다.</li>
</ul></li>
</ul>
<pre><code class="language-python">pts1 = np.float32([[50, 50], [200, 50], [50, 200]])
pts2 = np.float32([[10, 100], [200, 50], [100, 250]])
M = cv2.getAffineTransform(pts1, pts2)
dst1 = cv2.warpAffine(img, M, (w, h))
M = cv2.getRotationMatrix2D((w / 2, h / 2), -30, 1)
dst2 = cv2.warpAffine(img, M, (w, h))
plt.figure(figsize=(12, 4))
plt.subplot(1, 3, 1)
plt.imshow(img, cmap='gray')
plt.title('Input')
plt.subplot(1, 3, 2)
plt.imshow(dst1, cmap='gray')
plt.title('Affine')
plt.subplot(1, 3, 3)
plt.imshow(dst2, cmap='gray')
plt.title('Rotation')
plt.suptitle('Lena with geometric transform')
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.4/2019-12-16-Basic_Image_Operation_20.png" />
</figure>
<ul>
<li>간단하게 고양이 Image를 뒤틀고, 회전시켜본 예시입니다.</li>
<li>각 함수의 자세한 사용법은 OpenCV 공식 문서<a href="https://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html" target="_blank">[6]</a>에서 확인할 수 있습니다.</li>
</ul>
<h2 id="interpolation">Interpolation</h2>
<hr />
<ul>
<li>Image의 크기를 바꾸는 경우(특히 확대할 때), 원본 Image의 픽셀과 픽셀 사이에 새로운 값이 생성되는 것이므로 이 새로운 값을 어떻게 채워야 할 지에 대한 문제가 발생하게 됩니다.</li>
<li>단순하게 한 쪽 픽셀 값을 그대로 가져다가 적용할 경우 영상이 실질적으로 해상도가 커지는 것이 아니라, 단순히 크기만 키우는 것 이라고 볼 수 있습니다.</li>
<li>이와 반대로 (머신러닝 등의 방법 없이)더 좋은 해상도의 Image를 얻기 위하여 Interpolation을 사용합니다.</li>
<li>OpenCV는 다양한 Interpolation(보간법)을 제공하는데, <strong>&lsquo;cv2.resize()&rsquo;</strong> 함수의 인자 &lsquo;interpolation&rsquo; 으로 조절할 수 있습니다.
<ul>
<li><em>&lsquo;cv2.INTER_NEAREST&rsquo;</em> - 최근접 이웃 픽셀의 값을 사용함. (size의 단순한 확대)</li>
<li><em>&lsquo;cv2.INTER_LINEAR&rsquo;</em> - 양 선형 보간 (default 값)</li>
<li><em>&lsquo;cv2.INTER_AREA&rsquo;</em> - 영역의 넓이에 기반한 방법. (사이즈를 줄일 때 좋은 성능)</li>
<li><em>&lsquo;cv2.INTER_CUBIC&rsquo;</em> - 양 3차 보간 : 양 선형 보간법 보다 4배 많은 정보를 활용.</li>
<li><em>&lsquo;cv2.INTER_LANCZOS4&rsquo;</em> - Lanczos 보간 : 양 3차 보간법 보다 4배 많은 정보를 활용.</li>
</ul></li>
</ul>
<pre><code class="language-python">h, w = [int(x) for x in img.shape]
face_img = img[h // 2 - 60 : h // 2 + 80, w // 2 - 110 : w // 2 + 30]
h, w = [int (x) for x in face_img.shape]
dst3 = np.zeros([h * 2, w * 2])
for i in range(h):
for j in range(w):
dst3[2 * i, 2 * j] = face_img[i, j]
dst3[2 * i + 1, 2 * j + 1] = face_img[i, j]
dst3[2 * i, 2 * j + 1] = face_img[i, j]
dst3[2 * i + 1, 2 * j] = face_img[i, j]
dst4 = cv2.resize(face_img, (w * 2, h * 2))
dst5 = cv2.resize(face_img, (w * 2, h * 2), interpolation=cv2.INTER_CUBIC)
dst6 = cv2.resize(face_img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4)
plt.figure(figsize=(4, 4))
plt.imshow(face_img, cmap='gray')
plt.title('original')
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.4/2019-12-16-Basic_Image_Operation_23.png" />
</figure>
<pre><code class="language-python">plt.figure(figsize=(16, 16))
plt.subplot(2, 2, 1)
plt.imshow(dst3, cmap='gray')
plt.title('resize manual')
plt.subplot(2, 2, 2)
plt.imshow(dst4, cmap='gray')
plt.title('resize bilinear')
plt.subplot(2, 2, 3)
plt.imshow(dst5, cmap='gray')
plt.title('resize cubic')
plt.subplot(2, 2, 4)
plt.imshow(dst6, cmap='gray')
plt.title('resize lanczos4')
plt.show()
</code></pre>
<figure>
<img src="/img/opencv/2.4/2019-12-16-Basic_Image_Operation_24.png" />
</figure>
<ul>
<li>아기 고양이의 얼굴만 확대한 Image를 통해 Interpolation 방법에 따른 Image 품질 차이를 확인해보겠습니다.</li>
<li>Manual Resize된 Image와 Interpolation이 적용된 Image와의 품질 차이는 확실히 드러납니다.</li>
<li>나머지 Interpolation이 적용된 Image들의 품질을 여러분의 눈으로는 확인 가능하신가요? 자세히 보시면 보일겁니다.
<ul>
<li>Bilinear Interpolation은 새로운 픽셀의 값을 계산할 때 양 옆의 두 픽셀만을 고려하기 때문에 계산량이 다소 적은 편 입니다.</li>
<li>Cubic, Lanczos4 등의 방법론은 더 많은 주변 픽셀들을 고려하기 때문에 일반적으로 Bilinear보다 더 높은 품질의 결과물을 보여줍니다.</li>
<li>연산 효율이 중요할 경우에는 bilinear interpolation을, 결과물의 품질이 중요한 경우에는 Cubic이나 Lanczos4중에서 선택하시면 됩니다.</li>
</ul></li>
</ul>
<h2 id="conclusion">Conclusion</h2>
<hr />
<ul>
<li>Image에 적용하는 기본 연산들을 알아보았습니다.</li>
<li>원하는 효과를 내기 위해 다양한 방식으로 연산을 조합해서 눈으로 직접 확인해보시면 많은 도움이 될 것 입니다.</li>
</ul>