PjE – Projet Encadré IVI Semaine 3 : introduction au...

26
Master Informatique – Projet Encadré IVI 1 PjE – Projet Encadré IVI Semaine 3 : introduction au traitement d'images avec OpenCV Master Informatique : http://www.fil.univ-lille1.fr Spécialité IVI : http://master-ivi.univ-lille1.fr

Transcript of PjE – Projet Encadré IVI Semaine 3 : introduction au...

Page 1: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 1

PjE – Projet Encadré IVISemaine 3 : introduction au traitement

d'images avec OpenCV

Master Informatique : http://www.fil.univ-lille1.frSpécialité IVI : http://master-ivi.univ-lille1.fr

Page 2: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 2

Plan du cours

1 – Analyse des images numériques

Image numériqueDémarche globale d'analyse d'une imagePré-traitements, segmentation, post-traitements

2 – Transformations d'images

Différents types de transformationsHistogrammeTransformations ponctuelles pour l'amélioration du contraste

3 – Traitement d'images avec OpenCV

Présentation de la bibliothèquePremiers programmesInterfaces C++ et pythonAccès aux pixels

Références

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 3: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 3

Image numérique : image en niveaux de gris

Double discrétisation

Échantillonnage de l'espace (pixel = picture element)Quantification de l'intensité reçue en chaque pixel

95 93 87 83 80 73 72 67 63

105 100 94 91 86 80 75 73 67

116 105 102 98 93 86 81 76 73

124 116 110 106 96 92 87 81 77

128 123 116 113 105 95 90 85 82

135 131 125 119 112 103 99 92 86

142 140 135 126 118 110 106 100 93

147 144 142 133 126 117 111 104 95

154 151 149 141 129 124 119 110 100

0,0 x

y

752

480

y=402

x=445

0                          255

Exemple : codage sur 8 bits échelle des niveaux de gris discrets

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 4: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 4

Image numérique : représentations

Plane(standard)

Surfacique

Courbes deniveaux

Profil deniveaux

d'après Andrey

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 5: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 5

Image numérique : image en couleurs

Image couleur

Plusieurs canaux ou plans de composantesEx.: codage en R, G, B Ex. : codage sur 8 bits  cube des couleurs 

http://www.morecrayons.com/palettes/webSmart/colorcube.php

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 6: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 6

Analyse d'image

But

Extraire d'une image des descripteurs quantitatifs des objets représentés.

Exemples :

Nombre/ID Position      Dimension         Forme/Orientation ...

1 2

3 4

Analyse

Image 1. x=105.2, y=45.5, S=21302. x=353.7, y=28.3, S=18303. x=134.9, y=303.2, S=26404. x=320.3, y=312.6, S=1876

Mesures

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 7: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 7

Segmentation (1/2)

Généralités

But : distinguer les objets d'intérêt du fondet identifier ceux-ci.Principe :

distinguer les objets du fond (binarisation) = partition de l'image en régions homogènes. 2 approches duales :

régions : utilisation d'une mesure d'homogénéité Ex. niveau de gris (intensité), couleur, texture, ...Permet de classifier les pixelscontours : détection des contours des objets

individualiser chaque objet

RemarqueÉtape clé pour l'analyse, souvent délicate  nombreuses méthodes

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 8: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 8

Segmentation (2/2)

Exemple

Binarisation par seuillage du niveau de gris

Transformation des niveaux t : i  i' = t(i)Binarisation : t(i) = 0 si i < S , t(i) = 255 si i  S

Identification des objets par étiquetage en composantes connexes

Un objet correspond à un ensemble de pixels connexes dans l'image binaire (composantes connexes)Attribution d'une étiquette (label) propre à chaque composante connexe

Étiquettes numériques

Étiquettes en (fausses) couleurs

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 9: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 9

Segmentation et analyse

Résumé

Problème :

Image initiale dégradée (bruit, faible contraste, illumination variable, ...) segmentation délicate, image segmentée difficilement exploitableNécessité de

pré-traitements pour améliorer l'image initialepost-traitements de l'image segmentée

Analyse

Image

