0% ont trouvé ce document utile (0 vote)
0 vues17 pages

Introduction à la Computer Vision

Ce document est une introduction à la Computer Vision, abordant des concepts de base, l'installation des bibliothèques nécessaires, et des manipulations d'images. Il couvre également des transformations d'images, la préparation des données, et l'utilisation de réseaux de neurones convolutifs (CNN) avec Keras. Enfin, un projet pratique complet est proposé pour appliquer les connaissances acquises.

Transféré par

ndeyekharyniang11
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
0 vues17 pages

Introduction à la Computer Vision

Ce document est une introduction à la Computer Vision, abordant des concepts de base, l'installation des bibliothèques nécessaires, et des manipulations d'images. Il couvre également des transformations d'images, la préparation des données, et l'utilisation de réseaux de neurones convolutifs (CNN) avec Keras. Enfin, un projet pratique complet est proposé pour appliquer les connaissances acquises.

Transféré par

ndeyekharyniang11
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd

Introduction à la Computer Vision

Table des Matières


1. Introduction et Concepts de Base
2. Installation et Configuration
3. Manipulations Basiques d'Images
4. Transformations d'Images
5. Préparation des Données
6. Introduction aux Réseaux de Neurones Convolutifs (CNN)
7. Construction d'un Modèle CNN avec Keras
8. Projet Pratique Complet

1. Introduction et Concepts de Base


Qu'est-ce que la Computer Vision ?
La computer vision est une branche de l'intelligence artificielle qui permet aux ordinateurs
d'interpréter et de comprendre les images numériques. Elle simule la vision humaine pour extraire des
informations utiles des images.
Applications courantes :
 Reconnaissance faciale
 Détection d'objets
 Classification d'images
 Diagnostic médical
 Voitures autonomes
Représentation numérique d'une image :
 Image en niveaux de gris : matrice 2D (hauteur × largeur)
 Image couleur (RGB) : matrice 3D (hauteur × largeur × 3 canaux)
 Chaque pixel a une valeur entre 0 et 255

2. Installation et Configuration
1. # Installation des bibliothèques nécessaires
2. pip install pillow
3. pip install matplotlib
4. pip install numpy
5. pip install tensorflow
6. pip install scikit-learn
7. pip install opencv-python # Pour les opérations avancées seulement
8. # Imports nécessaires
9. import numpy as np
10. import [Link] as plt
11. from PIL import Image, ImageFilter, ImageEnhance, ImageOps
12. import tensorflow as tf
13. from tensorflow import keras
14. from [Link] import layers
15. import os
16.

3. Manipulations Basiques d'Images


3.1 Chargement et Affichage d'Images
1. # Charger une image avec PIL (très simple !)
2. img_pil = [Link]('chemin/vers/[Link]')
3.
4. # Convertir en array numpy pour les calculs
5. img_array = [Link](img_pil)
6.
7. # Affichage avec matplotlib
8. [Link](figsize=(12, 5))
9.
10. [Link](1, 2, 1)
11. [Link](img_pil) # On peut afficher directement l'objet PIL
12. [Link]('Image avec PIL')
13. [Link]('off')
14.
15. [Link](1, 2, 2)
16. [Link](img_array) # Ou l'array numpy
17. [Link]('Image comme Array NumPy')
18. [Link]('off')
19.
20. [Link]()
21.
22. # Alternative : afficher directement l'image PIL
23. img_pil.show() # Ouvre l'image dans le visualiseur par défaut
24.
3.2 Propriétés de l'Image
1. # Informations de base avec PIL
2. print("=== Informations PIL ===")
3. print(f"Taille : {img_pil.size}") # (largeur, hauteur)
4. print(f"Mode : {img_pil.mode}") # RGB, RGBA, L (grayscale), etc.
5. print(f"Format : {img_pil.format}") # JPEG, PNG, etc.
6.
7. # Informations détaillées avec NumPy
8. print("\n=== Informations NumPy ===")
9. print(f"Dimensions : {img_array.shape}")
10. print(f"Hauteur : {img_array.shape[0]} pixels")
11. print(f"Largeur : {img_array.shape[1]} pixels")
12. if len(img_array.shape) == 3:
13. print(f"Nombre de canaux : {img_array.shape[2]}")
14.
15. print(f"Type de données : {img_array.dtype}")
16. print(f"Valeur min : {img_array.min()}")
17. print(f"Valeur max : {img_array.max()}")
18. print(f"Taille en mémoire : {img_array.nbytes} bytes")
19.
3.3 Conversion entre Modes d'Images
1. # Conversion avec PIL (beaucoup plus simple qu'OpenCV !)
2.
3. # Conversion en niveaux de gris
4. img_gray = img_pil.convert('L')
5.
6. # Conversion en RGBA (avec canal alpha/transparence)
7. img_rgba = img_pil.convert('RGBA')
8.
9. # Conversion en mode palette (256 couleurs)
10. img_palette = img_pil.convert('P')
11.
12. # Affichage des différentes conversions
13. [Link](figsize=(15, 10))
14.
15. images_modes = [
16. (img_pil, 'RGB Original'),
17. (img_gray, 'Niveaux de Gris (L)'),
18. (img_rgba, 'RGBA (avec Alpha)'),
19. (img_palette, 'Palette (P)')
20. ]
21.
22. for i, (img, title) in enumerate(images_modes, 1):
23. [Link](2, 2, i)
24. if [Link] == 'L': # Niveaux de gris
25. [Link](img, cmap='gray')
26. else:
27. [Link](img)
28. [Link](f'{title} - Mode: {[Link]}')
29. [Link]('off')
30.
31. plt.tight_layout()
32. [Link]()
33.
34. # Conversion vers array numpy si nécessaire
35. gray_array = [Link](img_gray)
36. print(f"Image en niveaux de gris - Shape: {gray_array.shape}")
37.

