Kirill Rozin - Computer Vision. Alchemy of Modeling
1. Computer Vision
What is that?
What does mean
image processing?
What does mean
video processing?
What does mean
FG/BG, FD/FR,
Intrusion Area,
Tracking, Blob
merge?
Where magic is?
2. зрение
Компьютерное зрение представляет собой дисциплину, которое включает в себя методы сбора, обработки,
анализа, и
распознования образов на видео или изображении.
Типичные задачи компьютерного зрения:
Анализ
движения
ОтслеживаниеОбнаружение объекта Распознавание объектов
КлассификацияРаспознавание лица Распознавания эмоций
Оптическое
Распознавание
символов Подсчет Карта «горячая» Доп. реальность
6. Окружение CV
• Все виды сенсоров:
• Audio, Video, Image, IR, Stereo, Electro-magnetic, Sonar, Laser etc
• Может использоваться практически под любым
HW/SW:
• PC: Desktop, Laptop solutions for Windows / Linux / iOS /
Android
• Embedded: DSP, ARM, Stretch, FPGA etc
• Clouds: Supported
7. Тренды
• CV решения на SoC (System-on-a-Chip) растут быстро
• Аналоговые камеры заменяются на IP cams
• Низкоеразрегение at 5..15 FPS заменяется на HD/Full
HD video at high 25..30+ FPS
• Grayscale данные заменяются на Color
• CV алгоритмы становятся более CPU greedy
• More GPU HW platforms now available for CV
applications
• Clouds support becomes an usual requirement
10. CV Standard
• Khronos OpenVX Computer Vision Standard
Finalized (by October 20, 2014)
11. Image Processing: Color spaces
• General color spaces are:
• 1. Red, Green, Blue
• 2. Hue, Saturation, Value(Brightness)
тон, насыщенность, значение
• 3. Grayscale
12. Image Processing:
Analyze images
Обработка изображений — любая форма
обработки информации, для которой
входные данные представлены
изображением, например, фотографиями
или видеокадрами. Обработка изображений
может осуществляться как для получения
изображения на выходе (например,
подготовка к полиграфическому
тиражированию, к телетрансляции и т. д.),
так и для получения другой информации
(например, распознание текста, подсчёт
числа и типа клеток в поле микроскопа и т.
д.). Кроме статичных двухмерных
изображений, обрабатывать требуется
15. Image processing: Thresholding (3/3) -
Otsu's method
• The adaptive thresholding is more effectively method than simple.
• But exist a method of choise constant threshold, that is most effective in the cases of bimodal image (In
simple words, bimodal image is an image whose histogram has two peaks). This name is Otsu’s Binarization.
• Information about OpenCV futures thresholding: http://opencv-python-
tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html
Метод Оцу (англ. Otsu's method) — это алгоритм вычисления порога
бинаризации для полутонового изображения, используемый в области
компьютерного распознавания образов и обработки изображений.
17. Image processing:
matrix filtering
• The main operator is convolution
of matrices []. The first
argument is target region of
image. The second part is
Convolution kernel (filter).
• Convolution kernel runs
throughout the image. And we
need to solve a problem with
boundary elements convolution.
• This solve with making borders
for images:
• 1. Adds a constant colored border.
• 2. Make border as a mirror
reflection of the border elements
18. Image processing: Smoothing
(1/6)
• Target: smooth image for easy
object detection. Remove noise
from image.
• Get more information about OpenCV features of Smoothing: http://
opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_f
iltering/py_filtering.html
20. Image processing: Smoothing
(3/6) - Median filter
• 2. Median filter.
Effectively remove pepper-salt noise.
We take pixel and area around, find out
median (sorting, min(array)), replace
source pixel value by median
21. Image processing: Smoothing
(4/6) - Gaussian filter
,
•
Фильтр Гаусса (Gaussian filter)
обычно используется в цифровом
виде для обработки двумерных
сигналов (изображений) с целью
снижения уровня шума.
Фильтр размытия по Гауссу имеет сложность
O(hi * wi * n *n), где hi, wi – размеры
изображения, n – размер матрицы (ядра
фильтра). Данный алгоритм можно
оптимизировать с приемлемым качеством.
Квадратное ядро (матрицу) можно заменить
двумя одномерными: горизонтальным и
вертикальным. Для размера ядра 5 они будут
иметь вид:
Фильтр применяется в 2 прохода: сначала
горизонтальный, а потом к результату
вертикальный (или на оборот).
22. Image processing: Smoothing (5/6)
– bilateral filtering
Bilateral filtering. Effectively
remove Gaussian noise with
preserve a borders. It consist
of two parts. Right is a
Gaussian, and left is deep fall
Функция сверки – объёмная
Те мы выберем ядро как
Функцию среза от объемной
двусторонний фильтр является нелинейным, находящим границы, удаляющий
шум и сглаживающий фильтром для изображений. Значение интенсивности
каждого пикселя в изображении заменяется средневзвешенным значением
интенсивности от соседних пикселей.
23. Image processing: Smoothing
(6/6) - Kalman filter
Фиильтр Каилмана — эффективный рекурсивный фильтр,
оценивающий вектор состояния динамической системы,
используя ряд неполных и зашумленных измерений.
Универсальный фильтр Удаления “Гаус шума”.
Используется для улучшения разрешения изображения.
• For more information about Kalman filter read: http://www.bzarg.com/p/how-a-kalman-filter-works-in-pictures/, http://
www.computeroptics.smr.ru/KO/PDF/KO38-1/380117.pdf.
25. • 1. Erosion (эрозия) ‘’ [Image Area & Kernel] – returns 1 if
all elements of image Area is 1, else 0.
->
• 2. Dilation (расширение) ‘’ [Image Area | Kernel] –
returns 1 if exist element of image Area is 1, else 0.
->
Image processing: Mathematical
morphology (2/5)
26. • 3. Opening is just another name of erosion
followed by dilation. It is useful in removing
noise, as we explained above.
• 4. Closing is reverse of Opening, Dilation
followed by Erosion. It is useful in closing small
holes inside the foreground objects, or small black
points on the object.
Image processing: Mathematical
morphology (3/5)
27. • 5. Morphological Gradient is the difference
between dilation and erosion of an image. The
result will look like the outline of the object.
• 6. Inner Bound is the difference between image
and erosion.
• 7. Outer Bound is the difference between dilation
and image.
Image processing: Mathematical
morphology (4/5)
29. •Target: Find image
gradients and edges
• Get more information about OpenCV features of Gradients:
http://opencv-python-tutroals.readthedocs.org/en/latest/p
y_tutorials/py_imgproc/py_gradients/py_gradients.html
Image processing: Gradients
(1/4)
30. •
Image processing: Gradients (2/4)
Оператор Собеля
Оператор Собеля — дискретный дифференциальный оператор,
вычисляющий приближённое значение градиента яркости
изображения. Результатом применения оператора Собеля в
каждой точке изображения является либо вектор градиента
яркости в этой точке, либо его норма. Используется в области
обработки изображений, в частности, часто применяется в
алгоритмах выделения границ.
31. • The Sobel-Feldman does not have perfect rotational
symmetry. Scharr looked into optimizing this property.
• 2. Sharr filter is like a Sobel operator, but Gx and Gy
matrices are:
•
Image processing: Gradients (3/4)
Оператор Щарра
Оператор Собеля сглаживает паразитные эффекты на изображении,
вызываемые чисто центрально-дифференциальным оператором, но не
обладает полной вращательной симметрией. Щарр исследовал
улучшение этого свойства и пришёл к выводу, что лучшие результаты
даёт другое ядро свертки ядро
32. ••
Image processing: Gradients(4/4) Оператор
Лапласа
Операитор Лапласа (лапласиаин, оператор дельта) —
дифференциальный оператор, действующий в
линейном пространстве гладких функций и
обозначаемый символом Функции F он ставит в
соответствие функцию
в n-мерном пространстве.
33. Image processing: Canny
Оператор Кэнни (детектор границ Кэнни, алгоритм Кэнни) в дисциплине
компьютерного зрения — оператор обнаружения границ изображения.
Основные этапы алгоритма:
• Сглаживание. Размытие изображения для удаления шума.
• Поиск градиентов. Границы отмечаются там, где градиент изображения приобретает максимальное
• значение.
• Подавление немаксимумов. Только локальные максимумы отмечаются как границы.
• Двойная пороговая фильтрация. Потенциальные границы определяются порогами.
• Трассировка области неоднозначности. Итоговые границы определяются путём подавления
• всех краёв,
несвязанных с определенными (сильными) границами.
35. Task Definition
• Indoor camera is looking at secure area
• Intrusion Area is defined at scene
• We need Video Analytics system to:
1. Record video data related to any activity that occurs at
scene
2. Detect and report any suspicious activity in Intrusion area
3. If person/human had occurred in intrusion area do
recognition whether it is possible
37. Task #1: Detect Any Activity At
Scene
• The simplest way for completion of this
task is: prepare Near Frames Difference
(NFD) image
38. Task #1: Detect Any Activity At
Sceneframe difference
is taken from the
current frame and
previous frame
NFD
thresholding is
done using the
Otsu’s method.
perform the morphological
operations to remove the noise
present in the image (erosion and
dilation ). We used median filter on
the thresholder image
Centroid and
Bounding Box on
detected vehicle
39. Task #1: Detect Any Activity At
Scene
• Approach A (fast & not robust):
• Where ‘sensitivityTheshold’ specifies how big absolute value of NFD image
pixel should be for recognizing it as significant difference
• Where ‘MinMotionThresholdPerc’ specifies: what is the minimal % of scene
change shall be recognized as Motion at Scene event
rchresholdPeMinMotionT
widthheight
SumNonZero
ctedMotionDete
yThresholdsensitivitcolrowNFDPixSumNonZero
height
row
width
col
)%100(
),(
1 1
40. Task #1: Detect Any Activity At
Scene• Approach B (still fast & more robust):
• compute NFD image & make its binary version NFDBin using ‘sensitivityThreshold’
value (see approach A for details)
• Detect all blobs (red, green) using segmentation approach applied over NFDBin
image; do dilate/erode operation if needed; filter out all blobs that have
insignificant size (red) and pass other(green)
• Report Motion At Scene event if:
• either # Sum of left Blobs area exceeded some MinSceneChangeThr OR
• At least one blob that has reasonable size was detected
The thresholding is done using the Otsu’s method.
41. Task #1: Detect Any Activity At
Scene
• Important! There are several approaches available for
NFD image computation:
• Based on usage of cyclic images buffer and computation of
Near Frame Difference between the most old and most recent
image in the buffer
• Based on update at every frame of every pixel of M_HISTORY
image with say ‘0’ if motion was observed for some pixel or
doing pix(r,c)++ otherwise
NFDBin image then can be prepared by using threshold function
applied to M_HISTORY:
NFDBin(r,c) = (M_HISTORY(r,c)> FrmThr) ? 255: 0M_HISTORY image
new motion – white
previous motion – value (we
forgot in time)
Pre previous motion – become
more dark
42. Task #2: Detect Suspicious Activity in
Intrusion Area
• At first it is needed to define what ‘suspicious’ means; not
every activity is suspicious, for ex.:
• Shadows – static and dynamic are OK
• Pets are OK
• Office Illumination ON/OFF is OK
• Customer recognizes activity as suspicious if:
• A person without granted access permissions entered Intrusion
area
• ANY person presence in Intrusion area for more than 3 seconds
43. Task #2: Sub-task Shadow
Suppression
• There are two
types of shadows:
• Static: from static
objects such as
trees, columns,
barriers etc (these
still can change
position over time)
• Dynamic: from
moving, i.e. non-
stationary objects
• Usually Shadow
suppression is
performed in HSV
(preferred) or YUV
(usually used)
color spaces
44. Task #2: Sub-task Shadow
Suppression
• For Shadow
Suppression
(usually) three
images are
used:
• BG: Reference
frame, i.e.
Background
frame
• CUR: Current
frame
• FG:
Foreground/Mot
ion mask image
• Processing is
45. Task #2: Sub Task - Pets
detection
• Simple rejection of false
detections by classifying
them as pets can be
done using invalidation
by object size, w/h
proportions etc
• Advanced detection of
pets can be performed
using classifiers
preliminary trained for
pets: cats/dogs/birds
detection; such
classifiers if ran for input
image might return
46. Task #2: Sub Task – Illumination
changes support
• System shall not generate
false alarms if overall
scene intensity drastically
changed in a moment, i.e.
lights were turned
ON/OFF/TRIMMED
• Such behavior can be
implemented if % of
changed pixels at NFD
image exceeded some
very high level say
90..95%; so if such
change happened then in
simple case no need to
generate False Intrusion
47. Task #2: Detect Suspicious
Activity
• People detection sub-task:
• The quickest but inaccurate
yet approach is to generate
Intrusion events for all
objects from not allowed (i.e
“ignore”) list
• Another simple approach is
to try to detect a person
using check for object
sizes/proportions etc
• More advanced approach is
to train classifier for people
detection so it will return
object BBOX if such
happened in Region of
48. Task #2: Do Validation
• As per requirement
not every people
intrusion requires
Event generation –
people from White list
are allowed to enter
• Person identification
can be done by
sequential running of
Face Detector and
Face Recognition
approaches