Spaces:
Runtime error
Runtime error
File size: 9,122 Bytes
27263a7 |
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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 |
#!/usr/bin/env python
# coding: utf-8
# In[30]:
import cv2
import numpy as np
import tensorflow as tf
#from sklearn.metrics import confusion_matrix
import itertools
import os, glob
from tqdm import tqdm
#from efficientnet.tfkeras import EfficientNetB4
import tensorflow as tf
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
from tensorflow.keras.utils import img_to_array, array_to_img
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
import pandas as pd
import numpy as np
import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from sklearn.preprocessing import LabelBinarizer
from IPython.display import clear_output
import warnings
warnings.filterwarnings('ignore')
import cv2
import gradio as gr
# In[46]:
labels = {0: 'Normal', 1: 'RoadAccidents', 2: 'Violent'}
# In[47]:
model = keras.models.load_model("AniketModel.h5", compile=False)
# In[48]:
def videoToFrames(video):
# Read the video from specified path
cam = cv2.VideoCapture(video)
'''
try:
# creating a folder named data
if not os.path.exists('/home/shubham/__New-D__/VITA/Project/redundant/data/Abuse'):
os.makedirs('/home/shubham/__New-D__/VITA/Project/redundant/data/Abuse')
# if not created then raise error
except OSError:
print ('Error: Creating directory of data')
'''
# frame
currentframe = 1
while(True):
# reading from frame
ret,frame = cam.read()
if ret:
# if video is still left continue creating images
# name = '/home/shubham/__New-D__/VITA/Project/redundant/data/Abuse/frame' + str(currentframe) + '.jpg'
# print ('Creating...' + name)
# writing the extracted images
# cv2.imwrite(name, frame)
# increasing counter so that it will
# show how many frames are created
currentframe += 1
else:
break
# Release all space and windows once done
cam.release()
cv2.destroyAllWindows()
return currentframe
# In[49]:
def hconcat_resize(img_list, interpolation=cv2.INTER_CUBIC):
# take minimum hights
h_min = min(img.shape[0] for img in img_list)
# image resizing
im_list_resize = [cv2.resize(img,
(int(img.shape[1] * h_min / img.shape[0]),
h_min), interpolation
= interpolation)
for img in img_list]
return cv2.hconcat(im_list_resize)
# In[55]:
def make_average_predictions(video_file_path, predictions_frames_count):
confidences = {}
number_of_classes = 3
# Initializing the Numpy array which will store Prediction Probabilities
#predicted_labels_probabilities_np = np.zeros((predictions_frames_count, number_of_classes), dtype = np.float)
# Reading the Video File using the VideoCapture Object
video_reader = cv2.VideoCapture(video_file_path)
#print(video_reader)
# Getting The Total Frames present in the video
video_frames_count = int(video_reader.get(cv2.CAP_PROP_FRAME_COUNT))
# print(video_frames_count)
# Calculating The Number of Frames to skip Before reading a frame
skip_frames_window = video_frames_count // predictions_frames_count
# print(skip_frames_window)
frame_counter = 1
count = 0
features = []
for frame_counter in range(predictions_frames_count):
try:
frames = []
# Setting Frame Position
#video_reader.set(cv2.CAP_PROP_POS_FRAMES, frame_counter * skip_frames_window)
# Reading The Frame
_ , frame = video_reader.read()
#print(frame)
image_height, image_width = 128, 128
# Resize the Frame to fixed Dimensions
resized_frame = cv2.resize(frame, (image_height, image_width))
# Normalize the resized frame by dividing it with 255 so that each pixel value then lies between 0 and 1
normalized_frame = resized_frame / 255
#print(normalized_frame)
#normalized_frame = np.vstack([normalized_frame])
#normalized_frame = image.img_to_array(normalized_frame)
#print(frs.shape)
#print(normalized_frame.shape)
#normalized_frame = image.array_to_img(normalized_frame)
frames.append(normalized_frame)
if frame_counter % 16 == 0:
#frs = np.append(frs, normalized_frame)
#print(frames)
images = cv2.hconcat(frames)
#cv2.imshow('', images)
images = cv2.resize(images, (128, 128))
#images = images / 255
X = image.img_to_array(images)
X = np.expand_dims(X, axis=0)
images = np.vstack([X])
#print(images.shape)
#print(images)
# Passing the Image Normalized Frame to the model and receiving Predicted Probabilities.
predicted_labels_probabilities = model.predict(images)
#print(predicted_labels_probabilities)
#predicted_labels_probabilities = model.predict(images)[0]
# Appending predicted label probabilities to the deque object
predicted_labels_probabilities = np.squeeze(predicted_labels_probabilities)
print(predicted_labels_probabilities)
#predicted_labels_probabilities_np[frame_counter] = predicted_labels_probabilities
prediction = np.argmax(predicted_labels_probabilities)
print(prediction)
output = labels[prediction]
print(output)
if normalized_frame is not None:
features.append(prediction)
#print(frame_counter)
#print(features)
frames = []
if count < 10:
count += 1
#print(count)
else:
break
except:
break
"""# Calculating Average of Predicted Labels Probabilities Column Wise
predicted_labels_probabilities_averaged = predicted_labels_probabilities_np.mean(axis = 0)
# Sorting the Averaged Predicted Labels Probabilities
predicted_labels_probabilities_averaged_sorted_indexes = np.argsort(predicted_labels_probabilities_averaged)[::-1]
predicted_labels_probabilities_averaged_sorted_indexes = predicted_labels_probabilities_averaged_sorted_indexes[:3]
# Iterating Over All Averaged Predicted Label Probabilities
for predicted_label in predicted_labels_probabilities_averaged_sorted_indexes:
# Accessing The Class Name using predicted label.
predicted_class_name = labels[predicted_label]
# Accessing The Averaged Probability using predicted label.
predicted_probability = predicted_labels_probabilities_averaged[predicted_label]
print(f"CLASS NAME: {predicted_class_name} AVERAGED PROBABILITY: {(predicted_probability*100):.2}")
confidences[predicted_class_name]=predicted_probability
# Closing the VideoCapture Object and releasing all resources held by it.
video_reader.release()"""
return confidences, features
# In[56]:
def most_frequent(List):
counter = 0
num = List[0]
for i in List:
curr_frequency = List.count(i)
if(curr_frequency> counter):
counter = curr_frequency
num = i
return num
# In[64]:
video = "/home/shubham/__New-D__/VITA/Project/redundant/production ID_4959443.mp4"
#labels = {0: 'RoadAccidents', 1: 'Normal', 2: 'Violent'}
framecount = videoToFrames(video)
confidences, features = make_average_predictions(video, framecount)
List = most_frequent(features)
print("The Video You Have Entered is of",labels.get(List))
#print(confidences)
# In[53]:
"""def classify_video(video):
labels = {0: 'RoadAccidents', 1: 'Normal', 2: 'Violent'}
framecount = videoToFrames(video)
confidences, features = make_average_predictions(video, framecount)
List = most_frequent(features)
#print("The Video You Have Entered is of",labels.get(List))
return labels.get(List)
demo = gr.Interface(classify_video,
inputs=gr.Video(),
outputs=gr.outputs.Label(),
cache_examples=True)
if __name__ == "__main__":
demo.launch(share=False)"""
# In[ ]:
# In[ ]:
|