File size: 9,490 Bytes
5255198
 
 
 
2ffb4a2
5255198
 
 
 
 
2ffb4a2
5255198
 
 
2ffb4a2
5255198
2ffb4a2
5255198
 
 
 
 
2ffb4a2
5255198
2ffb4a2
5255198
 
 
 
 
 
 
2ffb4a2
5255198
2ffb4a2
5255198
 
 
 
 
2ffb4a2
5255198
2ffb4a2
5255198
 
 
2ffb4a2
5255198
2ffb4a2
5255198
 
 
 
 
 
 
2ffb4a2
 
 
5255198
 
 
 
 
 
 
2ffb4a2
5255198
2ffb4a2
5255198
 
 
 
 
 
2ffb4a2
5255198
 
 
 
2ffb4a2
5255198
 
 
 
 
 
 
2ffb4a2
5255198
 
2ffb4a2
 
5255198
 
 
 
2ffb4a2
5255198
 
2ffb4a2
5255198
 
 
2ffb4a2
5255198
 
2ffb4a2
5255198
 
 
2ffb4a2
5255198
2ffb4a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255198
 
2ffb4a2
5255198
2ffb4a2
5255198
2ffb4a2
5255198
2ffb4a2
5255198
2ffb4a2
5255198
2ffb4a2
5255198
2ffb4a2
5255198
2ffb4a2
5255198
2ffb4a2
5255198
2ffb4a2
5255198
2ffb4a2
 
 
 
 
 
 
 
5255198
2ffb4a2
 
5255198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ffb4a2
5255198
 
2ffb4a2
5255198
 
2ffb4a2
 
 
5255198
2ffb4a2
5255198
 
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
import gradio as gr
from PIL import Image
import numpy as np
import cv2
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
import PIL.ImageFilter
from scipy.ndimage import convolve
from skimage import morphology

# ==========================================================================================
# 1. Charger l'image
def load_image(image):
    return image
# ==========================================================================================

# ==========================================================================================
# Transformer l'image en niveau de gris
def gray(image):
    image = np.array(image)
    image_gris = rgb2gray(image)
    return image_gris
# ==========================================================================================

# ==========================================================================================
# Transformer en blanc noir
def blanc_noir(image):
    image = np.array(image)
    image_gris = rgb2gray(image)
    image_blanc_noir = np.where(image_gris > 0.5, 0, 1)
    image = (image_blanc_noir * 255).astype(np.uint8)
    return Image.fromarray(image)
# ==========================================================================================

# ==========================================================================================
# 2. Application d'un négatif à l'image
def apply_negative(image):
    img_np = np.array(image)
    negative = 255 - img_np
    return Image.fromarray(negative)
# ==========================================================================================

# ==========================================================================================
# 3. Transformation en Rotation
def rotate_image(image, angle):
    return image.rotate(angle, expand=True)
# ==========================================================================================

# ==========================================================================================
# 4. Application des filtres
def filtrage_image(image, filter_name):
    filtre_mapping = {
        'Floutage': PIL.ImageFilter.BLUR,
        'Détails': PIL.ImageFilter.DETAIL,
        'Netteté': PIL.ImageFilter.SHARPEN,
        'Effet 3D': PIL.ImageFilter.EMBOSS,
        'Contour': PIL.ImageFilter.FIND_EDGES,
        'Floutage Moyen': PIL.ImageFilter.BoxBlur(5),
        'Floutage Gaussien': PIL.ImageFilter.GaussianBlur(5)
    }
    
    if filter_name in filtre_mapping:
        filtre = filtre_mapping[filter_name]
        return image.filter(filtre)
    else:
        raise ValueError(f"Le filtre '{filter_name}' n'existe pas dans les filtres définis.")
# ==========================================================================================

# ==========================================================================================
# 5. Binarisation de l'image
def binarize_image(image, threshold):
    img_np = np.array(image.convert('L'))
    _, binary = cv2.threshold(img_np, threshold, 255, cv2.THRESH_BINARY)
    return Image.fromarray(binary)

# ==========================================================================================
# 6. Redimensionnement de l'image
def resize_image(image, width, height):
    return image.resize((width, height))

# ==========================================================================================
# 7. Détecter les contours avec canny:
def detect_contour(image):
    image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY)
    image = cv2.GaussianBlur(image, (5, 5), 0)
    edges = cv2.Canny(image, threshold1=50, threshold2=150)
    return Image.fromarray(edges)

# ==========================================================================================
# 8. Détecter les contours avec Sobel:
def detect_contour_sobel(image):
    sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
    sobel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
    image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY)
    sobel_x_img = convolve(image, sobel_x)
    sobel_y_img = convolve(image, sobel_y)
    sobel_combined = np.hypot(sobel_x_img, sobel_y_img)
    sobel_combined = (sobel_combined / sobel_combined.max()) * 255
    return Image.fromarray(sobel_combined.astype(np.uint8))

