-
Notifications
You must be signed in to change notification settings - Fork 0
/
video_translate.py
91 lines (69 loc) · 2.65 KB
/
video_translate.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
"""
To Run:
python video_translate.py <video_name>
"""
import cv2
import numpy as np
from scipy.stats import mode
import sys
import tensorflow as tf
CATEGORIES = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'nothing', 'space']
def prepare(frame, model_name):
# making the frame square by cropping
orig_width, orig_height, channel = frame.shape
req_dim = min(orig_width, orig_height)
frame = frame[orig_width//2-req_dim//2:orig_width//2+req_dim //
2, orig_height//2-req_dim//2:orig_height//2+req_dim//2]
if model_name == 'basic' or model_name == 'basic_augmented' or model_name == 'ensemble':
frame = cv2.resize(frame, (224, 224))/255
if model_name == 'efficientnet_b0':
frame = tf.keras.applications.efficientnet.preprocess_input(
cv2.resize(frame, (224, 224))
)
if model_name == 'mobilenet':
frame = tf.keras.applications.mobilenet.preprocess_input(
cv2.resize(frame, (224, 224))
)
return frame.reshape(-1, 224, 224, 3)
def predict(model, frame, model_name):
frame = prepare(frame, model_name)
if model_name == 'ensemble':
prediction = int(mode([np.argmax(m.predict([frame])[0])
for m in model])[0][0])
else:
prediction = int(np.argmax(model.predict([frame])[0]))
return prediction
def main():
models = ['basic',
'basic_augmented',
'efficientnet_b0',
'mobilenet',
'ensemble']
choose_model = int(input(
'Choose model to use:\n1. Basic\n2. Basic trained with Augmented data\n3. Transfer Learning\n4. Transfer Learning trained with Augmented data\n5. Ensemble model\nEnter: '))-1
if choose_model == 4:
model = [tf.keras.models.load_model(
f'models/asl_basic_ensemble_{i}.h5') for i in range(5)]
else:
model = tf.keras.models.load_model(
f'models/asl_{models[choose_model]}.h5')
cap = cv2.VideoCapture(sys.argv[1])
try:
while True:
_, frame = cap.read()
prediction = predict(model, frame, models[choose_model])
final = (CATEGORIES[prediction])
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame, final, (50, 50), font,
1, (0, 0, 0), 2, cv2.LINE_AA)
cv2.imshow('Input', frame)
c = cv2.waitKey(1)
if c == 27: # hit esc key to stop
break
except:
pass
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()