4. Transformations d'Images
4.1 Redimensionnement
1. # Redimensionnement avec PIL (très simple !)
2. def resize_image_pil(image, width, height):
3. """Redimensionne une image PIL"""
4. return [Link]((width, height))
5.
6. # Différentes méthodes de redimensionnement
7. img_resized_default = img_pil.resize((224, 224)) # Méthode par défaut
8. img_resized_lanczos = img_pil.resize((224, 224), [Link]) # Haute qualité
9. img_resized_nearest = img_pil.resize((224, 224), [Link]) # Rapide
10.
11. # Redimensionnement en conservant les proportions
12. def resize_with_aspect_ratio(image, max_size=224):
13. """Redimensionne en conservant le ratio hauteur/largeur"""
14. [Link]((max_size, max_size), [Link])
15. return image
16.
17. img_thumbnail = img_pil.copy() # Copie car thumbnail modifie l'image originale
18. img_thumbnail.thumbnail((224, 224))
19.
20. # Affichage des différents redimensionnements
21. [Link](figsize=(15, 10))
22.
23. resize_examples = [
24. (img_pil, f'Originale {img_pil.size}'),
25. (img_resized_default, f'Redim. défaut {img_resized_default.size}'),
26. (img_resized_lanczos, f'Redim. Lanczos {img_resized_lanczos.size}'),
27. (img_thumbnail, f'Thumbnail {img_thumbnail.size}')
28. ]
29.
30. for i, (img, title) in enumerate(resize_examples, 1):
31. [Link](2, 2, i)
32. [Link](img)
33. [Link](title)
34. [Link]('off')
35.
36. plt.tight_layout()
37. [Link]()
38.
4.2 Rotation et Retournement
1. # Transformations géométriques avec PIL
2.
3. # Rotations
4. img_rotate_45 = img_pil.rotate(45) # Rotation simple
5. img_rotate_45_expand = img_pil.rotate(45, expand=True) # Agrandit pour éviter la coupure
6.
7. # Retournements (très simple avec PIL !)
8. img_flip_h = img_pil.transpose([Link].FLIP_LEFT_RIGHT) # Horizontal
9. img_flip_v = img_pil.transpose([Link].FLIP_TOP_BOTTOM) # Vertical
10.
11. # Autres transformations
12. img_rotate_90 = img_pil.transpose([Link].ROTATE_90)
13. img_rotate_180 = img_pil.transpose([Link].ROTATE_180)
14.
15. # Affichage des transformations
16. [Link](figsize=(15, 12))
17.
18. transformations = [
19. (img_pil, 'Originale'),
20. (img_rotate_45, 'Rotation 45°'),
21. (img_rotate_45_expand, 'Rotation 45° (expand)'),
22. (img_flip_h, 'Retournement Horizontal'),
23. (img_flip_v, 'Retournement Vertical'),
24. (img_rotate_90, 'Rotation 90°')
25. ]
26.
27. for i, (img, title) in enumerate(transformations, 1):
28. [Link](2, 3, i)
29. [Link](img)
30. [Link](title)
31. [Link]('off')
32.
33. plt.tight_layout()
34. [Link]()
35.
4.3 Filtres et Effets avec PIL
1. # PIL a des filtres intégrés très pratiques !
2.
3. # Appliquer différents filtres
4. img_blur = img_pil.filter([Link])
5. img_detail = img_pil.filter([Link])
6. img_edge = img_pil.filter(ImageFilter.FIND_EDGES)
7. img_sharpen = img_pil.filter([Link])
8. img_smooth = img_pil.filter([Link])
9. img_emboss = img_pil.filter([Link])
10.
11. # Filtres avec paramètres
12. img_gaussian = img_pil.filter([Link](radius=3))
13. img_unsharp = img_pil.filter([Link](radius=2, percent=150))
14.
15. # Affichage des filtres
16. [Link](figsize=(15, 12))
17.
18. filters_examples = [
19. (img_pil, 'Originale'),
20. (img_blur, 'Flou'),
21. (img_gaussian, 'Flou Gaussien'),
22. (img_detail, 'Détail'),
23. (img_edge, 'Contours'),
24. (img_sharpen, 'Netteté'),
25. (img_smooth, 'Lissage'),
26. (img_emboss, 'Embossage')
27. ]
28.
29. for i, (img, title) in enumerate(filters_examples, 1):
30. [Link](2, 4, i)
31. if 'Contours' in title:
32. [Link](img, cmap='gray')
33. else:
34. [Link](img)
35. [Link](title)
36. [Link]('off')
37.
38. plt.tight_layout()
39. [Link]()
40.
4.4 Ajustements de Couleur et Luminosité
1. # PIL facilite les ajustements d'image avec ImageEnhance
2.
3. # Créer les objets d'amélioration
4. brightness_enhancer = [Link](img_pil)
5. contrast_enhancer = [Link](img_pil)
6. color_enhancer = [Link](img_pil)
7. sharpness_enhancer = [Link](img_pil)
8.
9. # Appliquer différents facteurs
10. img_bright = brightness_enhancer.enhance(1.5) # Plus lumineux
11. img_dark = brightness_enhancer.enhance(0.7) # Plus sombre
12. img_high_contrast = contrast_enhancer.enhance(2.0) # Plus de contraste
13. img_low_contrast = contrast_enhancer.enhance(0.5) # Moins de contraste
14. img_saturated = color_enhancer.enhance(1.5) # Plus saturé
15. img_desaturated = color_enhancer.enhance(0.3) # Moins saturé
16.
17. # Affichage des ajustements
18. [Link](figsize=(15, 12))
19.
20. adjustments = [
21. (img_pil, 'Originale'),
22. (img_bright, 'Plus Lumineux'),
23. (img_dark, 'Plus Sombre'),
24. (img_high_contrast, 'Plus de Contraste'),
25. (img_low_contrast, 'Moins de Contraste'),
26. (img_saturated, 'Plus Saturé'),
27. (img_desaturated, 'Moins Saturé'),
28. (img_gray, 'Niveaux de Gris')
29. ]
30.
31. for i, (img, title) in enumerate(adjustments, 1):
32. [Link](2, 4, i)
33. if title == 'Niveaux de Gris':
34. [Link](img, cmap='gray')
35. else:
36. [Link](img)
37. [Link](title)
38. [Link]('off')
39.
40. plt.tight_layout()
41. [Link]()
42.
43. # Fonction utilitaire pour combiner plusieurs effets
44. def apply_random_effects(image):
45. """Applique des effets aléatoires à une image"""
46. import random
47.
48. # Copie de l'image
49. result = [Link]()
50.
51. # Ajustements aléatoires
52. if [Link]() > 0.5:
53. brightness = [Link](0.8, 1.2)
54. result = [Link](result).enhance(brightness)
55.
56. if [Link]() > 0.5:
57. contrast = [Link](0.8, 1.2)
58. result = [Link](result).enhance(contrast)
59.
60. if [Link]() > 0.5:
61. saturation = [Link](0.8, 1.2)
62. result = [Link](result).enhance(saturation)
63.
64. return result
65.
66. # Exemple d'utilisation
67. random_effect = apply_random_effects(img_pil)
68. [Link](figsize=(10, 5))
69. [Link](1, 2, 1)
70. [Link](img_pil)
71. [Link]('Originale')
72. [Link]('off')
73. [Link](1, 2, 2)
74. [Link](random_effect)
75. [Link]('Effets Aléatoires')
76. [Link]('off')
77. [Link]()
78.

