File size: 12,511 Bytes
d63a8cc
 
 
 
 
 
 
 
62ec819
d63a8cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d48712
d63a8cc
 
 
 
 
0d48712
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d63a8cc
 
0d48712
 
 
 
 
 
 
 
 
 
 
d63a8cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d48712
 
 
 
 
 
 
 
 
 
 
 
 
 
d63a8cc
 
 
 
0d48712
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99eeefd
0d48712
 
 
 
 
 
d63a8cc
 
 
 
 
0d48712
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d63a8cc
 
 
 
 
 
 
 
 
0d48712
 
d63a8cc
 
 
 
 
 
0d48712
 
 
 
d63a8cc
 
 
 
 
0d48712
 
d63a8cc
 
 
 
0d48712
 
 
d63a8cc
 
 
 
0d48712
 
 
 
 
 
 
 
 
43dda14
 
 
 
 
62ec819
 
 
 
43dda14
62ec819
 
0d48712
43dda14
62ec819
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43dda14
62ec819
 
 
 
 
 
 
 
 
 
 
 
 
 
43dda14
 
62ec819
43dda14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d63a8cc
 
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
import streamlit as st
import cv2
import numpy as np
from PIL import Image
from io import BytesIO
import barcode
from barcode.writer import ImageWriter
import qrcode
import tempfile

def image_to_bytes(img):
    pil_image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    buffer = BytesIO()
    pil_image.save(buffer, format="PNG")
    return buffer.getvalue()

def generate_barcode(link):
    code128 = barcode.get_barcode_class('code128')
    barcode_image = code128(link, writer=ImageWriter())
    buffer = BytesIO()
    barcode_image.write(buffer)
    return Image.open(buffer)

def generate_qrcode(link):
    qr = qrcode.QRCode(
        version=2,  
        error_correction=qrcode.constants.ERROR_CORRECT_L,  
        box_size=4,  
        border=2,    
    )
    qr.add_data(link)
    qr.make(fit=True)
    qr_image = qr.make_image(fill_color="black", back_color="white")

    small_qr_image = qr_image.resize((60, 60), Image.Resampling.LANCZOS)

    buffer = BytesIO()
    small_qr_image.save(buffer, format="PNG")
    return Image.open(buffer)

def add_custom_css():
    css = """
    <style>
        body {
            background: linear-gradient(135deg, #a8dadc, #f1faee);
            color: #1d3557;
            font-family: 'Arial', sans-serif;
            animation: backgroundAnimation 10s infinite alternate;
        }

        @keyframes backgroundAnimation {
            0% {
                background: linear-gradient(135deg, #a8dadc, #f1faee);
            }
            100% {
                background: linear-gradient(135deg, #f1faee, #457b9d);
            }
        }

        .stButton>button {
            background-color: #457b9d;
            color: white;
            border-radius: 5px;
            transition: transform 0.3s, background-color 0.3s;
            box-shadow: 2px 2px 6px rgba(0,0,0,0.2);
        }

        .stButton>button:hover {
            transform: scale(1.1);
            background-color: #1d3557;
        }

        .stSidebar {
            background: linear-gradient(135deg, #457b9d, #a8dadc);
            color: white;
            font-size: 16px;
        }

        .stImage {
            animation: fadeIn 2s ease-in-out;
        }

        @keyframes fadeIn {
            0% {
                opacity: 0;
            }
            100% {
                opacity: 1;
            }
        }

        header, footer {
            background: #457b9d;
            color: white;
        }

        .stMarkdown {
            animation: slideIn 1s ease-out;
        }

        @keyframes slideIn {
            0% {
                transform: translateY(-20px);
                opacity: 0;
            }
            100% {
                transform: translateY(0);
                opacity: 1;
            }
        }
    </style>
    """
    st.markdown(css, unsafe_allow_html=True)

