File size: 4,619 Bytes
fa297e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a3c1bb
fa297e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1105152
fa297e7
 
 
 
 
 
 
 
 
 
 
 
1105152
fa297e7
 
 
4ec6882
fa297e7
 
 
1105152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a3c1bb
 
 
1105152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import gradio as gr
import cv2
from matplotlib import pyplot as plt
import numpy as np
from typing import List
from ultralytics import YOLO
import cv2
import numpy as np
import os
import shutil


def recortar_notas(imagen_path: str) -> int:
    if os.path.exists('deteccion'):
        shutil.rmtree('deteccion')
    if os.path.exists('diarios'):
        shutil.rmtree('diarios')
    if os.path.exists('recorte'):
        shutil.rmtree('recorte')
    
    model = YOLO("seg-640.pt")
    results = model.predict(source=imagen_path, save=True, save_txt=True, project="diarios", classes=0, conf=0.5) 

    # cargar imagen tif
    image = cv2.imread(imagen_path)

    # crear una carpeta para guardar los recortes
    filename = os.path.splitext(os.path.basename(results[0].path))[0]
    foldername = os.path.splitext(filename)[0]
    if not os.path.exists(f"recorte/{foldername}"):
        os.makedirs(f"recorte/{foldername}")

    datos = results[0].masks.xy

    num_notas = 0

    for i, coords in enumerate(datos): 
        # coordenadas de segmentación
        coordenadas = np.array(coords)

        # crear una máscara vacía
        mask = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)

        # dibujar un polígono en la máscara
        cv2.fillPoly(mask, [coordenadas.astype(np.int32)], 255)

        # aplicar la máscara a la imagen
        masked = cv2.bitwise_and(image, image, mask=mask)

        # recortar la imagen utilizando la caja delimitadora de la máscara
        x, y, w, h = cv2.boundingRect(mask)
        recorte = masked[y:y+h, x:x+w]

        # guardar el recorte como una imagen
        recorte_path = os.path.join(f"recorte/{foldername}", f"nota {i}.jpg")
        cv2.imwrite(recorte_path, recorte)

        num_notas += 1
    
    noticias(foldername)
    segmentacion = f"diarios/predict/{filename}.png"
    segmentacion = cv2.imread(segmentacion)
    recorte1 = f"recorte/{foldername}/nota 0.jpg"
    prediccion = f"deteccion/{foldername}/predict/nota 0.jpg"
        
    try:
        recorte2 = f"recorte/{foldername}/nota 1.jpg"
        prediccion2 = f"deteccion/{foldername}/predict/nota 1.jpg"
        if not os.path.exists(recorte2):
            raise Exception(f"El archivo {recorte2} no existe.")
    except:
          recorte2 = "sin_nota.jpg"
          prediccion2 = "sin_nota.jpg"
    
    return segmentacion, prediccion, prediccion2, num_notas

def noticias(carpeta):
        nombre = carpeta
        model = YOLO("best-detect.pt")
        results = model.predict(source=f"recorte/{nombre}", save=True, save_txt=True,project=f"deteccion/{nombre}", conf=0.75)  # save plotted images
        return print(f"Imagen {nombre} procesada correctamente")

with gr.Blocks() as demo:
    gr.Markdown(
        """
        <h1 align="center"> IA por la Identidad
        </h1>
        <h2 align="center"> Dathaton 
        </h2>
        """
    )   
    gr.Markdown(
        """
<p align="center">
    <img width = 600 src="https://raw.githubusercontent.com/BonfantiMatias/images/main/banner%20fundaciones.jpeg">
    
</p>

"""
    )

    
    gr.Markdown(
    """
- Puede Seleccionar una de las imagenes de ejemplo o subir una desde su pc
- Para borrar la imagen que esta en la ventana de procesamiento debe presionar la "X" que se encuentra en el vertice superior derecho.
- Las imagenes .tif pueden ser procesadas pero no tienen previsualizacion.
- Para Iniciar el modelo Precionar el Boton "Iniciar Modelo" que se encuentra en la parte inferior 
"""
    )
    with gr.Row():
            seed = gr.components.Image(type="filepath", label="Input") 
            with gr.Row():
                with gr.Column():
                        gr.Examples(["Ambito2.jpg"], inputs=[seed])
                        gr.Examples(["Clarin2.jpg"], inputs=[seed])
                        
                with gr.Column():
                        gr.Examples(["Popular.jpg"], inputs=[seed])
                        gr.Examples(["Clarin3.jpg"], inputs=[seed])

    with gr.Row():
                notas = gr.Label(label="Numero de Notas")
      
    with gr.Row():
            
        with gr.Column():
            segmentacion = gr.Image(label="Segmentacion Notas")
        with gr.Column():
            prediccion = gr.Image(label="Prediccion Primera Nota")
        with gr.Column():
            prediccion2 = gr.Image(label="Prediccion Segunda Nota")

    with gr.Row():
        btn = gr.Button("Procesar Imagen")
        btn.click(recortar_notas, inputs=[seed], outputs=[segmentacion, prediccion, prediccion2, notas])          
          
if __name__ == "__main__":
    demo.launch()