5. Préparation des Données


5.1 Normalisation des Images
1. def normalize_image_pil(image):
2. """Normalise une image PIL (convertit en array et normalise)"""
3. img_array = [Link](image).astype(np.float32)
4. return img_array / 255.0
5.
6. def normalize_image_array(image_array):
7. """Normalise un array numpy"""
8. return image_array.astype(np.float32) / 255.0
9.
10. def standardize_image(image_array):
11. """Standardise l'image (moyenne=0, écart-type=1)"""
12. img_float = image_array.astype(np.float32)
13. return (img_float - img_float.mean()) / img_float.std()
14.
15. # Exemples d'utilisation
16. img_array = [Link](img_pil)
17. img_normalized = normalize_image_pil(img_pil)
18. img_standardized = standardize_image(img_array)
19.
20. print("=== Comparaison des normalisations ===")
21. print(f"Image originale - Min: {img_array.min()}, Max: {img_array.max()}")
22. print(f"Image normalisée - Min: {img_normalized.min():.3f}, Max: {img_normalized.max():.3f}")
23. print(f"Image standardisée - Moyenne: {img_standardized.mean():.3f}, Écart-type: {img_standardized.std():.3f}")
24.
25. # Visualisation
26. [Link](figsize=(15, 5))
27.
28. [Link](1, 3, 1)
29. [Link](img_array.astype(np.uint8))
30. [Link]('Originale (0-255)')
31. [Link]('off')
32.
33. [Link](1, 3, 2)
34. [Link](img_normalized)
35. [Link]('Normalisée (0-1)')
36. [Link]('off')
37.
38. [Link](1, 3, 3)
39. # Pour afficher l'image standardisée, on doit la remettre dans une plage visible
40. img_std_display = (img_standardized - img_standardized.min()) / (img_standardized.max() - img_standardized.min())
41. [Link](img_std_display)
42. [Link]('Standardisée')
43. [Link]('off')
44.
45. plt.tight_layout()
46. [Link]()
47.
5.2 Augmentation de Données avec PIL
1. import random
2.
3. def augment_image_pil(image):
4. """
5. Pipeline d'augmentation de données avec PIL
6. Retourne une liste d'images augmentées
7. """
8. augmented_images = []
9.
10. # Image originale
11. augmented_images.append(('Originale', image))
12.
13. # 1. Rotation aléatoire
14. angle = [Link](-30, 30)
15. rotated = [Link](angle, expand=True)
16. augmented_images.append(('Rotation', rotated))
17.
18. # 2. Retournement horizontal
19. if [Link]() > 0.5:
20. flipped = [Link]([Link].FLIP_LEFT_RIGHT)
21. augmented_images.append(('Retournement', flipped))
22.
23. # 3. Changement de luminosité
24. brightness_factor = [Link](0.7, 1.3)
25. bright_img = [Link](image).enhance(brightness_factor)
26. augmented_images.append(('Luminosité', bright_img))
27.
28. # 4. Changement de contraste
29. contrast_factor = [Link](0.8, 1.2)
30. contrast_img = [Link](image).enhance(contrast_factor)
31. augmented_images.append(('Contraste', contrast_img))
32.
33. # 5. Changement de saturation
34. color_factor = [Link](0.8, 1.2)
35. color_img = [Link](image).enhance(color_factor)
36. augmented_images.append(('Saturation', color_img))
37.
38. # 6. Flou léger
39. blurred = [Link]([Link](radius=[Link](0.5, 2.0)))
40. augmented_images.append(('Flou', blurred))
41.
42. # 7. Recadrage aléatoire (crop)
43. width, height = [Link]
44. crop_size = min(width, height) * 0.8 # 80% de la taille originale
45. left = [Link](0, int(width - crop_size))
46. top = [Link](0, int(height - crop_size))
47. cropped = [Link]((left, top, left + crop_size, top + crop_size))
48. # Redimensionner à la taille originale
49. cropped_resized = [Link]((width, height))
50. augmented_images.append(('Recadrage', cropped_resized))
51.
52. return augmented_images
53.
54. # Appliquer l'augmentation
55. augmented = augment_image_pil(img_pil)
56.
57. # Affichage
58. [Link](figsize=(20, 10))
59. for i, (title, img) in enumerate(augmented):
60. [Link](2, 4, i+1)
61. [Link](img)
62. [Link](title)
63. [Link]('off')
64.
65. plt.tight_layout()
66. [Link]()
67.
68. print(f"Nombre d'images générées : {len(augmented)}")
69.
5.3 Fonction d'Augmentation Avancée
1. def create_augmentation_pipeline(image, num_augmentations=5):
2. """
3. Crée plusieurs versions augmentées d'une image
4. """
5. augmented_images = []
6.
7. for i in range(num_augmentations):
8. # Commencer avec l'image originale
9. aug_img = [Link]()
10.
11. # Appliquer aléatoirement différentes transformations
12. transformations_applied = []
13.
14. # Rotation (probabilité 70%)
15. if [Link]() < 0.7:
16. angle = [Link](-20, 20)
17. aug_img = aug_img.rotate(angle)
18. transformations_applied.append(f"Rot{angle:.1f}°")
19.
20. # Retournement (probabilité 50%)
21. if [Link]() < 0.5:
22. aug_img = aug_img.transpose([Link].FLIP_LEFT_RIGHT)
23. transformations_applied.append("Flip")
24.
25. # Ajustements de couleur (probabilité 80%)
26. if [Link]() < 0.8:
27. # Luminosité
28. brightness = [Link](0.8, 1.2)
29. aug_img = [Link](aug_img).enhance(brightness)
30.
31. # Contraste
32. contrast = [Link](0.9, 1.1)
33. aug_img = [Link](aug_img).enhance(contrast)
34.
35. transformations_applied.append("Color")
36.
37. # Flou léger (probabilité 30%)
38. if [Link]() < 0.3:
39. blur_radius = [Link](0.5, 1.5)
40. aug_img = aug_img.filter([Link](radius=blur_radius))
41. transformations_applied.append("Blur")
42.
43. # Créer le titre
44. title = f"Aug {i+1}: {', '.join(transformations_applied)}" if transformations_applied else f"Aug {i+1}: Original"
45.
46. augmented_images.append((title, aug_img))
47.
48. return augmented_images
49.
50. # Créer un dataset augmenté
51. augmented_dataset = create_augmentation_pipeline(img_pil, num_augmentations=8)
52.
53. # Affichage
54. [Link](figsize=(20, 10))
55. for i, (title, img) in enumerate(augmented_dataset):
56. [Link](2, 4, i+1)
57. [Link](img)
58. [Link](title, fontsize=10)
59. [Link]('off')
60.
61. plt.tight_layout()
62. [Link]()
63.