# ==========================================================================================
# 9. Transformation morphologique : erosion
def morphologies_erosion(image):
    image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY)
    erosion = morphology.binary_erosion(image=image, footprint=morphology.disk(1))
    return Image.fromarray(erosion.astype(np.uint8))

# ==========================================================================================
# 10. Transformation morphologique : dilatation
def morphologies_dilatation(image):
    image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY)
    dilation = morphology.binary_dilation(image=image, footprint=morphology.disk(1))
    return Image.fromarray(dilation.astype(np.uint8))

# ==========================================================================================
# 11. Afficher l'histogramme de l'image dans Gradio
def display_histogram(image):
    img_np = np.array(image.convert('L'))
    plt.figure()
    plt.hist(img_np.ravel(), bins=256, range=[0, 256], color='black', alpha=0.7)
    plt.title('Histogramme de l\'image')
    plt.xlabel('Intensité des pixels')
    plt.ylabel('Fréquence')
    plt.grid(False)
    
    # Sauvegarder l'histogramme dans un buffer
    import io
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    plt.close()
    
    # Charger l'image du buffer
    hist_image = Image.open(buf)
    return hist_image

# ==========================================================================================
# Interface Gradio mise à jour pour inclure l'affichage de l'histogramme
def image_processing(image, operation, filter_name, threshold=128, width=100, height=100, angle=0, display_hist=False):
    processed_image = image
    hist_image = None  # Ajout d'une variable pour l'histogramme
    
    if operation == "Négatif":
        processed_image = apply_negative(image)
    elif operation == 'Niveau de Gris':
        processed_image = gray(image)
    elif operation == "Blanc Noir":
        processed_image = blanc_noir(image)
    elif operation == "Binarisation":
        processed_image = binarize_image(image, threshold)
    elif operation == "Redimensionner":
        processed_image = resize_image(image, width, height)
    elif operation == "Rotation":
        processed_image = rotate_image(image, angle)
    elif operation == "Filtrage":
        processed_image = filtrage_image(image, filter_name)
    elif operation == "Contour Pro (Canny)":
        processed_image = detect_contour(image)
    elif operation == "Contour Pro (Sobel)":
        processed_image = detect_contour_sobel(image)
    elif operation == "Erosion":
        processed_image = morphologies_erosion(image)
    elif operation == "Dilatation":
        processed_image = morphologies_dilatation(image)
    
    # Afficher l'histogramme si l'option est cochée
    if display_hist:
        hist_image = display_histogram(processed_image)
    
    # Retourner l'image modifiée et l'histogramme
    return processed_image, hist_image

# ==========================================================================================
# Interface Gradio mise à jour
with gr.Blocks() as demo:
    gr.Markdown("## APPLICATION DE TRAITEMENT DES IMAGES")

    with gr.Row():
        image_input = gr.Image(type="pil", label="Charger Image")
        operation = gr.Radio(["Négatif", "Binarisation", "Redimensionner", 
                              "Rotation", "Niveau de Gris", "Blanc Noir", 
                              "Filtrage", "Contour Pro (Canny)", "Contour Pro (Sobel)",
                              "Erosion", "Dilatation"], label="Opération")
        dict_options = {
            'Floutage': 'Floutage', 
            'Détails': 'Détails', 
            'Netteté': 'Netteté', 
            'Effet 3D': 'Effet 3D',
            'Contour': 'Contour', 
            'Floutage Moyen': 'Floutage Moyen', 
            'Floutage Gaussien': 'Floutage Gaussien',
        }
        options = gr.Dropdown(choices=list(dict_options.keys()), label="Choisissez votre filtre", visible=True)
        threshold = gr.Slider(0, 255, 128, label="Seuil de binarisation", visible=False)
        width = gr.Number(value=100, label="Largeur", visible=False)
        height = gr.Number(value=100, label="Hauteur", visible=False)
        angle = gr.Number(value=360, label="Angle de Rotation", visible=True)
        display_hist = gr.Checkbox(label="Afficher Histogramme", visible=True)

    image_output = gr.Image(label="Image Modifiée")
    hist_output = gr.Image(label="Histogramme", visible=True)  # Ajout d'un espace pour l'histogramme

    submit_button = gr.Button("Appliquer")
    submit_button.click(image_processing, 
                        inputs=[image_input, operation, options, threshold, width, height, angle, display_hist], 
                        outputs=[image_output, hist_output])

# ==========================================================================================
# Lancer l'application Gradio
demo.launch()