1. x=105.2, y=45.52. x=353.7, y=28.33. x=134.9, y=303.24. x=320.3, y=312.6

MesuresImage segmentée

Image étiquetée

Étiquetage en CC

Segmentation

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 10: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 10

Pré-traitements et post-traitements

Pré-traitements

Correction de la géométrie(rectification)Outils : basés sur l'interpolation

Amélioration du contrasteOutils : basés sur l'histogramme

Réduction du bruitOutils : filtres de voisinage

Post-traitementsOutils : filtres morphologiques

Éliminationdes trous dans les objetsdes artefacts dans le fond

Fusion d'objets scindésDivision d'objets fusionnés

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 11: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 11

Transformations d'images : principe et types (1/2)

Principe

Changer la valeur de chaque pixel d'une image I pour obtenir une nouvelle image I'. Cette image résultat a même taille que I, mais des propriétés plus intéressantes.

Notation

La transformation est notée t :

Types de transformations

Ponctuelles (ou pixel à pixel) : la nouvelle valeur I'(x,y) est obtenue à partir de I(x,y) seulement.Locales (ou de voisinage) : la nouvelle valeur I'(x,y) est obtenue à partir de l'ensemble des valeurs initiales I(V (x,y)) dans un voisinage autour du

pixel de coordonnées (x,y).Globales : la nouvelle valeur I'(x,y) est obtenue à partir de l'ensemble des valeurs de l'image initiale I.

I N x×N yt

I ' N x×N y

Histogramme Transformations Amélioration du contraste Opérations algébriquesAnalyse des images Transformations d'images Bibliothèque OpenCV

Page 12: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 12

Transformations d'images : principe et types (2/2)

Transformations ponctuelles

Ex. seuillage, ajustement luminosité/contraste

opérations algébriques, manip. d'histogramme

Transformations locales

Ex. filtrage

Transformations globales

Ex. transformation dans l'espace de Fourier

I x , y t

I ' x , y =t I x , y

I x , y t

I ' x , y =t I

x

y

x

y

t

x

y

t

I I'

I x , y t

I ' x , y =t I V x , y

x

y

x

y

t

V x , y

I I'

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 13: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 13

Histogramme : définition

Définition et notation

Distribution statistique des niveaux de l'image. h(i) = nombre de pixels de l'image ayant le niveau de gris i.

I 100×100

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 14: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 14

Histogramme : interprétation

Informations issues de l'histogramme

luminance de l'image : moyenne des niveaux de gris :

dynamique de l'image : nombre de niveaux [imin

 , imax

] réellement présents.

contraste de l'image : estimé par l'écart-type s.

=1

N x⋅N y∑i=0

255

i⋅hi

0                 =143.7       2550     =76.4                   255

500

0

500

00 i

min=3                       i

max=2550   i

min=66          i

max=191  255

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 15: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 15

Transformations ponctuelles et histogramme

LUT (Look-Up Table)

Table de correspondance définissant la transformation t des niveaux de gris entre l'image initiale et l'image finaleCette transformation change la distribution statistique des niveaux de gris, caractérisée par l'histogramme de chaque image

Utilisation (ex.)

Rehaussementdu contraste parexpansion de la dynamique

i '= 255imax−i min

i−i minavec

i−imin

imax−imin∈[0,1]

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 16: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 16

OpenCV : introduction (1/2)

Présentation générale

Qu'est-ce ?Open Source Computer Vision LibraryBibliothèque open source de traitement des images numériquesProjet initié par Intel (en 1999, actuellement 4.1.1) Téléchargeable sur https://opencv.orgFortement orientée temps réel

écrite en C et C++optimisée pour les processeurs multi-cœurs

Multi-plateformes : disponible pour Linux/Mac, Windows, iOS et AndroidMulti-langages : python, Java, Matlab (binding), C#, Perl, Ruby (wrapper)

Que contient-elle ?Des fonctionnalités (structures, 2500+ routines) pour bâtir rapidement des applications autour de la vision par ordinateurExemples d'utilisation : traitements de bas niveau (filtrage, ...), détection de visages, reconnaissance et suivi d'objets en mouvement, ...

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 17: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 17

