ojoel98 commited on
Commit
0413d20
verified
1 Parent(s): 57827d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -85
app.py CHANGED
@@ -1,25 +1,15 @@
1
 
2
  import torch
3
- TORCH_VERSION = ".".join(torch.__version__.split(".")[:2])
4
- CUDA_VERSION = torch.version.cuda
5
- print("torch:", TORCH_VERSION, "; cuda:", CUDA_VERSION)
6
-
7
- # Commented out IPython magic to ensure Python compatibility.
8
- # Importaci贸n de bibliotecas
9
  import pandas as pd
10
- import os, cv2, sys
11
  import matplotlib.pyplot as plt
12
- import ipywidgets as widgets
13
- # %matplotlib auto
14
 
15
- # Importaci贸n de los paquetes de Detectron2
16
  from detectron2 import model_zoo
17
  from detectron2.engine import DefaultPredictor
18
  from detectron2.config import get_cfg
19
  from detectron2.utils.visualizer import Visualizer
20
  from detectron2.data import catalog
21
-
22
- # importar m贸dulos colab_zirc_dims
23
  from colab_zirc_dims import save_load
24
  from colab_zirc_dims import alc_notebook_fxns
25
  from colab_zirc_dims import zirc_dims_GUI
@@ -34,80 +24,56 @@ try:
34
  except ModuleNotFoundError:
35
  from colab_zirc_dims.jupyter_colab_compat import output_local as output
36
 
37
- from PIL import Image
38
- import skimage.io
39
-
40
- import gradio as gr
41
-
42
- from google.colab import drive
43
- drive.mount('/content/gdrive')
44
-
45
- # Commented out IPython magic to ensure Python compatibility.
46
- def generate_medition(sample_img,Escala):
47
- #sample_img = im.convert('RGB')
48
- #print(sample_img.shape)
49
- #input()
50
-
51
- from PIL import Image
52
- im = Image.fromarray(sample_img)
53
- im.save("sample_image.jpg")
54
- fn = 'sample_image.jpg'
55
- filepath = '/content/sample_image.jpg'
56
- #Escala = 3
57
- selected_samples = []
58
- sample_img
59
- loaded_data_dict = {fn: {fn: {'img_file': filepath, 'Align_file': '', 'rel_file': fn, 'scale_factor': Escala, 'scale_from': 'default (1.0)'}}}
60
- #print(loaded_data_dict)
61
- #input()
62
- alc_notebook_fxns.select_samples_fxn(loaded_data_dict, selected_samples)
63
-
64
- model_lib_loc = 'default'
65
- current_model_dict = {}
66
- alc_notebook_fxns.select_download_model_interface(current_model_dict, model_lib_loc)
67
-
68
- grain_metadata = catalog.Metadata(name='grain_meta', thing_classes=['grain'])
69
- predictor = non_std_cfgs.smart_load_predictor(
70
- current_model_dict['selected_config_yaml'],
71
- current_model_dict['selected_model_weights'],
72
- use_cpu = True,
73
- adj_nms_thresh='auto',
74
- adj_thresh_test='auto')
75
- print('Predictor loaded')
76
-
77
- ROOT_DIR = "/content/drive/MyDrive"
78
- Try_contrast_enhanced_subimage = True
79
- Try_Otsu_thresholding = True
80
- Save_polygons = True
81
- save_polys_bool = Save_polygons
82
- alt_methods = [Try_contrast_enhanced_subimage,
83
- Try_Otsu_thresholding]
84
- full_auto_str = ''
85
- # %matplotlib auto
86
- plt.switch_backend('Agg')
87
- run_dir = gen_notebook_fxns.full_auto_proc(ROOT_DIR, selected_samples, loaded_data_dict,
88
- predictor, save_polys_bool, alt_methods,
89
- full_auto_str, stream_output=False)
90
-
91
- filepath = run_dir + '/mask_images/' + fn + '/' + fn + '.png'
92
- im = Image.open(filepath)
93
- rgb_im = im.convert('RGB')
94
- rgb_im.save('imagef.jpg')
95
- imagef = '/content/imagef.jpg'
96
- from google.colab.patches import cv2_imshow
97
- img = cv2.imread(imagef, cv2.COLOR_BGR2RGB)
98
-
99
-
100
- # Carga de los datos de medici贸n del fragmento de ripios de perforaci贸n
101
- file = run_dir + '/grain_dimensions/' + fn + '_grain_dimensions.csv'
102
- print(file)
103
- df = pd.read_csv(file)
104
- df = df.head()
105
-
106
-
107
-
108
- return img, df
109
 
110
  demo = gr.Interface(fn=generate_medition, inputs=[gr.Image(label="Imagen"), gr.Radio([1,2,3,4,5,6], label="Escala de la imagen")], outputs=[gr.Image(label="Fragmento medido"), gr.Dataframe(label="Tabla de datos")], title="MEDICI脫N DE IM脕GENES DE RIPIOS DE PERFORACI脫N",
111
  description='La siguiente interfaz medir谩 de forma autom谩tica fragmentos en im谩genes de ripios de perforaci贸n. El usuario deber谩 ingresar en la parte de la izquierda la imagen a ser procesada y su escala en um/px, mientras que en la parte de la derecha se mostrar谩 la imagen con el fragmento ya medido y una tabla con los par谩metros medidos y calculados. Se recomienda ingresar im谩genes sin ning煤n tipo de mediciones o s铆mbolos ya que esto podr铆a afectar en la predicci贸n del modelo.',
112
  article='Nota: En el caso de ingresar im谩genes que no tengan relaci贸n a muestras de ripios de perforaci贸n, los autores de esta aplicaci贸n no se hacen responsables por los resultados de estas, el modelo de medici贸n de ripios de perforaci贸n est谩 entrenado para dar un resultado.')
