Spaces:
Sleeping

File size: 9,924 Bytes
a7a29c0
 
 
ecc2f23
 
cd9eeb2
e614057
 
d4eef49
461e83e
 
 
 
 
 
cd9eeb2
 
 
 
 
 
 
 
 
 
459b0d9
4a4a8cd
 
 
4a3f59f
a7a29c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecc2f23
a7a29c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecc2f23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4eef49
 
 
 
 
 
 
e614057
d4eef49
e614057
 
3b4a6b2
e614057
 
 
 
 
 
 
3b4a6b2
ecc2f23
 
 
 
 
461e83e
b04ceda
a7a29c0
 
b04ceda
a7a29c0
b04ceda
 
 
ecc2f23
 
 
 
 
b04ceda
e614057
 
19c0a22
e614057
3b4a6b2
19c0a22
3b4a6b2
434dd5d
52463d7
96bdcc0
 
 
fadd9d9
 
 
 
006f195
c43e323
 
 
66311d9
 
 
 
461e83e
 
 
 
 
 
 
 
 
 
d186534
461e83e
 
d186534
461e83e
 
a7a29c0
461e83e
4a4a8cd
461e83e
a7a29c0
 
 
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
import cv2 as cv
import numpy as np
from skimage import color
import PIL
from ultralytics import YOLO
import os


# detection_model = YOLO(r'./models/crack_detector.pt')
# classification_model = YOLO(r'./models/crack_classificator.pt')
# classification_model_2 = YOLO(r'./models/classification_model (13 epochs).pt')
# classification_model_3 = YOLO(r'./models/yolov8n-cls_egg_cls_5_epochs.pt')
# classification_model_4 = YOLO(r'./models/yolov8n-cls_egg_cls_1_epochs.pt')
# classification_model_5 = YOLO(r'./models/yolov8n-cls_egg_cls_4_epochs.pt')

# models = {
#     'Classificator_Test': YOLO(r'./models/Classificator_Test.pt'),
#     'Classificator_YOLOv8n (1 epoch)': YOLO(r'./models/Classificator_YOLOv8n (1 epoch).pt'),
#     'Classificator_YOLOv8n (13 epoch)': YOLO(r'./models/Classificator_YOLOv8n (13 epochs).pt'),
#     'Classificator_YOLOv8n (4 epoch)': YOLO(r'./models/Classificator_YOLOv8n (4 epochs).pt'),
#     'Classificator_YOLOv8n (5 epoch)': YOLO(r'./models/Classificator_YOLOv8n (5 epochs).pt')
# }

model_files = os.listdir('./models')
model_names = [i.removesuffix('.pt') for i in model_files]
loaded_models = [YOLO(r"./models/{}".format(i)) for i in model_files]
# model_files = os.listdir('./models')
# model_names = [i.removesuffix('.pt') for i in model_files]
# models = dict(zip(model_names, model_files))
model_table = dict(zip(model_names, loaded_models))

def remove_shadows(image):
    # Converte para tons de cinza
    gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)

    # Aplica um pequeno desfoque para reduzir ruído
    blur = cv.GaussianBlur(gray, (5, 5), 0)

    # Binariza usando Otsu (boa para fundo escuro)
    _, thresh = cv.threshold(blur, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)

    # Inverte: queremos o ovo branco sobre fundo preto
    thresh = cv.bitwise_not(thresh)

    # Pintando por cima da imagem original
    imagem_sem_sombra = cv.cvtColor(thresh.copy(), cv.COLOR_GRAY2BGR)
    height, width = imagem_sem_sombra.shape[:2]

    for h in range(height):
        for w in range(width):
            if thresh[h, w] == 255:
                imagem_sem_sombra[h, w] = image[h, w]
    
    return imagem_sem_sombra


