hoololi commited on
Commit
642e641
·
verified ·
1 Parent(s): 8ea4489

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +304 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ from PIL import Image, ImageDraw
5
+ import io
6
+
7
+ # Créer des images de test colorées et asymétriques
8
+ def create_test_image(image_type, size=256):
9
+ """Crée une image de test colorée avec des formes asymétriques"""
10
+ img = Image.new('RGB', (size, size), 'white')
11
+ draw = ImageDraw.Draw(img)
12
+
13
+ if image_type == "licorne":
14
+ # Corps de la licorne (ellipse rose)
15
+ draw.ellipse([80, 120, 180, 200], fill='#FF69B4', outline='#FF1493', width=3)
16
+ # Corne (triangle doré) - asymétrique !
17
+ draw.polygon([125, 80, 135, 80, 130, 50], fill='#FFD700', outline='#FFA500')
18
+ # Œil
19
+ draw.ellipse([110, 140, 120, 150], fill='black')
20
+ # Crinière (cercles colorés)
21
+ draw.ellipse([90, 90, 110, 110], fill='#FF6347')
22
+ draw.ellipse([140, 95, 160, 115], fill='#9370DB')
23
+
24
+ elif image_type == "nounours":
25
+ # Corps (cercle marron)
26
+ draw.ellipse([90, 110, 170, 190], fill='#8B4513', outline='#654321', width=3)
27
+ # Oreilles (asymétriques)
28
+ draw.ellipse([100, 80, 130, 110], fill='#8B4513')
29
+ draw.ellipse([130, 85, 160, 115], fill='#8B4513') # Légèrement décalée
30
+ # Museau
31
+ draw.ellipse([115, 140, 145, 160], fill='#DEB887')
32
+ # Yeux
33
+ draw.ellipse([110, 125, 120, 135], fill='black')
34
+ draw.ellipse([140, 125, 150, 135], fill='black')
35
+ # Nez asymétrique
36
+ draw.ellipse([125, 145, 135, 155], fill='black')
37
+
38
+ elif image_type == "chat":
39
+ # Corps (ellipse grise avec contour noir)
40
+ draw.ellipse([90, 130, 170, 190], fill='#808080', outline='black', width=3)
41
+ # Tête
42
+ draw.ellipse([105, 90, 155, 140], fill='#808080', outline='black', width=3)
43
+ # Oreilles triangulaires (asymétriques)
44
+ draw.polygon([115, 90, 125, 70, 135, 90], fill='#808080', outline='black', width=2)
45
+ draw.polygon([125, 95, 135, 75, 145, 95], fill='#808080', outline='black', width=2) # Décalée
46
+ # Intérieur des oreilles (rose)
47
+ draw.polygon([119, 86, 124, 76, 131, 86], fill='#FFB6C1')
48
+ draw.polygon([129, 91, 134, 81, 141, 91], fill='#FFB6C1')
49
+ # Yeux (grands ronds blancs)
50
+ draw.ellipse([112, 102, 128, 118], fill='white', outline='black', width=2)
51
+ draw.ellipse([132, 102, 148, 118], fill='white', outline='black', width=2)
52
+ # Pupilles noires
53
+ draw.ellipse([118, 108, 122, 112], fill='black')
54
+ draw.ellipse([138, 108, 142, 112], fill='black')
55
+ # Museau triangulaire
56
+ draw.polygon([125, 125, 135, 125, 130, 132], fill='#FFB6C1', outline='black', width=1)
57
+ # Langue rose qui dépasse (asymétrique !)
58
+ draw.ellipse([128, 132, 140, 142], fill='#FF69B4', outline='black', width=1)
59
+ # Moustaches (asymétriques)
60
+ draw.line([90, 120, 110, 122], fill='black', width=2)
61
+ draw.line([90, 125, 110, 125], fill='black', width=2)
62
+ draw.line([150, 120, 170, 118], fill='black', width=2) # Légèrement différente
63
+ draw.line([150, 125, 170, 127], fill='black', width=2)
64
+ # Queue (courbe asymétrique noire)
65
+ draw.arc([160, 120, 200, 180], 0, 180, fill='black', width=8)
66
+
67
+ return img
68
+
69
+ # Définir les transformations
70
+ transformations = {
71
+ "identite": {
72
+ "name": "Identité (aucune transformation)",
73
+ "matrix": np.array([[1, 0], [0, 1]]),
74
+ "explanation": "La matrice identité ne change rien à l'image"
75
+ },
76
+ "rotation_90": {
77
+ "name": "Rotation 90° (sens horaire)",
78
+ "matrix": np.array([[0, 1], [-1, 0]]),
79
+ "explanation": "Rotation d'un quart de tour vers la droite"
80
+ },
81
+ "symetrie_h": {
82
+ "name": "Symétrie horizontale",
83
+ "matrix": np.array([[-1, 0], [0, 1]]),
84
+ "explanation": "Miroir vertical - l'image se retourne de gauche à droite"
85
+ },
86
+ "symetrie_v": {
87
+ "name": "Symétrie verticale",
88
+ "matrix": np.array([[1, 0], [0, -1]]),
89
+ "explanation": "Miroir horizontal - l'image se retourne de haut en bas"
90
+ },
91
+ "homothetie_2": {
92
+ "name": "Homothétie x2",
93
+ "matrix": np.array([[2, 0], [0, 2]]),
94
+ "explanation": "Agrandissement d'un facteur 2 dans toutes les directions"
95
+ },
96
+ "homothetie_05": {
97
+ "name": "Homothétie x0.5",
98
+ "matrix": np.array([[0.5, 0], [0, 0.5]]),
99
+ "explanation": "Réduction d'un facteur 2 dans toutes les directions"
100
+ },
101
+ "cisaillement": {
102
+ "name": "Cisaillement",
103
+ "matrix": np.array([[1, 0.5], [0, 1]]),
104
+ "explanation": "Déformation oblique - l'image 'penche' vers la droite"
105
+ }
106
+ }
107
+
108
+ def draw_grid_overlay(ax, matrix, color='gray', alpha=0.3, grid_range=150, spacing=20):
109
+ """Dessine un quadrillage transformé par la matrice"""
110
+ # Créer les points du quadrillage
111
+ x_lines = np.arange(-grid_range, grid_range + spacing, spacing)
112
+ y_lines = np.arange(-grid_range, grid_range + spacing, spacing)
113
+
114
+ # Lignes verticales
115
+ for x in x_lines:
116
+ y_points = np.array([[-grid_range], [grid_range]])
117
+ x_points = np.array([[x], [x]])
118
+
119
+ # Appliquer la transformation
120
+ points = np.vstack([x_points.flatten(), y_points.flatten()])
121
+ transformed = matrix @ points
122
+
123
+ ax.plot(transformed[0], transformed[1], color=color, alpha=alpha, linewidth=0.8)
124
+
125
+ # Lignes horizontales
126
+ for y in y_lines:
127
+ x_points = np.array([[-grid_range], [grid_range]])
128
+ y_points = np.array([[y], [y]])
129
+
130
+ # Appliquer la transformation
131
+ points = np.vstack([x_points.flatten(), y_points.flatten()])
132
+ transformed = matrix @ points
133
+
134
+ ax.plot(transformed[0], transformed[1], color=color, alpha=alpha, linewidth=0.8)
135
+
136
+ def transform_image_pixels(img_array, matrix):
137
+ """Transforme une image pixel par pixel avec la matrice donnée"""
138
+ height, width = img_array.shape[:2]
139
+
140
+ # Créer une image de sortie (fond blanc)
141
+ if len(img_array.shape) == 3:
142
+ transformed = np.ones((height, width, 3), dtype=np.uint8) * 255
143
+ else:
144
+ transformed = np.ones((height, width), dtype=np.uint8) * 255
145
+
146
+ # Centrer les coordonnées
147
+ center_x, center_y = width // 2, height // 2
148
+
149
+ # Pour chaque pixel de l'image de sortie
150
+ for y in range(height):
151
+ for x in range(width):
152
+ # Coordonnées centrées
153
+ coord_x = x - center_x
154
+ coord_y = center_y - y # Inverser Y pour avoir origine en bas à gauche
155
+
156
+ # Appliquer la transformation inverse pour trouver le pixel source
157
+ try:
158
+ inv_matrix = np.linalg.inv(matrix)
159
+ original_coord = inv_matrix @ np.array([coord_x, coord_y])
160
+
161
+ # Reconvertir en coordonnées image
162
+ orig_x = int(original_coord[0] + center_x)
163
+ orig_y = int(center_y - original_coord[1])
164
+
165
+ # Vérifier si le pixel source est dans l'image
166
+ if 0 <= orig_x < width and 0 <= orig_y < height:
167
+ transformed[y, x] = img_array[orig_y, orig_x]
168
+
169
+ except np.linalg.LinAlgError:
170
+ # Matrice non inversible, laisser blanc
171
+ pass
172
+
173
+ return transformed
174
+
175
+ def apply_transformation(image_choice, transform_choice):
176
+ """Applique la transformation et crée la visualisation comparative"""
177
+
178
+ # Créer l'image de test
179
+ original_img = create_test_image(image_choice)
180
+ original_array = np.array(original_img)
181
+
182
+ # Récupérer la transformation
183
+ transform_info = transformations[transform_choice]
184
+ matrix = transform_info["matrix"]
185
+
186
+ # Transformer l'image
187
+ transformed_array = transform_image_pixels(original_array, matrix)
188
+ transformed_img = Image.fromarray(transformed_array)
189
+
190
+ # Créer la figure avec deux sous-graphiques
191
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
192
+ fig.suptitle('🦄 Transformations Matricielles 🦄', fontsize=16, fontweight='bold')
193
+
194
+ # Image originale
195
+ ax1.imshow(original_img, extent=[-128, 128, -128, 128])
196
+ ax1.set_title('Image originale', fontsize=14, color='#FF1493', fontweight='bold',
197
+ bbox=dict(boxstyle="round,pad=0.3", facecolor='#FFB6C1', alpha=0.7))
198
+
199
+ # Quadrillage original
200
+ draw_grid_overlay(ax1, np.eye(2), alpha=0.4)
201
+
202
+ # Cadre rose
203
+ for spine in ax1.spines.values():
204
+ spine.set_color('#FF1493')
205
+ spine.set_linewidth(3)
206
+
207
+ ax1.set_xlim(-150, 150)
208
+ ax1.set_ylim(-150, 150)
209
+ ax1.set_aspect('equal')
210
+ ax1.grid(False)
211
+ ax1.set_xticks([])
212
+ ax1.set_yticks([])
213
+
214
+ # Image transformée
215
+ ax2.imshow(transformed_img, extent=[-128, 128, -128, 128])
216
+ ax2.set_title('Après la transformation matricielle !', fontsize=14, color='#8A2BE2', fontweight='bold',
217
+ bbox=dict(boxstyle="round,pad=0.3", facecolor='#DDA0DD', alpha=0.7))
218
+
219
+ # Quadrillage fixe (même que l'original pour comparaison)
220
+ draw_grid_overlay(ax2, np.eye(2), alpha=0.4)
221
+
222
+ # Cadre violet
223
+ for spine in ax2.spines.values():
224
+ spine.set_color('#8A2BE2')
225
+ spine.set_linewidth(3)
226
+
227
+ ax2.set_xlim(-150, 150)
228
+ ax2.set_ylim(-150, 150)
229
+ ax2.set_aspect('equal')
230
+ ax2.grid(False)
231
+ ax2.set_xticks([])
232
+ ax2.set_yticks([])
233
+
234
+ plt.tight_layout()
235
+
236
+ # Convertir en image pour Gradio
237
+ buf = io.BytesIO()
238
+ plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
239
+ buf.seek(0)
240
+ result_img = Image.open(buf)
241
+ plt.close()
242
+
243
+ # Créer le texte d'explication
244
+ matrix_str = f"[{matrix[0,0]:4.1f}, {matrix[0,1]:4.1f}]\n[{matrix[1,0]:4.1f}, {matrix[1,1]:4.1f}]"
245
+ explanation = f"📐 **Matrice de transformation :**\n\n```\n{matrix_str}\n```\n\n💡 **Explication :** {transform_info['explanation']}"
246
+
247
+ return result_img, explanation
248
+
249
+ # Interface Gradio
250
+ def create_interface():
251
+ with gr.Blocks(title="🦄 Transformations Matricielles", theme=gr.themes.Soft()) as demo:
252
+
253
+ gr.Markdown("""
254
+ # 🦄 Transformations Matricielles 🦄
255
+ ### Visualisez les effets de transformations matricielles sur des images !
256
+ """)
257
+
258
+ with gr.Row():
259
+ with gr.Column():
260
+ # Choix de l'image
261
+ image_choice = gr.Dropdown(
262
+ choices=[("Licorne 🦄", "licorne"), ("Nounours 🧸", "nounours"), ("Chat 🐱", "chat")],
263
+ value="licorne",
264
+ label="1️⃣ Choisissez votre image :"
265
+ )
266
+
267
+ # Choix de la transformation
268
+ transform_choice = gr.Dropdown(
269
+ choices=[(info["name"], key) for key, info in transformations.items()],
270
+ value="identite",
271
+ label="2️⃣ Choisissez votre transformation :"
272
+ )
273
+
274
+ # Explication de la matrice
275
+ explanation_text = gr.Markdown(value="", label="Matrice et explication")
276
+
277
+ # Résultat
278
+ result_image = gr.Image(label="Visualisation", type="pil")
279
+
280
+ # Auto-update quand on change les paramètres
281
+ def update_all(img_choice, trans_choice):
282
+ result_img, explanation = apply_transformation(img_choice, trans_choice)
283
+ return result_img, explanation
284
+
285
+ image_choice.change(update_all, [image_choice, transform_choice], [result_image, explanation_text])
286
+ transform_choice.change(update_all, [image_choice, transform_choice], [result_image, explanation_text])
287
+
288
+ # Initialisation
289
+ demo.load(update_all, [image_choice, transform_choice], [result_image, explanation_text])
290
+
291
+ gr.Markdown("""
292
+ ---
293
+ 💡 **Astuce :** Vous pouvez observer les effets des matrices sur l'image initiale :
294
+ - **homothétie** : les objets changent de taille
295
+ - **rotation** : tout tourne ensemble
296
+ - **cisaillement** : les images s'aplatissent
297
+ """)
298
+
299
+ return demo
300
+
301
+ # Lancer l'application
302
+ if __name__ == "__main__":
303
+ demo = create_interface()
304
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio
2
+ numpy
3
+ matplotlib
4
+ pillow