Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import tensorflow as tf
|
3 |
+
import tensorflow_hub as hub
|
4 |
+
# Load compressed models from tensorflow_hub
|
5 |
+
os.environ['TFHUB_MODEL_LOAD_FORMAT'] = 'COMPRESSED'
|
6 |
+
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
+
import matplotlib as mpl
|
9 |
+
|
10 |
+
# For drawing onto the image.
|
11 |
+
import numpy as np
|
12 |
+
from tensorflow.python.ops.numpy_ops import np_config
|
13 |
+
np_config.enable_numpy_behavior()
|
14 |
+
from PIL import Image
|
15 |
+
from PIL import ImageColor
|
16 |
+
from PIL import ImageDraw
|
17 |
+
from PIL import ImageFont
|
18 |
+
import time
|
19 |
+
|
20 |
+
import streamlit as st
|
21 |
+
|
22 |
+
# For measuring the inference time.
|
23 |
+
import time
|
24 |
+
|
25 |
+
def run_detector(detector, path):
|
26 |
+
# img = load_img_2(path)
|
27 |
+
img = path
|
28 |
+
|
29 |
+
converted_img = tf.image.convert_image_dtype(img, tf.float32)[tf.newaxis, ...]
|
30 |
+
|
31 |
+
start_time = time.time()
|
32 |
+
result = detector(converted_img)
|
33 |
+
end_time = time.time()
|
34 |
+
|
35 |
+
result = {key:value.numpy() for key,value in result.items()}
|
36 |
+
|
37 |
+
# print("Found %d objects." % len(result["detection_scores"]))
|
38 |
+
# print("Inference time: ", end_time-start_time)
|
39 |
+
|
40 |
+
primer = format(result["detection_class_entities"][0]) + ' ' + format(round(result["detection_scores"][0]*100)) + '%'
|
41 |
+
|
42 |
+
image_with_boxes = draw_boxes(
|
43 |
+
img, result["detection_boxes"],
|
44 |
+
result["detection_class_entities"], result["detection_scores"])
|
45 |
+
|
46 |
+
display_image(image_with_boxes)
|
47 |
+
return image_with_boxes, primer
|
48 |
+
|
49 |
+
def display_image(image):
|
50 |
+
fig = plt.figure(figsize=(20, 15))
|
51 |
+
plt.grid(False)
|
52 |
+
plt.imshow(image)
|
53 |
+
|
54 |
+
def draw_bounding_box_on_image(image,
|
55 |
+
ymin,
|
56 |
+
xmin,
|
57 |
+
ymax,
|
58 |
+
xmax,
|
59 |
+
color,
|
60 |
+
font,
|
61 |
+
thickness=4,
|
62 |
+
display_str_list=()):
|
63 |
+
"""Adds a bounding box to an image."""
|
64 |
+
draw = ImageDraw.Draw(image)
|
65 |
+
im_width, im_height = image.size
|
66 |
+
(left, right, top, bottom) = (xmin * im_width, xmax * im_width,
|
67 |
+
ymin * im_height, ymax * im_height)
|
68 |
+
draw.line([(left, top), (left, bottom), (right, bottom), (right, top),
|
69 |
+
(left, top)],
|
70 |
+
width=thickness,
|
71 |
+
fill=color)
|
72 |
+
|
73 |
+
# If the total height of the display strings added to the top of the bounding
|
74 |
+
# box exceeds the top of the image, stack the strings below the bounding box
|
75 |
+
# instead of above.
|
76 |
+
display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]
|
77 |
+
# Each display_str has a top and bottom margin of 0.05x.
|
78 |
+
total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)
|
79 |
+
|
80 |
+
if top > total_display_str_height:
|
81 |
+
text_bottom = top
|
82 |
+
else:
|
83 |
+
text_bottom = top + total_display_str_height
|
84 |
+
# Reverse list and print from bottom to top.
|
85 |
+
for display_str in display_str_list[::-1]:
|
86 |
+
text_width, text_height = font.getsize(display_str)
|
87 |
+
margin = np.ceil(0.05 * text_height)
|
88 |
+
draw.rectangle([(left, text_bottom - text_height - 2 * margin),
|
89 |
+
(left + text_width, text_bottom)],
|
90 |
+
fill=color)
|
91 |
+
draw.text((left + margin, text_bottom - text_height - margin),
|
92 |
+
display_str,
|
93 |
+
fill="black",
|
94 |
+
font=font)
|
95 |
+
text_bottom -= text_height - 2 * margin
|
96 |
+
|
97 |
+
def draw_boxes(image, boxes, class_names, scores, max_boxes=10, min_score=0.4):
|
98 |
+
"""Overlay labeled boxes on an image with formatted scores and label names."""
|
99 |
+
colors = list(ImageColor.colormap.values())
|
100 |
+
|
101 |
+
try:
|
102 |
+
font = ImageFont.truetype("./Roboto-Light.ttf", 24)
|
103 |
+
|
104 |
+
except IOError:
|
105 |
+
print("Font not found, using default font.")
|
106 |
+
font = ImageFont.load_default()
|
107 |
+
|
108 |
+
for i in range(min(boxes.shape[0], max_boxes)):
|
109 |
+
if scores[i] >= min_score:
|
110 |
+
ymin, xmin, ymax, xmax = tuple(boxes[i])
|
111 |
+
display_str = "{}: {}%".format(class_names[i].decode("ascii"),
|
112 |
+
int(100 * scores[i]))
|
113 |
+
color = colors[hash(class_names[i]) % len(colors)]
|
114 |
+
image_pil = Image.fromarray(np.uint8(image)).convert("RGB")
|
115 |
+
draw_bounding_box_on_image(
|
116 |
+
image_pil,
|
117 |
+
ymin,
|
118 |
+
xmin,
|
119 |
+
ymax,
|
120 |
+
xmax,
|
121 |
+
color,
|
122 |
+
font,
|
123 |
+
display_str_list=[display_str])
|
124 |
+
np.copyto(image, np.array(image_pil))
|
125 |
+
return image
|
126 |
+
|
127 |
+
def main():
|
128 |
+
image = Image.open('./itaca_logo_2.png')
|
129 |
+
# image_hospital = Image.open('./ust.png')
|
130 |
+
st.image(image,use_column_width=False)
|
131 |
+
# st.sidebar.info('This app is created to detect objects in a picture')
|
132 |
+
# st.sidebar.image(image_hospital)
|
133 |
+
# st.sidebar.success('https://www.ust.com')
|
134 |
+
st.title("Object Detector :sunglasses:")
|
135 |
+
|
136 |
+
# filename = file_selector(FILE_PATH)
|
137 |
+
|
138 |
+
img_file_buffer = st.file_uploader("Carga una imagen", type=["png", "jpg", "jpeg"])
|
139 |
+
if img_file_buffer is not None:
|
140 |
+
image = np.array(Image.open(img_file_buffer))
|
141 |
+
# st.image(image, caption="Imagen", use_column_width=True)
|
142 |
+
|
143 |
+
module_handle = "https://tfhub.dev/google/faster_rcnn/openimages_v4/inception_resnet_v2/1"
|
144 |
+
# module_handle = "https://tfhub.dev/google/openimages_v4/ssd/mobilenet_v2/1"
|
145 |
+
|
146 |
+
detector = hub.load(module_handle).signatures['default']
|
147 |
+
|
148 |
+
if st.button("Prediction"):
|
149 |
+
# img, primero = run_detector(detector, filename)
|
150 |
+
img, primero = run_detector(detector, image)
|
151 |
+
# primero = run_detector(detector, image)
|
152 |
+
st.success('The first image detected is: ' + primero)
|
153 |
+
st.image(img, caption="Imagen", use_column_width=True)
|
154 |
+
|
155 |
+
|
156 |
+
|
157 |
+
if __name__ == '__main__':
|
158 |
+
main()
|