-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnew2.py
139 lines (73 loc) · 2.76 KB
/
new2.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
"""Example using TF Lite to classify objects with the Raspberry Pi camera."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import io
import time
import numpy as np
import picamera
import pygame
from PIL import Image
from tflite_runtime.interpreter import Interpreter
from tflite_runtime.interpreter import load_delegate
def load_labels(path):
with open(path, 'r') as f:
return {i: line.strip() for i, line in enumerate(f.readlines())}
def set_input_tensor(interpreter, image):
tensor_index = interpreter.get_input_details()[0]['index']
input_tensor = interpreter.tensor(tensor_index)()[0]
input_tensor[:, :] = image
def classify_image(interpreter, image, top_k=1):
"""Returns a sorted array of classification results."""
set_input_tensor(interpreter, image)
interpreter.invoke()
output_details = interpreter.get_output_details()[0]
output = np.squeeze(interpreter.get_tensor(output_details['index']))
# If the model is quantized (uint8 data), then dequantize the results
if output_details['dtype'] == np.uint8:
scale, zero_point = output_details['quantization']
output = scale * (output - zero_point)
ordered = np.argpartition(-output, top_k)
if (top_k==1) and (output[1] > 0.9):
res = 1
else:
res = 0
return res
def main():
mp3_file = "test_tts.mp3"
pygame.mixer.init()
pygame.mixer.music.load(mp3_file)
labels = "labels.txt"
model = "model_edgetpu.tflite"
interpreter = Interpreter(model, experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
interpreter.allocate_tensors()
_, height, width, _ = interpreter.get_input_details()[0]['shape']
with picamera.PiCamera(resolution=(640, 480), framerate=30) as camera:
print("before cam start")
camera.start_preview()
print("cam start")
try:
stream = io.BytesIO()
for _ in camera.capture_continuous(
stream, format='jpeg', use_video_port=True):
stream.seek(0)
image = Image.open(stream).convert('RGB').resize((width, height),
Image.ANTIALIAS)
start_time = time.time()
results = classify_image(interpreter, image)
print("result:")
print(results)
if results==0:
pygame.mixer.music.play()
# time.sleep(10)
elapsed_ms = (time.time() - start_time) * 1000
# label_id, prob = results[0]
stream.seek(0)
stream.truncate()
# camera.annotate_text = '%s %.2f\n%.1fms' % (labels[label_id], prob,
# elapsed_ms)
finally:
camera.stop_preview()
if __name__ == '__main__':
main()