5.4 Sauvegarde des Images Augmentées


1. def save_augmented_images(original_image, output_folder='augmented_images', num_images=10):
2. """
3. Sauvegarde des images augmentées
4. """
5. import os
6.
7. # Créer le dossier si il n'existe pas
8. [Link](output_folder, exist_ok=True)
9.
10. # Sauvegarder l'image originale
11. original_image.save([Link](output_folder, '[Link]'))
12.
13. # Générer et sauvegarder les images augmentées
14. for i in range(num_images):
15. augmented = create_augmentation_pipeline(original_image, 1)[0][1]
16. filename = f'augmented_{i+1:03d}.jpg'
17. [Link]([Link](output_folder, filename))
18.
19. print(f"Sauvegardé {num_images + 1} images dans '{output_folder}'")
20.
21. # Exemple d'utilisation (décommentez pour exécuter)
22. # save_augmented_images(img_pil, 'mon_dataset_augmente', 20)
23.

6. Introduction aux Réseaux de Neurones Convolutifs (CNN)


6.1 Concepts Théoriques
Convolution
La convolution est une opération mathématique qui applique un filtre (noyau) sur l'image pour extraire
des caractéristiques.
1. # Pour les démonstrations de convolution, on utilise OpenCV car PIL n'a pas cette fonctionnalité
2. import cv2
3.
4. def apply_convolution(image, kernel):
5. """Applique une convolution avec un noyau donné"""
6. # Convertir l'image PIL en array pour OpenCV si nécessaire
7. if hasattr(image, 'convert'):
8. img_array = [Link]([Link]('L')) # Convertir en niveaux de gris
9. else:
10. img_array = image
11.
12. return cv2.filter2D(img_array, -1, kernel)
13.
14. # Différents noyaux pour comprendre la convolution
15. kernels = {
16. 'Détection de contours': [Link]([[-1, -1, -1],
17. [-1, 8, -1],
18. [-1, -1, -1]]),
19. 'Flou': [Link]([[1, 1, 1],
20. [1, 1, 1],
21. [1, 1, 1]]) / 9,
22. 'Netteté': [Link]([[0, -1, 0],
23. [-1, 5, -1],
24. [0, -1, 0]]),
25. 'Détection verticale': [Link]([[-1, 0, 1],
26. [-1, 0, 1],
27. [-1, 0, 1]]),
28. 'Détection horizontale': [Link]([[-1, -1, -1],
29. [ 0, 0, 0],
30. [ 1, 1, 1]])
31. }
32.
33. # Convertir l'image PIL en niveaux de gris pour la démonstration
34. img_gray_array = [Link](img_gray)
35.
36. # Application des noyaux
37. [Link](figsize=(18, 12))
38. [Link](2, 3, 1)
39. [Link](img_gray_array, cmap='gray')
40. [Link]('Image Originale')
41. [Link]('off')
42.
43. for i, (name, kernel) in enumerate([Link](), 2):
44. result = apply_convolution(img_gray_array, kernel)
45. [Link](2, 3, i)
46. [Link](result, cmap='gray')
47. [Link](f'{name}')
48. [Link]('off')
49.
50. plt.tight_layout()
51. [Link]()
52.
53. # Expliquer ce qui se passe
54. print("🔍 Qu'est-ce que la convolution ?")
55. print("- Chaque noyau détecte des caractéristiques spécifiques")
56. print("- Les noyaux de détection de contours mettent en évidence les bords")
57. print("- Les noyaux de flou lissent l'image")
58. print("- Les noyaux directionnels détectent les lignes dans certaines directions")
59.
Visualisation du processus de convolution
1. def visualize_convolution_step(image, kernel, position=(50, 50)):
2. """
3. Visualise une étape de convolution en détail
4. """
5. img_array = [Link]([Link]('L')) if hasattr(image, 'convert') else image
6.
7. # Extraire une petite région autour de la position
8. row, col = position
9. region = img_array[row-1:row+2, col-1:col+2]
10.
11. # Calculer le résultat de la convolution pour cette position
12. result = [Link](region * kernel)
13.
14. # Visualisation
15. fig, axes = [Link](1, 4, figsize=(15, 4))
16.
17. # Image originale avec la région en surbrillance
18. axes[0].imshow(img_array, cmap='gray')
19. rect = [Link]((col-1, row-1), 3, 3, linewidth=2, edgecolor='red', facecolor='none')
20. axes[0].add_patch(rect)
21. axes[0].set_title('Image avec région sélectionnée')
22. axes[0].axis('off')
23.
24. # Région extraite
25. axes[1].imshow(region, cmap='gray')
26. axes[1].set_title(f'Région 3x3\n{region}')
27. axes[1].axis('off')
28.
29. # Noyau
30. axes[2].imshow(kernel, cmap='RdBu', vmin=-2, vmax=2)
31. axes[2].set_title(f'Noyau\n{kernel}')
32. axes[2].axis('off')
33.
34. # Calcul
35. axes[3].text(0.1, 0.7, 'Calcul:', fontsize=12, fontweight='bold')
36. axes[3].text(0.1, 0.5, f'Région × Noyau = {result:.1f}', fontsize=10)
37. axes[3].text(0.1, 0.3, f'Σ(pixel × poids)', fontsize=10)
38. axes[3].set_xlim(0, 1)
39. axes[3].set_ylim(0, 1)
40. axes[3].axis('off')
41. axes[3].set_title('Résultat')
42.
43. plt.tight_layout()
44. [Link]()
45.
46. return result
47.
48. # Démonstration avec le noyau de détection de contours
49. edge_kernel = [Link]([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
50. result = visualize_convolution_step(img_gray, edge_kernel, position=(100, 100))
51. print(f"Résultat de la convolution à cette position : {result:.2f}")
52.
Pooling (Mise en Commun)
1. def max_pooling_demo(image, pool_size=2):
2. """Démontre le max pooling avec visualisation détaillée"""
3.
4. # Convertir en array si nécessaire
5. if hasattr(image, 'convert'):
6. img_array = [Link]([Link]('L'))
7. else:
8. img_array = image
9.
10. height, width = img_array.shape
11. pooled_height = height // pool_size
12. pooled_width = width // pool_size
13.
14. pooled = [Link]((pooled_height, pooled_width))
15.
16. # Appliquer le max pooling
17. for i in range(pooled_height):
18. for j in range(pooled_width):
19. pooled[i, j] = [Link](
20. img_array[i*pool_size:(i+1)*pool_size,
21. j*pool_size:(j+1)*pool_size]
22. )
23.
24. return [Link](img_array.dtype)
25.
26. # Démonstration avec différentes tailles de pooling
27. [Link](figsize=(15, 10))
28.
29. pooling_sizes = [2, 4, 8]
30. img_gray_array = [Link](img_gray)
31.
32. [Link](2, 3, 1)
33. [Link](img_gray_array, cmap='gray')
34. [Link](f'Originale {img_gray_array.shape}')
35. [Link]('off')
36.
37. for i, pool_size in enumerate(pooling_sizes, 2):
38. pooled = max_pooling_demo(img_gray_array, pool_size)
39. [Link](2, 3, i)
40. [Link](pooled, cmap='gray')
41. [Link](f'Max Pooling {pool_size}x{pool_size}\n{[Link]}')
42. [Link]('off')
43.
44. # Comparaison des tailles
45. [Link](2, 3, 5)
46. sizes = [img_gray_array.shape[0]]
47. for pool_size in pooling_sizes:
48. [Link](img_gray_array.shape[0] // pool_size)
49.
50. [Link](range(len(sizes)), sizes, color=['blue', 'orange', 'green', 'red'])
51. [Link]('Réduction de taille')
52. [Link](range(len(sizes)), ['Original', '2x2', '4x4', '8x8'])
53. [Link]('Hauteur (pixels)')
54.
55. [Link](2, 3, 6)
56. params = [s*s for s in sizes]
57. [Link](range(len(params)), params, color=['blue', 'orange', 'green', 'red'])
58. [Link]('Nombre de pixels')
59. [Link](range(len(params)), ['Original', '2x2', '4x4', '8x8'])
60. [Link]('Nombre total')
61.
62. plt.tight_layout()
63. [Link]()
64.
65. print("🔍 Pourquoi le pooling ?")
66. print("- Réduit la taille des données (moins de calculs)")
67. print("- Rend le modèle moins sensible aux petits déplacements")
68. print("- Conserve les caractéristiques importantes")
69. print(f"- Réduction de {img_gray_array.shape} à {max_pooling_demo(img_gray_array, 4).shape}")
70.

7. Construction d'un Modèle CNN avec Keras


7.1 Architecture Simple de CNN
1. def create_simple_cnn(input_shape=(224, 224, 3), num_classes=10):
2. """
3. Crée un CNN simple pour la classification d'images
4.
5. Args:
6. input_shape: Forme des images d'entrée
7. num_classes: Nombre de classes à prédire
8.
9. Returns:
10. model: Modèle Keras compilé
11. """
12. model = [Link]([
13. # Première couche de convolution
14. layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
15. layers.MaxPooling2D((2, 2)),
16.
17. # Deuxième couche de convolution
18. layers.Conv2D(64, (3, 3), activation='relu'),
19. layers.MaxPooling2D((2, 2)),
20.
21. # Troisième couche de convolution
22. layers.Conv2D(128, (3, 3), activation='relu'),
23. layers.MaxPooling2D((2, 2)),
24.
25. # Aplatissement et couches denses
26. [Link](),
27. [Link](128, activation='relu'),
28. [Link](0.5), # Regularisation
29. [Link](num_classes, activation='softmax')
30. ])
31.
32. # Compilation du modèle
33. [Link](
34. optimizer='adam',
35. loss='categorical_crossentropy',
36. metrics=['accuracy']
37. )
38.
39. return model
40.
41. # Créer le modèle
42. model = create_simple_cnn()
43.
44. # Afficher l'architecture
45. [Link]()
46.
7.2 Visualisation de l'Architecture
1. # Visualiser l'architecture du modèle
2. [Link].plot_model(
3. model,
4. to_file='model_architecture.png',
5. show_shapes=True,
6. show_layer_names=True,
7. rankdir='TB'
8. )
9.
10. # Afficher les paramètres par couche
11. print("\nDétails des couches :")
12. for i, layer in enumerate([Link]):
13. if hasattr(layer, 'kernel_size'):
14. print(f"Couche {i+1} ({[Link]}): {[Link]} filtres de taille
{layer.kernel_size}")
15. elif hasattr(layer, 'units'):
16. print(f"Couche {i+1} ({[Link]}): {[Link]} neurones")
17. else:
18. print(f"Couche {i+1} ({[Link]})")
19.

8. Projet Pratique Complet


8.1 Classification d'Images avec CIFAR-10
1. # Charger et préparer les données CIFAR-10
2. def load_and_preprocess_cifar10():
3. """Charge et préprocesse le dataset CIFAR-10"""
4.
5. # Charger les données
6. (x_train, y_train), (x_test, y_test) = [Link].cifar10.load_data()
7.
8. # Classes CIFAR-10
9. class_names = ['Avion', 'Automobile', 'Oiseau', 'Chat', 'Cerf',
10. 'Chien', 'Grenouille', 'Cheval', 'Navire', 'Camion']
11.
12. # Normalisation
13. x_train = x_train.astype('float32') / 255.0
14. x_test = x_test.astype('float32') / 255.0
15.
16. # Conversion en categorical
17. y_train = [Link].to_categorical(y_train, 10)
18. y_test = [Link].to_categorical(y_test, 10)
19.
20. print(f"Données d'entraînement : {x_train.shape}")
21. print(f"Données de test : {x_test.shape}")
22. print(f"Labels d'entraînement : {y_train.shape}")
23. print(f"Labels de test : {y_test.shape}")
24.
25. return (x_train, y_train), (x_test, y_test), class_names
26.
27. # Charger les données
28. (x_train, y_train), (x_test, y_test), class_names = load_and_preprocess_cifar10()
29.
30. # Visualiser quelques exemples
31. [Link](figsize=(15, 6))
32. for i in range(10):
33. [Link](2, 5, i+1)
34. [Link](x_train[i])
35. [Link](class_names[[Link](y_train[i])])
36. [Link]('off')
37. [Link]('Exemples du dataset CIFAR-10')
38. plt.tight_layout()
39. [Link]()
40.
8.2 Entraînement du Modèle
1. # Créer le modèle pour CIFAR-10
2. model_cifar = create_simple_cnn(input_shape=(32, 32, 3), num_classes=10)
3.
4. # Callbacks pour l'entraînement
5. callbacks = [
6. [Link](
7. monitor='val_loss',
8. patience=5,
9. restore_best_weights=True
10. ),
11. [Link](
12. monitor='val_loss',
13. factor=0.1,
14. patience=3,
15. min_lr=1e-7
16. )
17. ]
18.
19. # Entraînement
20. print("Début de l'entraînement...")
21. history = model_cifar.fit(
22. x_train, y_train,
23. batch_size=32,
24. epochs=20,
25. validation_data=(x_test, y_test),
26. callbacks=callbacks,
27. verbose=1
28. )
29.
30. print("Entraînement terminé !")
31.
8.3 Évaluation et Visualisation des Résultats
1. # Évaluation finale
2. test_loss, test_accuracy = model_cifar.evaluate(x_test, y_test, verbose=0)
3. print(f"Précision sur le test : {test_accuracy:.4f}")
4.
5. # Visualisation des courbes d'apprentissage
6. def plot_training_history(history):
7. """Visualise les courbes d'apprentissage"""
8.
9. [Link](figsize=(15, 5))
10.
11. # Précision
12. [Link](1, 2, 1)
13. [Link]([Link]['accuracy'], label='Entraînement')
14. [Link]([Link]['val_accuracy'], label='Validation')
15. [Link]('Précision du Modèle')
16. [Link]('Époque')
17. [Link]('Précision')
18. [Link]()
19. [Link](True)
20.
21. # Perte
22. [Link](1, 2, 2)
23. [Link]([Link]['loss'], label='Entraînement')
24. [Link]([Link]['val_loss'], label='Validation')
25. [Link]('Perte du Modèle')
26. [Link]('Époque')
27. [Link]('Perte')
28. [Link]()
29. [Link](True)
30.
31. plt.tight_layout()
32. [Link]()
33.
34. plot_training_history(history)
35.
36. # Prédictions sur quelques exemples
37. def visualize_predictions(model, x_test, y_test, class_names, num_images=12):
38. """Visualise les prédictions du modèle"""
39.
40. predictions = [Link](x_test[:num_images])
41.
42. [Link](figsize=(15, 8))
43. for i in range(num_images):
44. [Link](3, 4, i+1)
45. [Link](x_test[i])
46.
47. true_label = class_names[[Link](y_test[i])]
48. pred_label = class_names[[Link](predictions[i])]
49. confidence = [Link](predictions[i])
50.
51. color = 'green' if true_label == pred_label else 'red'
52. [Link](f'Vrai: {true_label}\nPrédit: {pred_label}\n({confidence:.2f})',
53. color=color)
54. [Link]('off')
55.
56. plt.tight_layout()
57. [Link]()
58.
59. visualize_predictions(model_cifar, x_test, y_test, class_names)
60.
8.4 Amélioration du Modèle
1. def create_improved_cnn():
2. """CNN amélioré avec plus de couches et techniques de régularisation"""
3.
4. model = [Link]([
5. # Bloc 1
6. layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
7. [Link](),
8. layers.Conv2D(32, (3, 3), activation='relu'),
9. layers.MaxPooling2D((2, 2)),
10. [Link](0.25),
11.
12. # Bloc 2
13. layers.Conv2D(64, (3, 3), activation='relu'),
14. [Link](),
15. layers.Conv2D(64, (3, 3), activation='relu'),
16. layers.MaxPooling2D((2, 2)),
17. [Link](0.25),
18.
19. # Bloc 3
20. layers.Conv2D(128, (3, 3), activation='relu'),
21. [Link](),
22. [Link](0.25),
23.
24. # Classification
25. [Link](),
26. [Link](512, activation='relu'),
27. [Link](),
28. [Link](0.5),
29. [Link](10, activation='softmax')
30. ])
31.
32. [Link](
33. optimizer=[Link](learning_rate=0.001),
34. loss='categorical_crossentropy',
35. metrics=['accuracy']
36. )
37.
38. return model
39.
40. # Créer et entraîner le modèle amélioré
41. improved_model = create_improved_cnn()
42. improved_model.summary()
43.
44. print("\nComparaison des architectures :")
45. print(f"Modèle simple : {model_cifar.count_params()} paramètres")
46. print(f"Modèle amélioré : {improved_model.count_params()} paramètres")
47.

Exercices Pratiques
Exercice 1 : Manipulation d'Images
1. Chargez une image de votre choix
2. Convertissez-la en niveaux de gris
3. Appliquez différents filtres (flou, netteté, détection de contours)
4. Créez une mosaïque montrant tous les résultats
Exercice 2 : Augmentation de Données
1. Créez une fonction qui génère 10 variations d'une image
2. Incluez : rotation, retournement, zoom, changement de luminosité
3. Visualisez les résultats dans une grille
Exercice 3 : CNN Personnalisé
1. Modifiez l'architecture du CNN pour améliorer les performances
2. Expérimentez avec différents nombres de filtres et de couches
3. Ajoutez de la régularisation (Dropout, BatchNormalization)
4. Comparez les résultats
Exercice 4 : Classification Personnalisée
1. Utilisez un autre dataset (Fashion-MNIST, CIFAR-100)
2. Adaptez le modèle pour le nouveau nombre de classes
3. Évaluez les performances et visualisez les résultats

Ressources Complémentaires
Bibliothèques Importantes
 OpenCV : Traitement d'images
 PIL/Pillow : Manipulation d'images
 TensorFlow/Keras : Deep Learning
 scikit-image : Traitement d'images scientifique
Concepts Avancés à Explorer
 Transfer Learning
 Architectures avancées (ResNet, VGG, EfficientNet)
 Détection d'objets (YOLO, R-CNN)
 Segmentation d'images
 GANs (Generative Adversarial Networks)
Bonnes Pratiques
1. Préprocessing : Toujours normaliser les données
2. Validation : Utiliser un ensemble de validation séparé
3. Augmentation : Augmenter artificiellement le dataset
4. Régularisation : Prévenir le surapprentissage
5. Monitoring : Surveiller les métriques pendant l'entraînement

Conclusion
Ce tutoriel vous a introduit aux concepts fondamentaux de la computer vision, depuis les
manipulations basiques d'images jusqu'à la construction de réseaux de neurones convolutifs. La
computer vision est un domaine en constante évolution avec de nombreuses applications pratiques.
Points clés à retenir :
 Les images sont des matrices numériques
 Les transformations permettent d'augmenter les données
 Les CNNs sont particulièrement efficaces pour les tâches visuelles
 L'expérimentation et l'itération sont essentielles

Vous aimerez peut-être aussi