def segment_algorithm_1(image):
    # 1) Segmentar o ovo do fundo
    gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
    blur = cv.GaussianBlur(gray, (5, 5), 0)
    _, thresh = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
    thresh = cv.bitwise_not(thresh)  # ovo branco, fundo preto

    contours, _ = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    filtered = [c for c in contours if cv.contourArea(c) > 1000]
    main = max(filtered, key=cv.contourArea)

    mask = np.zeros_like(gray)
    cv.drawContours(mask, [main], -1, 255, -1)
    segmented = cv.bitwise_and(image, image, mask=mask)
    x, y, w, h = cv.boundingRect(main)
    egg_rgb = segmented[y:y+h, x:x+w]

    # 2) Converte para YIQ e extrai luminância em 8-bits
    egg_yiq = color.rgb2yiq(egg_rgb)
    Y, I, Q = cv.split(egg_yiq)
    Y_8b = (Y * 255).astype(np.uint8)

    # 3) Top-Hat multidirecional adaptativo
    h, w = Y_8b.shape
    base = max(3, int(max(h, w) * 0.01))
    if base % 2 == 0: base += 1

    kernels = [
        cv.getStructuringElement(cv.MORPH_RECT,    (base, 1)),
        cv.getStructuringElement(cv.MORPH_RECT,    (1, base)),
        cv.getStructuringElement(cv.MORPH_CROSS,   (base, base)),
        cv.getStructuringElement(cv.MORPH_ELLIPSE, (base, base)),
    ]

    tophats = [cv.morphologyEx(Y_8b, cv.MORPH_TOPHAT, k) for k in kernels]
    tophat_combined = np.max(np.stack(tophats), axis=0)

    # 4) Normalização do resultado do Top-Hat
    tophat_norm = ((tophat_combined - tophat_combined.min()) /
                (tophat_combined.max() - tophat_combined.min()) * 255).astype(np.uint8)

    # 5) Stretch linear para 0–255 (opcional se já normalizado)
    minv, maxv = tophat_norm.min(), tophat_norm.max()
    stretched = ((tophat_norm - minv) / (maxv - minv) * 255).astype(np.uint8)

    # 6) Focar na faixa clara (percentil + delta)
    p = 98
    min_i = int(np.percentile(stretched, p))
    delta = 10
    max_i = min(255, min_i + delta)
    foco = np.clip(stretched, min_i, max_i)
    foco_norm = ((foco - min_i) / (max_i - min_i) * 255).astype(np.uint8)

    # 7) Threshold final (Otsu ou manual)
    _, bin_final = cv.threshold(foco_norm, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)

    # 8) Limpeza pós-threshold (filtro por área e closing)
    conts, _ = cv.findContours(bin_final, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    output = np.zeros_like(bin_final)
    # área mínima adaptativa opcional
    min_area = 2000 * (h * w) / (3456 * 4608)
    for c in conts:
        if cv.contourArea(c) > min_area:
            cv.drawContours(output, [c], -1, 255, -1)

    # closing multi-kernel para unir falhas
    closed = np.zeros_like(output)
    for sz in [(20,1),(1,20),(15,15)]:
        k = cv.getStructuringElement(cv.MORPH_RECT, sz)
        closed |= cv.morphologyEx(output, cv.MORPH_CLOSE, k)

    return closed

def segment_algorithm_2(image):
  # 1) Segmentar o ovo do fundo
  gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
  blur = cv.GaussianBlur(gray, (5, 5), 0)
  _, thresh = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
  thresh = cv.bitwise_not(thresh)  # ovo branco, fundo preto

  contours, _ = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
  filtered = [c for c in contours if cv.contourArea(c) > 1000]
  main = max(filtered, key=cv.contourArea)

  mask = np.zeros_like(gray)
  cv.drawContours(mask, [main], -1, 255, -1)
  segmented = cv.bitwise_and(image, image, mask=mask)
  x, y, w, h = cv.boundingRect(main)
  egg_rgb = segmented[y:y+h, x:x+w]

  # 2) Converte para YIQ e extrai luminância em 8-bits
  egg_yiq = color.rgb2yiq(egg_rgb)
  Y, I, Q = cv.split(egg_yiq)
  Y_8b = (Y * 255).astype(np.uint8)

  from skimage.filters import frangi

  # 3) Realce de estruturas finas (rachaduras)
  frangi_img = frangi(Y_8b, sigmas=(5,5), scale_step=2)

  # Normalizar para 0–255
  frangi_norm = (255 * (frangi_img - frangi_img.min()) / np.ptp(frangi_img)).astype(np.uint8)

  # 6) Focar na faixa clara (percentil + delta)
  p = 98
  min_i = int(np.percentile(frangi_norm, p))
  delta = 10
  max_i = min(255, min_i + delta)
  foco = np.clip(frangi_norm, min_i, max_i)
  foco_norm = ((foco - min_i) / (max_i - min_i) * 255).astype(np.uint8)

  # 7) Threshold final (Otsu ou manual)
  _, bin_final = cv.threshold(foco_norm, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)

  return bin_final


# def crack_detection(image: np.ndarray) -> PIL.Image.Image:
#     '''makes a prediction'''
#     # getting results
#     bgr_image = cv.cvtColor(image, cv.COLOR_RGB2BGR)
#     yolo_result = detection_model.predict(bgr_image, verbose=True)[0]
#     result_img_bgr = yolo_result.plot()
#     result_img_rgb = PIL.Image.fromarray(cv.cvtColor(result_img_bgr, cv.COLOR_BGR2RGB))

#     return result_img_rgb


def crack_classification(image: np.ndarray, yolo_model: YOLO) -> str:
    """
    Makes a classification prediction for cracked/uncracked eggs.
    """
    # Convert to BGR (YOLO expects BGR)
    bgr_image = cv.cvtColor(image, cv.COLOR_RGB2BGR)
    
    # Run prediction
    yolo_result = yolo_model.predict(bgr_image, verbose=True, save=True)[0]
    result_img_bgr = yolo_result.plot()
    result_img_rgb = PIL.Image.fromarray(cv.cvtColor(result_img_bgr, cv.COLOR_BGR2RGB))

    return result_img_rgb

'''
def process_image(image, dropdown):
    if image is None:
        return None
    
    no_shadow_img = remove_shadows(image)

    if dropdown == 'Shadow Removal':
        return no_shadow_img
    elif dropdown == 'Segmentation 1':
        segmented_image = segment_algorithm_1(no_shadow_img)
        return segmented_image
    elif dropdown == 'Segmentation 2':
        segmented_image = segment_algorithm_2(no_shadow_img)
        return segmented_image
    elif dropdown == 'Crack Classification':
        segmented_image = segment_algorithm_2(no_shadow_img)
        classification = crack_classification(segmented_image, classification_model)
        return classification
    elif dropdown == 'Crack Classification 2':
        segmented_image = segment_algorithm_2(no_shadow_img)
        classification = crack_classification(segmented_image, classification_model_2)
        return classification
    elif dropdown == 'Crack Classification 3':
        segmented_image = segment_algorithm_2(no_shadow_img)
        classification = crack_classification(segmented_image, classification_model_3)
        return classification
    elif dropdown == 'Crack Classification 4':
        segmented_image = segment_algorithm_2(no_shadow_img)
        classification = crack_classification(segmented_image, classification_model_4)
        return classification
    elif dropdown == 'yolov8n-cls_egg_cls_4_epochs':
        segmented_image = segment_algorithm_2(no_shadow_img)
        classification = crack_classification(segmented_image, classification_model_5)
        return classification
    # elif dropdown == 'Crack Detection':
    #     segmented_image = segment_algorithm_2(no_shadow_img)
    #     result_img = crack_detection(segmented_image)
    #     return result_img
'''

def process_image(image, dropdown):
    if image is None:
        return None
    
    no_shadow_img = remove_shadows(image)

    if dropdown == 'Shadow Removal':
        return no_shadow_img
    elif dropdown == '1º Segmentation Algorithm':
        segmented_image = segment_algorithm_1(no_shadow_img)
        return segmented_image
    elif dropdown == '2º Segmentation Algorithm':
        segmented_image = segment_algorithm_2(no_shadow_img)
        return segmented_image

    segmented_image = segment_algorithm_2(no_shadow_img)
    classification = crack_classification(segmented_image, model_table[dropdown])
    return classification

def clear_image():
    return None