OpenCV : introduction (2/2)

Fonctionnalités (modules)

Bas et moyen niveauxLecture/écriture d'images et de séquences vidéo (imgcodecs et videoio)Représentation et manipulations de tableaux et autres structures (core) : région d'intérêt (ROI), analyse (ACP, LDA), transformées (FFT, DCT), ...Traitement des images (imgproc) : conversions, filtrage, transformations géométriques, seuillage, histogrammes, dessin, détection de contours, ... Détection d'objets et de caractéristiques (objdetect et features2d)

Haut niveauInterface graphique (huighgui) et visualisation (viz et plot)Détection et suivi (tracking) d'objets (video), dont visages (face)Analyse du mouvement (imgproc/motion, video/motion, optflow)Calibrage (calibration) de caméra et reconstruction 3D (calib3d)Mise en correspondance stéréoscopique (stereo matching) (stereo)Apprentissage (machine learning), dont réseaux de neurones (ml et dnn)Traitement flou (fuzzy processing) (fuzzy)

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 18: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 18

OpenCV : premiers programmes (1/2)

Lecture et affichage d'une image# Importer les paquets nécessairesimport cv2, sys

# Lire l'image lena.png et la stocker dans un tableauimage = cv2.imread("lena.png")

if image is None: # cv2.imread ne lève pas d'exception mais retourne None si échec sys.exit("Impossible de charger l'image lena.png")

# Créer une fenêtre nommée Exemple1, dont la taille s'adapte à son contenucv2.namedWindow("Exemple1", cv2.WINDOW_AUTOSIZE);

# Afficher l'image lena dans la fenêtre Exemple1cv2.cvShowImage("Exemple1", image);

# Attendre que l'utilisateur appuie sur une touchecv2.waitKey();

# Détruire la fenêtrecv2.destroyWindow("Exemple1")

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 19: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 19

OpenCV : premiers programmes (2/2)

Conversion et binarisation d'une image# Importer les paquets nécessairesimport cv2

# Charger l'image d'entrée, créer une fenêtre et y afficher l'imageinp = cv2.imread("lena.png")

cv2.namedWindow("Exemple2-in")cv2.imshow("Exemple2-in", inp)cv2.waitKey()

# Convertir l'image couleur d'entrée en image à ndginp = cv2.cvtColor(inp, cv2.COLOR_BGR2GRAY)cv2.imshow("Exemple2-in", inp)

# Créer une image de sortie binaire avec un seuil de 100seuil, out = cv2.threshold(inp, 100, 255, cv2.THRESH_BINARY)

# Créer une fenêtre et afficher l'image de sortiecv2.namedWindow("Exemple2-out")cv2.imshow("Exemple2-out", out)

# Détruire les fenêtrescv2.waitKey()cv2.destroyAllWindows()

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 20: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 20

OpenCV : API C++

Point{int x, int y} : point (pixel) du planPoint2f : idem avec nombres de type doublePoint3f : 3 nombres réels (dont coordonnée z)

Size{int width, int height} : taille d'une zone rectangulaire

Rect{int x, int y, int width, int height} : zone rectangulaire

Ex. de méthode : aRect.contains(aPoint)

Range{int start, int end} : plage d'entiers consécutifs

Vec : conteneur générique pour 2 à 4 entiers ou 2 à 6 réels

Ex. d'utilisation : valeur RGB (dans un Vec<uchar,4>)

Mat{int rows, int cols, int type, …} : tableau multi-dimensionnel Ex. d'utilisation : image

Types de données : constante CV_<profondeurEnBits>{S|U|F}C<nbCanaux>CV_32FC1 : flottants sur 32 bits (1 seul canal)CV_8UC3 : triplets d'entiers non signés sur 8 bits (3 canaux)

Ex. :  Mat img(Size(320,240),CV_8UC3); // image couleur de 320x240 pixels

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 21: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 21

OpenCV : API Python

Description

Très similaires à l'API C++ ; 2 possibilités : cv (OpenCV < 3.0) ou cv2cv : mêmes types qu'en C++cv2 : utilisation d'objets python

