asaderu commited on
Commit
4c38319
·
1 Parent(s): 307898e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -0
app.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import numpy as np
3
+ import gradio as gr
4
+ from tensorflow.keras.models import load_model
5
+ import imutils
6
+ import matplotlib.pyplot as plt
7
+ import cv2
8
+ import numpy as np
9
+ from tensorflow.keras.preprocessing.image import img_to_array
10
+ from PIL import Image
11
+
12
+ PROB_THRESHOLD = 0.4 # Minimum probably to show results.
13
+ class Model:
14
+ def __init__(self, model_filepath):
15
+ self.graph_def = tensorflow.compat.v1.GraphDef()
16
+ self.graph_def.ParseFromString(model_filepath.read_bytes())
17
+
18
+ input_names, self.output_names = self._get_graph_inout(self.graph_def)
19
+ assert len(input_names) == 1 and len(self.output_names) == 3
20
+ self.input_name = input_names[0]
21
+ self.input_shape = self._get_input_shape(self.graph_def, self.input_name)
22
+
23
+ def predict(self, image_filepath):
24
+ image = Image.fromarray(image_filepath).resize(self.input_shape)
25
+ input_array = np.array(image, dtype=np.float32)[np.newaxis, :, :, :]
26
+
27
+ with tensorflow.compat.v1.Session() as sess:
28
+ tensorflow.import_graph_def(self.graph_def, name='')
29
+ out_tensors = [sess.graph.get_tensor_by_name(o + ':0') for o in self.output_names]
30
+ outputs = sess.run(out_tensors, {self.input_name + ':0': input_array})
31
+ return {name: outputs[i][np.newaxis, ...] for i, name in enumerate(self.output_names)}
32
+
33
+ @staticmethod
34
+ def _get_graph_inout(graph_def):
35
+ input_names = []
36
+ inputs_set = set()
37
+ outputs_set = set()
38
+
39
+ for node in graph_def.node:
40
+ if node.op == 'Placeholder':
41
+ input_names.append(node.name)
42
+
43
+ for i in node.input:
44
+ inputs_set.add(i.split(':')[0])
45
+ outputs_set.add(node.name)
46
+
47
+ output_names = list(outputs_set - inputs_set)
48
+ return input_names, output_names
49
+
50
+ @staticmethod
51
+ def _get_input_shape(graph_def, input_name):
52
+ for node in graph_def.node:
53
+ if node.name == input_name:
54
+ return [dim.size for dim in node.attr['shape'].shape.dim][1:3]
55
+
56
+ def print_outputs(outputs, gambar):
57
+ image = gambar
58
+ assert set(outputs.keys()) == set(['detected_boxes', 'detected_classes', 'detected_scores'])
59
+ l, t, d = image.shape
60
+ labelopen = open("labels.txt", 'r')
61
+ labels = [line.split(',') for line in labelopen.readlines()]
62
+ for box, class_id, score in zip(outputs['detected_boxes'][0], outputs['detected_classes'][0], outputs['detected_scores'][0]):
63
+ if score > PROB_THRESHOLD:
64
+ print(f"Label: {class_id}, Probability: {score:.5f}, box: ({box[0]:.5f}, {box[1]:.5f}) ({box[2]:.5f}, {box[3]:.5f})")
65
+ x = box[0] * t
66
+ y = box[1] * l
67
+ h = box[2] * t
68
+ w = box[3] * l
69
+ result_image = cv2.rectangle(image, (int(x), int(y)), (int(h), int(w)), (255,215,0), 3)
70
+ cv2.putText(result_image, labels[int(class_id)][0], (int(x), int(y)-10), fontFace = cv2.FONT_HERSHEY_SIMPLEX, fontScale = 0.5, color = (255,215,0), thickness = 2)
71
+ return result_image
72
+
73
+
74
+
75
+
76
+ def main(gambar):
77
+ p = pathlib.Path("model.pb")
78
+ #b = pathlib.Path(gambar)
79
+ model = Model(p)
80
+ outputs = model.predict(gambar)
81
+
82
+ return print_outputs(outputs, gambar)
83
+
84
+ demo = gr.Interface(main, gr.Image(shape=(500, 500)), "image")
85
+ demo.launch()