-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlabel_image.py
67 lines (55 loc) · 2.21 KB
/
label_image.py
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
import argparse
import numpy as np
import tensorflow as tf
class create_imageClassify():
def __init__(self):
self.labels = None
self.graph = None
self.sess = None
self.input_operation = None
self.output_operation = None
self.input_layer = "input"
self.output_layer = "InceptionV3/Predictions/Reshape_1"
self.model_file = "./data/inception_v3_2016_08_28_frozen.pb"
self.label_file = "./data/imagenet_slim_labels.txt"
self.input_height = 299
self.input_width = 299
self.input_mean = 0
self.input_std = 255
def load_graph(self):
self.graph = tf.Graph()
graph_def = tf.GraphDef()
with open(self.model_file, "rb") as f:
graph_def.ParseFromString(f.read())
with self.graph.as_default():
tf.import_graph_def(graph_def)
input_name = "import/" + self.input_layer
output_name = "import/" + self.output_layer
self.input_operation = self.graph.get_operation_by_name(input_name)
self.output_operation = self.graph.get_operation_by_name(output_name)
self.sess = tf.compat.v1.Session(graph=self.graph)
def read_tensor_from_image_file(self, frame):
image_reader = frame
float_caster = tf.cast(image_reader, tf.float32)
dims_expander = tf.expand_dims(float_caster, 0)
resized = tf.image.resize_bilinear(
dims_expander, [self.input_height, self.input_width])
normalized = tf.divide(tf.subtract(
resized, [self.input_mean]), [self.input_std])
sess = tf.compat.v1.Session()
result = sess.run(normalized)
return result
def load_labels(self):
label = []
proto_as_ascii_lines = tf.gfile.GFile(self.label_file).readlines()
for l in proto_as_ascii_lines:
label.append(l.rstrip())
return label
def predict(self, frame):
t = self.read_tensor_from_image_file(frame)
results = self.sess.run(self.output_operation.outputs[0], {
self.input_operation.outputs[0]: t
})
results = np.squeeze(results)
top_result = results.argsort()[-1:][::-1]
return results, top_result