-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.py
67 lines (51 loc) · 1.8 KB
/
demo.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
# Python program using OpenCV and CNN for video trimming using signs
# CNN model trained to exactly predict 2 classes - Up or Down
# Import necessary libraries
import numpy as np
import cv2
import tensorflow.keras
from keras.preprocessing import image
# Access WebCam
cap = cv2.VideoCapture(0)
state = True
# Load the TensorFlow CNN model weights
model = tensorflow.keras.models.load_model('keras_model.h5')
labels = ['thumb_up','thumb_down','random']
# Set the width and height of the frame for video to be saved
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Create a writer object to save the frames
writer = cv2.VideoWriter(r'C:\Users\Sharan Babu\Desktop\trimmed_video.mp4', cv2.VideoWriter_fourcc(*'XVID'),25, (width, height))
final_video = []
while True:
success, image = cap.read()
if success==True:
final_video.append(image)
img = image.copy()
# Draw a rectangle to indicate the region of interest
img = cv2.flip(img,1)
cv2.rectangle(img,pt1=(450,100),pt2=(620,300),color=(0,255,0),thickness=3)
cv2.imshow("Video",img)
roi = img[102:298,448:618]
# Image pre-processing for making predictions of the image
data = cv2.resize(roi,(224,224))
data = np.array(data,dtype=np.float32)
data = np.expand_dims(data,axis=0)
data = data/255
# Predict output class for the image
prediction = model.predict(data)
predicted_class = labels[np.argmax(prediction)]
print(prediction, predicted_class)
if predicted_class == 'thumb_up':
for frame in final_video:
writer.write(frame)
final_video = []
elif predicted_class == 'thumb_down':
final_video = []
# Break the program
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Close webcam and other connections
writer.release()
cap.release()
cv2.destroyAllWindows()