Spaces:
Sleeping
Sleeping
Download utils.py from UrielWerneck/ClearVision: direct link, hf CLI and curl.
- Browser
- Download file 9.92 kB
-
https://huggingface.co/spaces/UrielWerneck/ClearVision/resolve/main/utils.py
- Command line
-
hf download hf://spaces/UrielWerneck/ClearVision/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/UrielWerneck/ClearVision/resolve/main/utils.py
9.92 kB
| 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 |