def add_custom_js():
    js = """
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const elements = document.querySelectorAll('.stButton>button');
            elements.forEach(button => {
                button.addEventListener('click', () => {
                    button.style.backgroundColor = '#a8dadc';
                    button.style.transform = 'rotate(360deg)';
                    setTimeout(() => button.style.transform = 'rotate(0deg)', 300);
                });
            });
        });
    </script>
    """
    st.markdown(js, unsafe_allow_html=True)

def main():
    st.set_page_config(page_title="ADS VISOR - Un autre regard", layout="wide")

    add_custom_css()
    add_custom_js()


    logo_path = "logo.jpg"  
    logo = Image.open(logo_path)
    st.image(logo, width=150, caption="ADS VISOR")

    st.title("ADS VISOR - Un autre regard")

    st.sidebar.header("Chargement de l'image")
    if "default_image" not in st.session_state:
        st.session_state["default_image"] = None

    uploaded_file = st.sidebar.file_uploader("Charge une image", type=["png", "jpg", "jpeg"])
    if uploaded_file is not None:
        image = Image.open(uploaded_file)
        st.session_state["default_image"] = np.array(image)
        st.sidebar.image(image, caption="Image par défaut", use_container_width=True)

    if st.session_state["default_image"] is None:
        st.sidebar.warning("Veuillez charger une image pour commencer.")
        return

    st.sidebar.header("Fonctionnalités")
    menu_option = st.sidebar.selectbox(
        "Choisissez une fonctionnalité",
        ["Accueil", "Transformations d'image", "Cropping", "Rotation", "Floutage", "Contours", "Génération de Code-barres et QR Code", "Détection Faciale"],
        format_func=lambda x: {
            "Accueil": "🏠 Accueil",
            "Transformations d'image": "🖼️ Transformations",
            "Cropping": "✂️ Cropping",
            "Rotation": "🔄 Rotation",
            "Floutage": "🌫️ Floutage",
            "Contours": "🔍 Contours",
            "Génération de Code-barres et QR Code": "📇 Codes",
            "Détection Faciale": "🙂 Détection Faciale"
        }.get(x, x)
    )

    image_np = st.session_state["default_image"]

    if menu_option == "Accueil":
        st.header("Bienvenue sur ADS VISOR")
        st.markdown(
            """
            <div class="stMarkdown">
                <h2>ADS VISOR est une application innovante pour analyser, transformer et explorer vos images. 🖼️✨</h2>
                <p>Elle a été concu par un groupe de trois étudiants dans le contexte du contrôle continu de Computer Vision.</p>
                <p>Que vous soyez un professionnel ou un passionné, découvrez un large éventail de fonctionnalités interactives !</p>
                <ul>
                    <li><b>Transformations d'image :</b> Couleurs, niveaux de gris, etc.</li>
                    <li><b>Découpage & Rotation :</b> Ajustez vos images à la perfection.</li>
                    <li><b>Détection Faciale :</b> Identifiez les visages automatiquement.</li>
                    <li><b>Codes-barres & QR Codes :</b> Génération rapide pour vos projets.</li>
                </ul>
            </div>
            """,
            unsafe_allow_html=True
        )

        st.write("### Équipe :")
        st.markdown(
            """
            | **Nom**                | **Niveau**                  |
            |------------------------|---------------------------|
            | **Ngoue David**        | Master 2 Intelligence Artificielle et Big Data      |
            | **Bidzanga Armel**     | Master 2 Intelligence Artificielle et Big Data       |
            | **Nziou Serena**       | Master 2 Administration de Systèmes d'Information     |
            """,
            unsafe_allow_html=True
        )

    elif menu_option == "Transformations d'image":
        st.subheader("Transformations d'image")

        tab1, tab2, tab3, tab4 = st.tabs([
            "Gris 🖤", "Rouge ❤️", "Vert 💚", "Jaune 💛"
        ])

        with tab1:
            st.image(cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY), caption="Image en Niveaux de Gris", use_container_width=True)
        with tab2:
            red = image_np.copy()
            red[:, :, 1:] = 0
            st.image(red, caption="Image Rouge", use_container_width=True)
        with tab3:
            green = image_np.copy()
            green[:, :, [0, 2]] = 0
            st.image(green, caption="Image Verte", use_container_width=True)
        with tab4:
            yellow = image_np.copy()
            yellow[:, :, 0] = 0
            st.image(yellow, caption="Image Jaune", use_container_width=True)

    elif menu_option == "Cropping":
        st.subheader("Cropping")

        x1 = st.number_input("x1", 0, image_np.shape[1] - 1, step=1)
        y1 = st.number_input("y1", 0, image_np.shape[0] - 1, step=1)
        x2 = st.number_input("x2", 1, image_np.shape[1], step=1)
        y2 = st.number_input("y2", 1, image_np.shape[0], step=1)

        cropped = image_np[int(y1):int(y2), int(x1):int(x2)]
        st.image(cropped, caption="Image Croppée", use_container_width=True)

    elif menu_option == "Rotation":
        st.subheader("Rotation")

        angle = st.selectbox("Angle de rotation", [45, 90, 180])

        rows, cols, _ = image_np.shape
        rotation_matrix = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)
        rotated = cv2.warpAffine(image_np, rotation_matrix, (cols, rows))
        st.image(rotated, caption=f"Image Rotée de {angle} degrés", use_container_width=True)

    elif menu_option == "Floutage":
        st.subheader("Floutage")

        blur_level = st.slider("Niveau de flou (k)", min_value=1, max_value=51, step=2, value=15)
        blurred = cv2.GaussianBlur(image_np, (blur_level, blur_level), 0)
        st.image(blurred, caption=f"Image Floutée (k={blur_level})", use_container_width=True)

    elif menu_option == "Contours":
        st.subheader("Contours")

        gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
        edges = cv2.Canny(gray, 100, 200)
        st.image(edges, caption="Contours de l'Image", use_container_width=True)

    elif menu_option == "Génération de Code-barres et QR Code":
        st.subheader("Génération de Code-barres et QR Code")
        link = st.text_input("Entre un lien ou un texte pour générer le code-barres et le QR code")
        if link:
            barcode_image = generate_barcode(link)
            st.image(barcode_image, caption="Code-barres généré", use_container_width=True)

            qrcode_image = generate_qrcode(link)
            st.image(qrcode_image, caption="QR Code généré", use_container_width=True)
        else:
            st.error("Veuillez entrer un lien valide pour générer les codes.")

    elif menu_option == "Détection Faciale":
        st.subheader("Détection Faciale")

        face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

        detection_option = st.radio(
            "Choisis la source pour la détection faciale",
            options=["Webcam", "Vidéo téléversée"]
        )

        if detection_option == "Webcam":
            if st.button("Lancer la détection via webcam"):
                cap = cv2.VideoCapture(0)

                if not cap.isOpened():
                    st.error("Impossible d'accéder à la webcam, Hugging Face et le navigateur bloquent l'accès.")
                else:
                    st.info("Appuyez sur Ctrl+C pour arrêter la détection.")
                    frame_placeholder = st.empty()

                    while True:
                        ret, frame = cap.read()
                        if not ret:
                            st.error("Erreur lors de la capture vidéo.")
                            break

                        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
                        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

                        for (x, y, w, h) in faces:
                            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)

                        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                        frame_placeholder.image(frame, channels="RGB", use_container_width=True)

                    cap.release()

        elif detection_option == "Vidéo téléversée":
            uploaded_video = st.file_uploader("Charge une vidéo", type=["mp4", "avi", "mov"])
            if uploaded_video is not None:
                video_bytes = uploaded_video.read()
                tfile = tempfile.NamedTemporaryFile(delete=False)
                tfile.write(video_bytes)
                tfile.close()

                cap = cv2.VideoCapture(tfile.name)
                frame_placeholder = st.empty()

                while cap.isOpened():
                    ret, frame = cap.read()
                    if not ret:
                        break

                    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
                    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

                    for (x, y, w, h) in faces:
                        cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)

                    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                    frame_placeholder.image(frame, channels="RGB", use_container_width=True)

                cap.release()

if __name__ == "__main__":
    main()