Spaces:
Sleeping
Sleeping
Commit
路
39f28ba
1
Parent(s):
28c3993
Update app.py
Browse files
app.py
CHANGED
@@ -4,6 +4,151 @@ from fastai.vision.all import *
|
|
4 |
import PIL
|
5 |
import torchvision.transforms as transforms
|
6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
#repo_id = "Ignaciobfp/segmentacion-dron-marras"
|
8 |
#learner = from_pretrained_fastai(repo_id)
|
9 |
|
|
|
4 |
import PIL
|
5 |
import torchvision.transforms as transforms
|
6 |
|
7 |
+
##Extras por si pudiera reconstruir la imagen en HF tambi茅n
|
8 |
+
import os
|
9 |
+
import re
|
10 |
+
|
11 |
+
def subimages_from_directory(directorio):
|
12 |
+
# Define el directorio a recorrer
|
13 |
+
directorio = directorio
|
14 |
+
|
15 |
+
# Define la expresi贸n regular para buscar los n煤meros X e Y en el nombre de archivo
|
16 |
+
patron = re.compile(r"(.*)_(\d+)_(\d+)\.(png|jpg|tif)")
|
17 |
+
|
18 |
+
windowlist = []
|
19 |
+
coords = []
|
20 |
+
|
21 |
+
# Recorre el directorio en busca de im谩genes
|
22 |
+
for filename in os.listdir(directorio):
|
23 |
+
match = patron.search(filename)
|
24 |
+
if match:
|
25 |
+
origname = match.group(1)
|
26 |
+
x = int(match.group(2))
|
27 |
+
y = int(match.group(3))
|
28 |
+
#print(f"El archivo {filename} tiene los n煤meros X={x} e Y={y}")
|
29 |
+
img = cv2.imread(os.path.join(directorio, filename))
|
30 |
+
windowlist.append(img)
|
31 |
+
coords.append((x, y))
|
32 |
+
|
33 |
+
# Ordena las listas por coordenadas X e Y
|
34 |
+
windowlist, coords = zip(*sorted(zip(windowlist, coords), key=lambda pair: (pair[1][0], pair[1][1])))
|
35 |
+
wh, ww, chan = windowlist[0].shape
|
36 |
+
origsize = tuple(elem1 + elem2 for elem1, elem2 in zip(coords[-1], (wh,ww)))
|
37 |
+
|
38 |
+
return windowlist, coords, wh, ww, chan, origsize
|
39 |
+
|
40 |
+
def subimages_onlypath(directorio):
|
41 |
+
# Define el directorio a recorrer
|
42 |
+
directorio = directorio
|
43 |
+
pathlist = []
|
44 |
+
|
45 |
+
patron = re.compile(r"(.*)_(\d+)_(\d+)\.(png|jpg|tif)")
|
46 |
+
|
47 |
+
for filename in os.listdir(directorio):
|
48 |
+
match = patron.search(filename)
|
49 |
+
if match:
|
50 |
+
pathlist.append(os.path.join(directorio, filename))
|
51 |
+
|
52 |
+
return pathlist
|
53 |
+
|
54 |
+
def ReconstructFromMW(windowlist, coords, wh, ww, chan, origsize):
|
55 |
+
canvas = np.zeros((origsize[1], origsize[0], chan), dtype=np.uint8)
|
56 |
+
for idx, window in enumerate(windowlist):
|
57 |
+
canvas[coords[idx][1]:coords[idx][1]+wh, coords[idx][0]:coords[idx][0]+ww, :] = window
|
58 |
+
return canvas
|
59 |
+
|
60 |
+
def get_list_tp(path):
|
61 |
+
list_to_process = [] # Inicializar la lista que contendr谩 los nombres de los subdirectorios
|
62 |
+
list_names = []
|
63 |
+
# Recorrer los elementos del directorio
|
64 |
+
for element in os.scandir(path):
|
65 |
+
# Verificar si el elemento es un directorio
|
66 |
+
if element.is_dir():
|
67 |
+
# Agregar el nombre del subdirectorio a la lista
|
68 |
+
windowlist, coords, wh, ww, chan, origsize = subimages_from_directory(element)
|
69 |
+
list_to_process.append(ReconstructFromMW(windowlist, coords, wh, ww, chan, origsize))
|
70 |
+
list_names.append(element.name)
|
71 |
+
return list_to_process, list_names
|
72 |
+
|
73 |
+
def get_paths_tp(path):
|
74 |
+
list_to_process = [] # Inicializar la lista que contendr谩 los nombres de los subdirectorios
|
75 |
+
# Recorrer los elementos del directorio
|
76 |
+
for element in os.scandir(path):
|
77 |
+
# Verificar si el elemento es un directorio
|
78 |
+
if element.is_dir():
|
79 |
+
# Agregar el nombre del subdirectorio a la lista
|
80 |
+
list_to_process.append(subimages_onlypath(element))
|
81 |
+
return list_to_process
|
82 |
+
|
83 |
+
def process_multifolder(process_folders, result_folder):
|
84 |
+
for folder in process_folders:
|
85 |
+
folname = os.path.basename(os.path.dirname(folder[0]))
|
86 |
+
destname = Path(result_folder)/folname
|
87 |
+
os.makedirs(destname, exist_ok=True)
|
88 |
+
for subimagepath in folder:
|
89 |
+
img = PIL.Image.open(subimagepath)
|
90 |
+
image = transforms.Resize((400,400))(img)
|
91 |
+
tensor = transform_image(image=image)
|
92 |
+
with torch.no_grad():
|
93 |
+
outputs = model(tensor)
|
94 |
+
outputs = torch.argmax(outputs,1)
|
95 |
+
mask = np.array(outputs.cpu())
|
96 |
+
mask[mask==1]=255
|
97 |
+
mask=np.reshape(mask,(400,400))
|
98 |
+
mask_img = Image.fromarray(mask.astype('uint8'))
|
99 |
+
|
100 |
+
filename = os.path.basename(subimagepath)
|
101 |
+
new_image_path = os.path.join(result_folder, folname, filename)
|
102 |
+
mask_img.save(new_image_path)
|
103 |
+
|
104 |
+
def recombine_windows(results_folder_w, result_f_rec):
|
105 |
+
imgs, nombres = get_list_tp(results_folder_w)
|
106 |
+
os.makedirs(result_f_rec, exist_ok=True)
|
107 |
+
|
108 |
+
for idx, image in enumerate(imgs):
|
109 |
+
img = Image.fromarray(image)
|
110 |
+
new_image_path = os.path.join(result_f_rec, nombres[idx] + '.tif')
|
111 |
+
img.save(new_image_path, compression='tiff_lzw')
|
112 |
+
return new_image_path
|
113 |
+
|
114 |
+
def process_single_image(single_image_path, base_f, pro_f, rsw_f, rsd_f):
|
115 |
+
gss_single(single_image_path, pro_f, 0, "tif", True)
|
116 |
+
process_multifolder(get_paths_tp(pro_f),rsw_f)
|
117 |
+
pt = recombine_windows(rsw_f,rsd_f)
|
118 |
+
shutil.rmtree(pro_f)
|
119 |
+
shutil.rmtree(rsw_f)
|
120 |
+
copiar_info_georref(single_image_path, pt)
|
121 |
+
return pt
|
122 |
+
|
123 |
+
from osgeo import gdal, osr
|
124 |
+
|
125 |
+
def copiar_info_georref(entrada, salida):
|
126 |
+
try:
|
127 |
+
# Abrir el archivo GeoTIFF original
|
128 |
+
original_dataset = gdal.Open(entrada)
|
129 |
+
|
130 |
+
# Obtener la informaci贸n de georreferenciaci贸n del archivo original
|
131 |
+
original_projection = original_dataset.GetProjection()
|
132 |
+
original_geotransform = original_dataset.GetGeoTransform()
|
133 |
+
|
134 |
+
# Abrir la imagen resultado
|
135 |
+
result_dataset = gdal.Open(salida, gdal.GA_Update)
|
136 |
+
|
137 |
+
# Copiar la informaci贸n de georreferenciaci贸n del archivo original a la imagen resultado
|
138 |
+
result_dataset.SetProjection(original_projection)
|
139 |
+
result_dataset.SetGeoTransform(original_geotransform)
|
140 |
+
|
141 |
+
# Cerrar los archivos
|
142 |
+
original_dataset = None
|
143 |
+
result_dataset = None
|
144 |
+
|
145 |
+
except Exception as e:
|
146 |
+
print("Error: ", e)
|
147 |
+
|
148 |
+
###FIN de extras
|
149 |
+
|
150 |
+
|
151 |
+
|
152 |
#repo_id = "Ignaciobfp/segmentacion-dron-marras"
|
153 |
#learner = from_pretrained_fastai(repo_id)
|
154 |
|