113
- demo.launch()
 
1
 
2
  import torch
 
 
 
 
 
 
3
  import pandas as pd
 
4
  import matplotlib.pyplot as plt
5
+ from PIL import Image
6
+ import gradio as gr
7
 
 
8
  from detectron2 import model_zoo
9
  from detectron2.engine import DefaultPredictor
10
  from detectron2.config import get_cfg
11
  from detectron2.utils.visualizer import Visualizer
12
  from detectron2.data import catalog
 
 
13
  from colab_zirc_dims import save_load
14
  from colab_zirc_dims import alc_notebook_fxns
15
  from colab_zirc_dims import zirc_dims_GUI
 
24
  except ModuleNotFoundError:
25
  from colab_zirc_dims.jupyter_colab_compat import output_local as output
26
 
27
+ def generate_medition(sample_img, Escala):
28
+ # Guardar imagen de muestra
29
+ im = Image.fromarray(sample_img)
30
+ im.save("sample_image.jpg")
31
+ fn = 'sample_image.jpg'
32
+ filepath = '/content/sample_image.jpg'
33
+ selected_samples = []
34
+ loaded_data_dict = {fn: {fn: {'img_file': filepath, 'Align_file': '', 'rel_file': fn, 'scale_factor': Escala, 'scale_from': 'default (1.0)'}}}
35
+ alc_notebook_fxns.select_samples_fxn(loaded_data_dict, selected_samples)
36
+
37
+ model_lib_loc = 'default'
38
+ current_model_dict = {}
39
+ alc_notebook_fxns.select_download_model_interface(current_model_dict, model_lib_loc)
40
+
41
+ grain_metadata = catalog.Metadata(name='grain_meta', thing_classes=['grain'])
42
+ predictor = non_std_cfgs.smart_load_predictor(
43
+ current_model_dict['selected_config_yaml'],
44
+ current_model_dict['selected_model_weights'],
45
+ use_cpu=True,
46
+ adj_nms_thresh='auto',
47
+ adj_thresh_test='auto')
48
+ print('Predictor loaded')
49
+
50
+ Try_contrast_enhanced_subimage = True
51
+ Try_Otsu_thresholding = True
52
+ Save_polygons = True
53
+ save_polys_bool = Save_polygons
54
+ alt_methods = [Try_contrast_enhanced_subimage, Try_Otsu_thresholding]
55
+ full_auto_str = ''
56
+ plt.switch_backend('Agg')
57
+ run_dir = gen_notebook_fxns.full_auto_proc('/content/', selected_samples, loaded_data_dict,
58
+ predictor, save_polys_bool, alt_methods,
59
+ full_auto_str, stream_output=False)
60
+
61
+ filepath = run_dir + '/mask_images/' + fn + '/' + fn + '.png'
62
+ im = Image.open(filepath)
63
+ rgb_im = im.convert('RGB')
64
+ rgb_im.save('imagef.jpg')
65
+ imagef = '/content/imagef.jpg'
66
+ img = cv2.imread(imagef, cv2.COLOR_BGR2RGB)
67
+
68
+ # Carga de los datos de medici贸n del fragmento de ripios de perforaci贸n
69
+ file = run_dir + '/grain_dimensions/' + fn + '_grain_dimensions.csv'
70
+ print(file)
71
+ df = pd.read_csv(file)
72
+ df = df.head()
73
+
74
+ return img, df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  demo = gr.Interface(fn=generate_medition, inputs=[gr.Image(label="Imagen"), gr.Radio([1,2,3,4,5,6], label="Escala de la imagen")], outputs=[gr.Image(label="Fragmento medido"), gr.Dataframe(label="Tabla de datos")], title="MEDICI脫N DE IM脕GENES DE RIPIOS DE PERFORACI脫N",
77
  description='La siguiente interfaz medir谩 de forma autom谩tica fragmentos en im谩genes de ripios de perforaci贸n. El usuario deber谩 ingresar en la parte de la izquierda la imagen a ser procesada y su escala en um/px, mientras que en la parte de la derecha se mostrar谩 la imagen con el fragmento ya medido y una tabla con los par谩metros medidos y calculados. Se recomienda ingresar im谩genes sin ning煤n tipo de mediciones o s铆mbolos ya que esto podr铆a afectar en la predicci贸n del modelo.',
78
  article='Nota: En el caso de ingresar im谩genes que no tengan relaci贸n a muestras de ripios de perforaci贸n, los autores de esta aplicaci贸n no se hacen responsables por los resultados de estas, el modelo de medici贸n de ripios de perforaci贸n est谩 entrenado para dar un resultado.')
79
+ demo.launch()