Utilisation de cv2

Importation du paquet : import cv2Appel de fonction : [var1, var2,… = ]cv2.func(arg1, arg2,…)

Analyse des images Transformations d'images Bibliothèque OpenCV

API cv cv2

Image Objet Mat Objet ndarray (module numpy)

Accès pixel aMat.at<type>(r,c) ou aMat.data[index]

anArray[r,c]

Région d’intérêt(ROI)

Mat roi(aMat,aRect) roi=anArray[rs:re,cs:ce] (slicing)

ContoursfindContours(…)

Objets vector<vector<Point>> (sommets), vector<Vec4i> (hiérarchie)

list de tableaux numpy (sommets), tableau numpy (hiérarchie)

Page 22: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 22

OpenCV : documentation (1/2)

Ex. : cv2.rectangle(im, (10,10), (50,50), (0,0,255), cv2.FILLED)

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 23: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 23

OpenCV : documentation (2/2)

Ex. : imDst = cv2.cvtColor(imSrc, cv2.COLOR_BGR2RGB)

Analyse des images Transformations d'images Bibliothèque OpenCV

Page 24: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 24

OpenCV : accès aux pixels (1/2)

numpy

module optimisé pour les opérations matriciellesgénéralise l'indexation et le slicing des tableaux pythonfournit une syntaxe proche de Matlab

Manipulation d'une image en niveaux de gris

Lecture : im = cv2.imread("gray.png",cv2.IMREAD_GRAYSCALE)→ tableau d'uint8 [ [ 0 25 50 75] [100 125 150 175] [200 225 250 255] ]

Accès aux pixelsim[1,3] →  175im[0,:] →  array([ 0, 25, 50, 75])im[0:2,1:3] → array([ [ 25, 50], [125, 150]])im[:,-1] = numpy.zeros((1,im.shape[0]))

Analyse des images Transformations d'images Bibliothèque OpenCV

0 1 2 3

0

1

2

Page 25: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 25

OpenCV : accès aux pixels (2/2)

Manipulation d'une image couleur

Lecture : im = cv2.imread("color.png")→ tableau d'uint8 [ [ [ 0 0 255] [ 0 0 127] [ 0 127 127] [ 0 127 0] ] [ [ 0 255 0] [ 0 127 0] [127 127 0] [127 0 0] ] [ [255 0 0] [127 0 0] [127 0 127] [ 0 0 127] ] ]

Attention : plans couleur ordonnés BGRAccès aux pixels

im[1,3] →  array([127, 0, 0])im[:,:,2] → array([[255, 127, 127, 0], [ 0, 0, 0, 0], [ 0, 0, 127, 127]])

Analyse des images Transformations d'images Bibliothèque OpenCV

0 1 2 3

0

1

2

Page 26: PjE – Projet Encadré IVI Semaine 3 : introduction au ...master-ivi.univ-lille1.fr/fichiers/Cours/pje-semaine-3-opencv.pdf · OpenCV : introduction (1/2) Présentation générale

Master Informatique – Projet Encadré IVI 26

OpenCV : références

Livres

G. Bradski & A. Kaehler, « Learning OpenCV », O'Reilly Press (2008)PDF : https://huit.re/xRrpg5UK, sources C : https://huit.re/g1FtHqNYJ. E. Solem, « Programming Computer Vision with Python », O'Reilly Press (2012), http://programmingcomputervision.com

Ressources en ligne

Référence complète (4.0.1) : https://docs.opencv.org/4.0.1/modules.htmlWiki : https://github.com/opencv/opencv/wikiTutoriels et exemples (dont installation)

http://deusyss.developpez.com/tutoriels/Python/python-en-bref/#LV-Qhttp://docs.opencv.org/4.0.1/d6/d00/tutorial_py_root.htmlhttps://www.pyimagesearch.com/practical-python-opencvhttp://opencvpython.blogspot.frLearning OpenCV by Examples : https://huit.re/UgD8NP8N

Tutoriel sur la vision utilisant OpenCV (en français) : http://bit.ly/2zqYsYY

Analyse des images Transformations d'images Bibliothèque OpenCV