-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.tex
1516 lines (1253 loc) · 93.6 KB
/
main.tex
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
\documentclass[oneside,final,14pt]{extreport}
%% my command
%%%%%%%%%%%%%%
% Путь к файлу с изображениями
\newcommand{\picPath}{pictures}
% Величина отступа
\newcommand{\indentSpace}{1.25cm}
% Сокращения
\newcommand{\urlTitle}{ $-$ URL: }
%%%%%%%%%%%%%%%
% Изменяем шрифт
\usepackage{fontspec}
\setmainfont{Times New Roman}
\listfiles
% Полуторный интервал
\linespread{1.6}
% Отступ
\setlength\parindent{\indentSpace}
% Математика
\usepackage{mathtools}
% Картинки
\usepackage{graphicx}
\usepackage{subcaption}
% Языковой пакет
\usepackage[russianb]{babel}
% Таблицы
\usepackage{tabularx}
% Настройка подписей к фигурам
% Меняем заголовки картинок
\usepackage[ labelsep= endash]{caption}
\captionsetup{%
figurename= Рисунок,
tablename= Таблица,
justification= centering% Формат - по центру
}
% Кирилица в подфигурах
\renewcommand{\thesubfigure}{\asbuk{subfigure}}
% разделитель в подфигурах - правая скобка
\DeclareCaptionLabelSeparator{r_paranthesis}{)\quad }
\captionsetup[subfigure]{labelformat=simple, labelsep=r_paranthesis}
% Добавляем итератор \asbuk,
% чтобы использовать кирилицу
% как маркеры
\usepackage{enumitem}
\makeatletter
\AddEnumerateCounter{\asbuk}{\russian@alph}{щ}
\makeatother
% Меняем маркеры в перечислениях
% Списки уровня 1
\setlist[enumerate,1]{label=\arabic*),ref=\arabic*}
% Списки уровня 2
\setlist[enumerate,2]{label=\asbuk*),ref=\asbuk*}
% Перечисления
\setlist[itemize,1]{label=$-$}
% Удаляем отступы перед и после
% списка
\setlist[itemize]{noitemsep, topsep=0pt}
\setlist[enumerate]{noitemsep, topsep=0pt}
% Красная строка в начале главы
\usepackage{indentfirst}
% Убиваем перенос
\usepackage[none]{hyphenat}
% Перенос длинных ссылок
\usepackage[hyphens]{url}
\urlstyle{same}
% Выравнивание по ширине
\usepackage{microtype}
%\usepackage[fontfamily=courier]{fancyvrb}
%\usepackage{verbatim}% configurable verbatim
% \makeatletter
% \def\verbatim@font{\normalfont\sffamily% select the font
% \let\do\do@noligs
% \verbatim@nolig@list}
%\makeatother
% Границы
\usepackage{vmargin}
\setpapersize{A4}
% отступы
%\setmarginsrb
%{3cm} % левый
%{2cm} % верхний
%{1cm} % Правый
%{2cm} % Нижний
%{0pt}{0mm} % Высота - отступ верхнего колонтитула
%{0pt}{0mm} % Высота - отступ нижнего колонтитула
\setlength\hoffset{0cm}
\setlength\voffset{0cm}
\usepackage[top=2cm, bottom=2cm, left=3cm, right=2cm,
]{geometry}
% Настройка заглавиий
\addto\captionsrussian{% Replace "english" with the language you use
\renewcommand{\contentsname}% содержания
{\hfill\bfseries
СОДЕРЖАНИЕ
\hfill
}%
\renewcommand{\bibname}% списка источников
{\hfill\bfseries
СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
\hfill
}%
}%\
%\renewcommand{\contentsname}{\hfill\bfseries СОДЕРЖАНИЕ \hfill}
% Настройка заглавий в главах
\usepackage{titlesec}
%\titleformat
%{\chapter} % command
%[display]
%{
%\bfseries
%} % format
%{
%\thechapter.
%} % label
%{
% 0 pt
%} % sep
%{
%\centering
%} % before-code
\titleformat{\chapter}
{\bfseries}
{\hspace{\indentSpace}\thechapter\hspace{1em}}
{0pt}
{
\vspace{0mm} }
[\vspace{14pt}]% Отступ после
% Начальный сдвиг заголовка 50 pt = 1.763888888cm.
% Второй параметр- сдвиг до = 2cm - 50pt
\titlespacing{\chapter}{0pt}{-0.2361cm}{0pt}
\titleformat{\section}
{\bfseries}{\hspace{\indentSpace}\thesection}{1em}{}
\titleformat{\subsection}
{\bfseries}{\hspace{\indentSpace}\thesubsection}{1em}{}
%\titleformat{\section}
% {\bfseries}
% {\thechapter.\hspace{1em}}
% {0pt}
% {\centering
% \vspace{0mm} }
% [\vspace{14pt}]% Отступ после
%\titlespacing{\section}{0pt}{-50pt}{0pt}
% Конец настройка заглавий
% Форматирование списка источников
\makeatletter
\renewcommand*{\@biblabel}[1]{\hfill#1}
\makeatother
% Убрать отсупы в списке источников
\usepackage{lipsum}
% ADD THE FOLLOWING COUPLE LINES INTO YOUR PREAMBLE
\let\OLDthebibliography\thebibliography
\renewcommand\thebibliography[1]{
\OLDthebibliography{#1}
\setlength{\parskip}{0pt}
\setlength{\itemsep}{0pt plus 0.3ex}
}
% Добавить точки в оглавление
\usepackage{tocstyle}
\newcommand{\autodot}{.}
% Чтобы картинки вставляись
% куда надо
\usepackage{float}
% Для вычисления кол-ва страниц
\usepackage{lastpage}
% Для вычисления кол-ва рисунков и таблиц
%%%
\usepackage{etoolbox}
\newcounter{totfigures}
\newcounter{tottables}
\providecommand\totfig{}
\providecommand\tottab{}
\makeatletter
\AtEndDocument{%
\addtocounter{totfigures}{\value{figure}}%
\addtocounter{tottables}{\value{table}}%
\immediate\write\@mainaux{%
\string\gdef\string\totfig{\number\value{totfigures}}%
\string\gdef\string\tottab{\number\value{tottables}}%
}%
}
\makeatother
\pretocmd{\chapter}{\addtocounter{totfigures}{\value{figure}}\setcounter{figure}{0}}{}{}
\pretocmd{\chapter}{\addtocounter{tottables}{\value{table}}\setcounter{table}{0}}{}{}
%%%
% Режим релиза
\sloppy
\usepackage{layout}
\begin{document}
%Статистический анализ текстовой информации вебинаров
%\newpage
\begin{center}
\bfseries РЕФЕРАТ
\end{center}
Курсовая работа содержит \pageref{LastPage} страниц, \totfig\ рисунков, \tottab\ таблицы, 5 источников.
ВЕБИНАР, КОРРЕЛЯЦИЯ ИЗОБРАЖЕНИЙ, ПРЕОБРАЗОВАНИЕ ФУРЬЕ, ЛОКАЛИЗАЦИЯ ТЕКСТА, TESSERACT, РАСПОЗНАВАНИЕ ТЕКСТА
Объектом исследования являются методы выделения текстовой информации из изображений.
Цель курсовой работы $-$ программная реализация процедур, вычисляющих основные критерии оценки вебинаров.
В результате работы были реализованы процедуры, реализующие
\begin{itemize}
\item поиск указки;
\item выделение слайдов;
\item распознавание блоков текста на слайдах.
\end{itemize}
\tableofcontents
\newpage
\begin{center}
\bfseries ВВЕДЕНИЕ
\end{center}
\addcontentsline{toc}{chapter}{Введение}
В Сибирском государственном университете телекоммуникаций и информатики,с которым у КубГУ имеется соглашение о сотрудничестве в сфере образования, науки, научной и инновационной деятельности стоит задача оценки
качества контактной работы, реализуемой посредством вебинаров, в ходе дистанционного обучения.
Для решения этой задачи разработана математическая модель, которая включает систему из 32 показателей качества организации и проведения вебинара (перечень которых представлен в приложении), позволяющих оценить с разных сторон качество вебинара 10-балльными экспертными оценками. Проблема заключается в существенных трудозатратах, которые несут эксперты при оценивании этих показателей. Кроме того, мнения экспертов субъективны, а задача поставлена максимально объективизировать процедуру оценивания, например, за счет минимизации влияния человеческого фактора в процедуре оценивания. В связи с этим актуальной является задача разработки такой компьютерной технологии, которая позволит оценить максимальное количество показателей без участия человека в автоматическом режиме. В числе показателей, которые могут быть автоматически при помощи некоторого алгоритма входят: колличество и качество информации на слайдах, использование указки, точность заявленной длительности мероприяти и тд.
Основой для анализа данных показателей является три основных аспекта:
\begin{itemize}
\item поиск указки;
\item выделение слайдов;
\item распознавание блоков текста на слайдах.
\end{itemize}
Для решения вышеперечисленных задач в ходе курсовой работы проведен анализ следующих процедур над изображениями:
\begin{itemize}
\item поиск границ объектов;
\item поиск вхождения одного изображения в другое;
\item вычисление коэффициента схожести изображений;
\item локализация текста.
\end{itemize}
Программно разработаны процедуры, реализующие основу для дальнейшего развития приложения автоматического вычисления основных критериев оценки вебинаров. В реализации используется бесплатная библиотека машинного зрения OpenCV.
\chapter{Методы определения границ объектов на изображении}
Границы объектов на изображении характеризуются изменением яркости в некотором направлении. Выделяют три вида границ: идеальные, размытые и крышевидные. На рисунке \ref{fig:contours} изображены вертикальные границы трех видов.
\begin{figure}[H]
\centering
\begin{subfigure}[b]{0.4\linewidth}
\includegraphics[width=\linewidth]{\picPath/perfect.png}
\caption{ Идеальная граница}
\end{subfigure}
\begin{subfigure}[b]{0.4\linewidth}
\includegraphics[width=\linewidth]{\picPath/smooth.png}
\caption{Размытая граница}
\end{subfigure}
\begin{subfigure}[b]{0.4\linewidth}
\includegraphics[width=\linewidth]{\picPath/roof.png}
\caption{Крышевидная граница}
\end{subfigure}
\caption{границы объектов: изображение, функция яркости, первая и вторая производные}
\label{fig:contours}
\end{figure}
Рассмотрим вертикальную размытую границу. Тогда зафиксировав ординату, получим дискретную функцию от одной переменной $g(x)$. Рассмотрим её первую и вторую производные: первая производная равна нулю в областях, где интенсивность постоянна и равна константе на границе, причем константа тем больше, чем уже граница. Вторая производная не равна нулю только в координатах начала и конца границы $g(x)$, в этих точках она равна бесконечности. Для случая крышевидной границы, первая производная положительна на подъеме и отрицательна на спуске границы. Вторая производная не ноль в трех точках, причем граница помещается между первой и последней не нулевой точкой второй производной. Отсюда следует вывод: зная направление границы, её координаты находятся из производной функции интенсивности по этому направлению.
В общем случае, если заранее неизвестны направления границ объектов, за направление берут направление максимального роста интенсивности то есть градиент изображения, если представлять его как дискретную функцию от двух переменных.
Градиент есть вектор частных производных:
\begin{equation}
\nabla f(x,y)
=
grad[f(x,y)]
=
\begin{bmatrix}
g_x(x,y)\\
g_y(x,y)
\end{bmatrix}
=
\begin{bmatrix}
\frac{\partial f(x,y)}
{\partial x}\\
\frac{\partial f(x,y)}
{\partial y}
\end{bmatrix}
\end{equation}
На практике производные вычисляются численно, разностными методами. Если принять расстояние между соседними в строке и соседними в столбце пикселями за единицу, компоненты градиента с точностью $O(1)$ вычисляется по формулам:
\begin{gather}
g_x(x,y)
=
\frac{\partial f(x,y)}
{\partial x}
=
f(x+1,y) - f(x,y)
\\
g_y(x,y)
=
\frac{\partial f(x,y)}
{\partial y}
=
f(x,y+1) - f(x,y)
\end{gather}
Что равносильно свертке изображения \cite{Dup:coursache} с ядрами
\begin{equation}
\begin{bmatrix}
-1\\1
\end{bmatrix}
\quad
\begin{bmatrix}
-1 & 1
\end{bmatrix}
\end{equation}
На практике для вычисления градиента используются оператор Собеля:
\vspace{3mm}
\begin{equation}
\begin{bmatrix}
-1 & \,2 & -1 \\
\,0 & \,0 &\,0 \\
\,1 & \,2 &\,1
\end{bmatrix}
\quad
\begin{bmatrix}
-1 & 0 & 1 \\
-2 & 0 & 2 \\
-1 & 0 & 1
\end{bmatrix}
\end{equation}
\vspace{3mm}Конечное изображение вычисляется по формуле
\begin{equation}
G
=
|G_x| + |G_y|
\end{equation}
Где $G_x$ и $G_y$ - результат свертки изображения с первым и вторым ядром оператора Собеля соответственно.
В результате применения оператора Собеля на изображении белым цветом выделены предполагаемые границы. Градиентный метод Собеля выделения границ широко используется в прикладных задачах благодаря своей простоте и высокой точности. К недостаткам метода Собеля можно отнести зависимость от шумов: при достаточно высоком их содержании алгоритм не способен адекватно определить границы объектов.
\chapter{Методы сравнения изображений}
\section{Сравнение гистограмм}
Метод сравнения гистограмм - один из самых простых и быстрых способов сравнения двух изображений. Алгоритм основан на предположении о том, что похожие изображения имеют похожие цвета.
Гистограмма это график или функция распределения элементов цифрового изображения с различной яркостью. Гистограмма определена на множестве всех возможных значений яркостей чёрно-белого изображения, значение функции равно количеству пикселей, яркость которых равна аргументу гистограммы. В общем случае значение яркости - $n$ мерный вектор. Обычно для сравнения цветных изображений используются каналы HS цветового пространства HSV. Это основано на том, что при сравнении цвета разной яркости не различают, а поэтому канал V, отвечающий за яркость цвета игнорируют.
Для сравнения гистограмм в openCV используется одна из метрик. Сравнение работы алгоритма с разными метриками на тестовых рисунках \ref{hist:pics} представлено в таблице \ref{hist:comparison}.
Correlation CV\_COMP\_CORREL
$$
d(H_1,H_2)
=
\frac{
\sum_I(H_1(I) - \overline{H}_1)
(H_2(I)-\overline{H}_2)
}{
\sqrt{
\sum_I(H_1(I) - \overline{H}_1)^2
\sum_I(H_2(I) - \overline{H}_2)^2
}
}
$$
$$
\overline{H}_k
=
\frac{1}{N}
\sum_J H_k(J)
$$
Chi-Square ( CV\_COMP\_CHISQR )
$$
d(H_1,H_2)
=
\sum_I \frac{
(H_1(I) - H_2(I))^2}
{H_1(I)}
$$
Intersection ( method=CV\_COMP\_INTERSECT )
$$
d(H_1,H_2)
=
\sum_I
\min (H_1(I),H_2(I))
$$
Bhattacharyya distance ( CV\_COMP\_BHATTACHARYYA )
$$
d(H_1,H_2)
=
\sqrt{ 1 -
\frac{1}{
\sqrt{\overline{H}_1
\overline{H}_2
N^2}
}
\sum_I
\sqrt{H_1(I) H_2(I)}
}
$$
Где $I$ в общем случае вектор, сумма идет по всем возможным векторам.
Достоинства данного метода - инвариантность относительно формы и размера сравниваемых изображений.
Главный недостаток метода сравнения гистограмм - разделение изображений весьма условно. Каждому изображению подобно всё множество изображений, составленных из тех же пикселей, расположенных в произвольном порядке. Поэтому данный метод не подходит, например, для задачи поиска курсора так как существует вероятность того, что на изображении, кроме курсора, могут находиться элементы, гистограммы которых очень близки к гистограмме курсора.
\begin{figure}[H]
\begin{center}
\begin{subfigure}[b]{0.2\linewidth}
\includegraphics[width=\linewidth]{\picPath/girl.jpg}
\caption{ girl.jpg}
\end{subfigure}
\begin{subfigure}[b]{0.3\linewidth}
\includegraphics[width=\linewidth]{\picPath/leafs.jpg}
\caption{ leafs.jpg}
\end{subfigure}
\begin{subfigure}[b]{0.3\linewidth}
\includegraphics[width=\linewidth]{\picPath/wood.jpg}
\caption{ wood.jpg}
\end{subfigure}
\end{center}
\caption{изображения, используемые в сравнительном тесте }
\label{hist:pics}
\end{figure}
\begin{table}[H]
\caption{cравнение результатов сравнения изображений по гистограмме}
\label{hist:comparison}
\begin{tabularx}{\textwidth}{|X|X|X|X|X|}
\hline
&
girl.jpg сравнить с girl.jpg
&
girl.jpg сравнить с leafs.jpg
&
girl.jpg сравнить с wood.jpg
&
wood.jpg сравнить с leafs.jpg
\\
\hline
CV\_\allowbreak COMP\_\allowbreak CORREL
&
1.000000
&
-0.028190,
&
0.639221
&
-0.018233
\\
\hline
CV\_\allowbreak COMP\_\allowbreak CHISQR
&
0.000000
&
47.621748,
&
131.495723
&
23476.763941
\\
\hline
CV\_\allowbreak COMP\_\allowbreak INTERSECT
&
13.806632
&
0.057196,
&
6.012272
&
0.124236
\\
\hline
CV\_\allowbreak COMP\_\allowbreak BHATTA\allowbreak CHARYYA
&
0.000000
&
0.996709,
&
0.449109
&
0.987969
\\
\hline
\end{tabularx}
\end{table}
\section{Совпадения по шаблону}
Методы сравнения по шаблону используются для нахождения координат малого шаблонного изображения в большом. Алгоритм поиска таков:
на первом этапе происходит нелинейная фильтрация изображения. Как и в остальных фильтрах, для фильтрации используется скользящее окно \cite{Dup:coursache}. Размер скользящего окна равен размеру малого изображения. Все возможные подобласти размера окна из большого изображения поэлементно сравниваются с малым изображением посредством одной из метрик:
\newpage
method=CV\_TM\_SQDIFF
$$
R(x,y)
=
\sum_{x',y'}
(T(x',y')-I(x+x',y+y'))^2
$$
method=CV\_TM\_SQDIFF\_NORMED
$$
R(x,y)
=
\frac{
R(x,y)
=
\sum_{x',y'}
(T(x',y')-I(x+x',y+y'))^2
}
{
\sqrt{
\sum_{x',y'}
T(x',y')^2
\sum_{x',y'}
I(x+x',y+y')^2
}
}
$$
method=CV\_TM\_CCORR
$$
R(x,y)
=
\sum_{x',y'}
( T(x',y')I(x+x',y+y'))
$$
method=CV\_TM\_CCORR\_NORMED
$$
R(x,y)
=
\frac{
\sum_{x',y'}
( T(x',y')I(x+x',y+y'))
}
{
\sum_{x',y'}
T(x',y')^2
\sum_{x',y'}
I(x+x',y+y')^2
}
$$
На втором этапе полученная двумерная матрица нормируется, и в зависимости от используемого метода находится её минимальный или максимальный элемент. Иллюстрация работы алгоритма поиска по шаблону представлена на рисунке \ref{fig:templateMatching} .
\begin{figure}[H]
\centering
\begin{subfigure}[b]{0.2\linewidth}
\includegraphics[width=\linewidth]{\picPath/cursor.png}
\caption{ Курсор}
\end{subfigure}
\begin{subfigure}[b]{0.4\linewidth}
\includegraphics[width=\linewidth]{\picPath/tmpl_matching_inp.png}
\caption{Исходное изображение}
\end{subfigure}
\begin{subfigure}[b]{0.4\linewidth}
\includegraphics[width=\linewidth]{\picPath/match_template_mask.png}
\caption{Результат применения свёртки \phantom{локализован курсор}}
\end{subfigure}
\begin{subfigure}[b]{0.4\linewidth}
\includegraphics[width=\linewidth]{\picPath/templ_matching_result.png}
\caption{На исходном изображении локализован курсор}
\end{subfigure}
\caption{пример работы алгоритма поиска изображения по шаблону}
\label{fig:templateMatching}
\end{figure}
Достоинство метода - высокая точность нахождения фрагментов изображений.
Недостатки - высокая точность достигается только в случае, когда фрагмент того же размера и не повернут относительно шаблона.
Существуют также методы, инвариантные относительно размера и положения искомого элемента и перспективы. Их называются \textit{методами совпадения по признакам}. Суть методов совпадения по признакам заключается в том, что из шаблонного изображения выделяются некоторые характерные признаки. После, в большом изображении находится объекты, схожие по признакам с шаблоном. Этот класс методов избыточен для решаемой в этой работе задаче.
\chapter{Пеобразование Фурье}
Для анализа аналоговых и цифровых сигналов зачастую используются дискретные преобразования, переводящие сигнал из одного базиса в другой. Многие операции над сигналом значительно упрощаются в частотном базисе, позволяя ускорить алгоритмы машинного зрения. Рассмотренные ниже преобразования представляют сигнал в виде суперпозиции частот.
\section{Непрерывное преобразование Фурье}
Непрерывное преобразование Фурье имеет вид:
Прямое:
\begin{equation}
F(s)
\equiv
\mathcal{F}\{f(x)\}(s)
\equiv
{\int\limits_{-\infty}^{\infty}f(x)\,e^{-2\pi i s x}\,dx~}
\end{equation}
Обратное:
\begin{equation}
f(x)
\equiv
\mathcal{F}^{-1}\{F(s)\}(x)
\equiv
{\int\limits_{-\infty}^{\infty}F(s)\,e^{2\pi i s x}\,ds~}
\end{equation}
Где $f(x)$ - непрерывная функция - сигнал вещественной переменной,
$F(x)$ - непрерывная функция комплексной переменной - Фурье образ $f(x)$ \cite{Gonzalez}.
Сверткой называют интегральное преобразование вида:
\begin{equation}
(f*g)(x)
=
{\int\limits_{-\infty}^{\infty} f(y)\,g(x-y)\,dy~}
=
{\int\limits_{-\infty}^{\infty} f(x-y)\,g(y)\,dy~}
\end{equation}
Корреляцией двух функций называют преобразование вида:
\begin{equation}
(f \star g)(x)
=
{\int\limits_{-\infty}^{\infty} f(y)\,g(x+y)\,dy~}
=
{\int\limits_{-\infty}^{\infty} f(x+y)\,g(y)\,dy~}
\end{equation}
Доказана теорема свертки
\begin{equation}
{(f*g)(x)}
\equiv
\mathcal{F}^{-1} \{
\mathcal{F}(f) \cdot \mathcal{F}(g)
\}
\label{correlation_theorem}
\end{equation}
Аналогично теореме о свертке, существует теорема о корреляция
\begin{equation}
{(f \star g)(x)}
\equiv
\mathcal{F}^{-1} \{
\mathcal{F}^*(f) \cdot \mathcal{F}(g)
\}
\end{equation}
Где операция \hspace{3pt} $\cdot$ \hspace{3pt} $-$ скалярное произведение, а $\mathcal{F}^*(f)$ - комплексно сопряженный образ Фурье функции $f$ .
\section{Дискретное преобразование Фурье}
Известно, что компьютер оперирует исключительно конечным набором цифровых данных и не может напрямую обрабатывать аналоговые сигналы. Поэтому первым этапом компьютерной обработки любого сигнала является его дискретизация т.е представление в виде конечной последовательности точек аргумент- значение.
Рассмотрим дельта функцию
\begin{equation*}
\delta(t)=
\begin{cases}
\infty & t = 0 \\
0 & t \neq 0
\end{cases}
\quad , \quad
{\int\limits_{-\infty}^{\infty}\delta(t)\,dt~}
=
1
\end{equation*}
Имеющую свойства
\begin{gather*}
{\int\limits_{-\infty}^{\infty}f(t)\delta(t)\,dt~}
=
f(0)
\\
{\int\limits_{-\infty}^{\infty}f(t)\delta(t-t_{0})\,dt~}
=
f(t_{0})
\end{gather*}
Если функция $f(t)$ - дискретная, то рассматривается дискретная дельта функция
\begin{equation}
\delta(t)=
\begin{cases}
1 & t = 0 \\
0 & t \neq 0
\end{cases}
\end{equation}
Тогда
\begin{gather}
\sum_{t = - \infty}^{\infty} \delta(t)
=
1
\\
\sum_{t = - \infty}^{\infty} f(t)
\delta(t - t_{0})
=
f(t_{0})
\end{gather}
Рассматривая функцию, называемую серия импульсов (в англоязычной литературе train of impulses)
\begin{equation}
s_{\varDelta T}(t)
=
\sum_{k=-\infty}^{\infty}
\delta(t - k\varDelta T)
\end{equation}
И её образ Фурье
\begin{equation}
S(\mu) = \mathcal{F}
\{ s_{\varDelta T}(t) \}
=
\frac{1}{\varDelta T}
\sum_{n = - \infty}^{\infty}
\delta(
\mu - \frac{n}{\varDelta T}
)
\end{equation}
Можем построить математическую модель дискретизации
функции $f(t)$ с соответствующим Фурье образом $F(s) = \mathcal{F}\{f\}(s)$ следующим образом
\begin{equation}
\tilde{f}(t) =
f(t)s_{\varDelta T}(t)
=
\sum_{n = -\infty}^{\infty}
f(t)
\delta(t - n\varDelta T)
\end{equation}
Тогда рассматривая образ Фурье дискретной функции, используя теорему свертки \ref{correlation_theorem}, можно получить \cite{Gonzalez}
\begin{equation}
\tilde{F}(\mu) =
\frac{1}{\varDelta T}
\sum_{n = - \infty}^{\infty}
F(
\mu - \frac{n}{\varDelta T}
)
\label{Furier_sampling_result}
\end{equation}
Пусть значения $F(\mu)$ ограничены $[-\mu_{max},\mu_{max} ] $ т.е. частоты $f(t)$ ограничены (в англоязычной литературе band limited functions) и
пусть частота при дискретизации удовлетворяет неравенству:
\begin{equation}
\frac{1}{\varDelta T}
>
2\mu_{max}
\end{equation}
Из \ref{Furier_sampling_result} и предыдущего неравенства очевидно, что $\tilde{F}(\mu)$ и $F(\mu)$ связаны соотношением
\begin{equation}
F(\mu)
=
H(\mu)
\tilde{F}(\mu)
\end{equation}
Где
\begin{equation}
H(\mu)
=
\begin{cases}
\varDelta T &
\mu \in [-\mu_{max},\mu_{max}] \\
0 & иначе
\end{cases}
\end{equation}
Обратное преобразование $H(\mu)$ имеет вид
\begin{gather*}
h(t)
=
\mathcal{F}^{-1}\{H(\mu)\}(t)
=
\int\limits_{-\infty}^{\infty}
H(\mu)
e^{2\pi i \mu t }
d\mu~
=
\int\limits_{-\mu_{max}}^{\mu_{max}}
\varDelta T
e^{2\pi i \mu t }
d\mu~
=
\\
=
\frac{\varDelta T}
{i 2 \pi t}
\left[
e^{ 2\pi i \mu t }
\right]_{-\mu_{max}}^{\mu_{max}}
=
2\varDelta T \mu_{max}
\frac{sin(2\pi t \mu_{max}) }{(2\pi t \mu_{max})}
=
2\varDelta T \mu_{max}
sinc(2t\mu_{max})
\end{gather*}
Отсюда следует вывод: допуская, что частота $f(t)$ ограничена по модулю значением $\mu_{max}$, зная $\tilde{f}(t)$, которая получена сэмплированием из $f(t)$ c частотой не меньше, чем $2 \mu_{max}$, можем приблизить $f(t)$ с любой точностью.
Вычислить $f(t)$ через $\tilde{f}(t)$ можно следующим образом:
\begin{gather*}
f(t)
=
\mathcal{F}^{-1}
\{ F(\mu) \}
\\
=
\mathcal{F}^{-1}
\{
H(\mu)\tilde{F}(\mu)
\}
\\
=
h(t)*\tilde{f}(t)
\end{gather*}
или
\begin{equation}
f(t)
=
2 \mu_{max} \varDelta T
\sum_{ n = - \infty}^{\infty}
f(n \varDelta T )
sinc[ 2 \mu_{max} (t - n \varDelta T) ]
\end{equation}
Если же $ \varDelta T = \frac{1}{2 \mu_{max}} $ :
\begin{equation}
f(t)
=
\sum_{ n = - \infty}^{\infty}
f(n \varDelta T )
sinc[ (t - n \varDelta T) / \varDelta T ]
\end{equation}
Данный вывод называется \textit{теоремой Котельникова или сэмплирования.}
Этот подход широко используется в обработке изображений и звука. Например зная, что человек слышит звуки частоты от 16 до 20 000 Гц можно без какой-либо потери информации для человеческого слуха записывать звуки с частотой дискретизации 44100 Гц.
\section{Двумерное преобразование Фурье}
Все теоремы и свойства, рассмотренные выше, распространяются на случай функции $n$ переменных. Рассмотрим двумерный случай. Для непрерывного сигнала $f(x,y)$ преобразование Фурье имеет вид
\begin{gather}
\label{FFT_2d}
F(\mu,\nu)
=
\int\limits_{-\infty}^{\infty}
\int\limits_{-\infty}^{\infty}
f(t,z) \,
e^{-i 2 \pi( \mu t + \nu z)}
dz dt~
\\
\label{IFFT_2d}
f(t,z)
=
\int\limits_{-\infty}^{\infty}
\int\limits_{-\infty}^{\infty}
F(\mu,\nu) \,
e^{i 2 \pi( \mu t + \nu z)}
d\mu d\nu~
\end{gather}
Последовательность импульсов в двумерном случае будет выглядеть так:
\begin{equation}
S_{ \varDelta T \varDelta Z }
(t,z)
=
\sum_
{ m = - \infty}^{\infty}
\sum_
{ n = - \infty}^{\infty}
\delta(
t - m \varDelta T,
z - n \varDelta Z
)
\end{equation}
Предполагая, что частоты функции $f(x,y)$ ограничены в $
[- \mu_{max},\mu_{max}]
\times
[- \nu_{max},\nu_{max}]
$
для “сжатия функции без потерь” достаточно взять
\begin{gather}
\varDelta T
<
\frac{1}{2 \mu_{max}}
\\
\varDelta Z
<
\frac{1}{2 \nu_{max}}
\label{Kotelnicov_imparity}
\end{gather}
Цифровые изображения хранятся как набор пикселей. Пусть дано изображение $M\times N$. Чтобы представить его в пространственном базисе, можно, например, положить, что один пиксель есть единица измерения пространства. Тогда изображение моделируется формулой вида
\begin{equation}
\tilde{f}(t,z)
=
f(t,z)
S_{ \varDelta T \varDelta Z }
=
\sum_
{ m = 0}^{M-1}
\sum_
{ n = 0}^{N-1}
f(t,z)\delta(
t - m \varDelta T,
z - n \varDelta Z
)
\label{sample_2d}
\end{equation}
Где $\varDelta t = \varDelta z = 1$. Тогда соответствующие частоты будут изменяться в
пределах $[-\frac{1}{2},
\frac{1}{2}]
\times
[-\frac{1}{2},
\frac{1}{2}]$ согласно \refeq{Kotelnicov_imparity}.Таким частотам соответствуют периоды в пикселях: $[...,-3,-2] \cup [2,3,...]$.
Подставляя выражение \refeq{sample_2d} в прямое преобразование Фурье \refeq{FFT_2d}, получим
\begin{equation}
F(\mu,\nu)
=
\sum_
{ x = 0}^{M-1}
\sum_
{ y = 0}^{N-1}
f(x,y)
e^{
-i2\pi(\mu x / M +
\nu y / N )
}
\label{DFFT_2d}
\end{equation}
Подставляя \refeq{DFFT_2d} в обратное преобразование \refeq{IFFT_2d}, получим
\begin{equation}
F(x,y)
=
\sum_
{ \mu = 0}^{M-1}
\sum_
{ \nu = 0}^{N-1}
f(\mu,\nu)
e^{
i2\pi(\mu x / M +
\nu y / N )
\label{DIFFT_2d}