Hii I have a code for flight detection as flight_utils.py
For Youtube Download.
import io
from pytube import YouTube
from IPython.display import HTML
from base64 import b64encode
import os
import cv2
import time
import copy
import glob
import torch
import argparse
import statistics
import threading
import torchvision
import numpy as np
import pandas as pd
import torch.nn as nn
from moviepy.editor import *
import albumentations as A
from collections import deque
#from google.colab.patches import cv2_imshow
def frames_extraction(video_path,SEQUENCE_LENGTH):
'''
This function will extract the required frames from a video after resizing and normalizing them.
Args:
video_path: The path of the video in the disk, whose frames are to be extracted.
SEQUENCE_LENGTH: TThe number of Frames we want.
Returns:
frames_list: A list containing the resized and normalized frames of the video.
'''
code
# Declare a list to store video frames.
frames_list = []
# Read the Video File using the VideoCapture object.
video_reader = cv2.VideoCapture(video_path)
# Get the total number of frames in the video.
video_frames_count = int(video_reader.get(cv2.CAP_PROP_FRAME_COUNT))
# Calculate the the interval after which frames will be added to the list.
skip_frames_window = max(int(video_frames_count/SEQUENCE_LENGTH), 1)
transform= transform_()
# Iterate through the Video Frames.
for frame_counter in range(SEQUENCE_LENGTH):
# Set the current frame position of the video.
video_reader.set(cv2.CAP_PROP_POS_FRAMES, frame_counter * skip_frames_window)
# Reading the frame from the video.
success, frame = video_reader.read()
# Check if Video frame is not successfully read then break the loop
if not success:
break
image = frame.copy()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = transform(image=frame)['image']
# Append the normalized frame into the frames list
frames_list.append(frame)
# Release the VideoCapture object.
video_reader.release()
# Return the frames list.
return frames_list
Assistant
User
5- Detect the Fight on Streaming:
python
Fight_utils.start_streaming(streamingURL)
this is the code for streamling can u use that in my flask
Assistant
User
Assistant
User
you have to write the complete code for eeb cam detection adn show the ouptpu
Assistant
User
Assistant
def create_dataset(DATASET_DIR,CLASSES_LIST,SEQUENCE_LENGTH):
'''
This function will extract the data of the selected classes and create the required dataset.
Returns:
features: A list containing the extracted frames of the videos.
labels: A list containing the indexes of the classes associated with the videos.
'''
code
# Declared Empty Lists to store the features and labels.
features = []
labels = []
# Iterating through all the classes mentioned in the classes list
for class_index, class_name in enumerate(CLASSES_LIST):
# Display the name of the class whose data is being extracted.
print(f'Extracting Data of Class: {class_name}')
# Get the list of video files present in the specific class name directory.
files_list = os.listdir(os.path.join(DATASET_DIR, class_name))
# Iterate through all the files present in the files list.
for file_name in files_list:
# Get the complete video path.
video_file_path = os.path.join(DATASET_DIR, class_name, file_name)
# Extract the frames of the video file.
frames = frames_extraction(video_file_path,SEQUENCE_LENGTH)
# Check if the extracted frames are equal to the SEQUENCE_LENGTH specified above.
# So ignore the vides having frames less than the SEQUENCE_LENGTH.
if len(frames) == SEQUENCE_LENGTH:
# Append the data to their repective lists.
input_frames = np.array(frames)
# transpose to get [3, num_clips, height, width]
input_frames = np.transpose(input_frames, (3,0, 1, 2))
# convert the Frames & Labels to tensor
input_frames = torch.tensor(input_frames, dtype=torch.float32)
label = torch.tensor(int(class_index))
# Append the data to their repective lists and Stack them as Tensor.
features.append(input_frames) # append to list
labels.append(label) # append to list
# Return the frames, class index, and video file path.
return torch.stack(features), torch.stack(labels)
Function To Train the Model From Pytorch Documentation
def train_model(device,model, dataloaders, criterion, optimizer, num_epochs=25, is_inception=False):
since = time.time()
code
val_acc_history = []
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1))
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(phase == 'train'):
# Get model outputs and calculate loss
# Special case for inception because in training it has an auxiliary output. In train
# mode we calculate the loss by summing the final output and the auxiliary output
# but in testing we only consider the final output.
if is_inception and phase == 'train':
# From https://discuss.pytorch.org/t/how-to-optimize-inception-model-with-auxiliary-classifiers/7958
outputs, aux_outputs = model(inputs)
loss1 = criterion(outputs, labels)
loss2 = criterion(aux_outputs, labels)
loss = loss1 + 0.4*loss2
else:
outputs = model(inputs)
loss = criterion(outputs, labels)
_, preds = torch.max(outputs, 1)
# backward + optimize only if in training phase
if phase == 'train':
loss.backward()
optimizer.step()
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / len(dataloaders[phase].dataset)
epoch_acc = running_corrects.double() / len(dataloaders[phase].dataset)
print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))
# deep copy the model
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict())
if phase == 'val':
val_acc_history.append(epoch_acc)
print()
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))
print('Best val Acc: {:4f}'.format(best_acc))
# load best model weights
model.load_state_dict(best_model_wts)
return model, val_acc_history
def PredTopKClass(k, clips, model):
with torch.no_grad(): # we do not want to backprop any gradients
code
input_frames = np.array(clips)
# add an extra dimension
input_frames = np.expand_dims(input_frames, axis=0)
# transpose to get [1, 3, num_clips, height, width]
input_frames = np.transpose(input_frames, (0, 4, 1, 2, 3))
# convert the frames to tensor
input_frames = torch.tensor(input_frames, dtype=torch.float32)
input_frames = input_frames.to(device)
# forward pass to get the predictions
outputs = model(input_frames)
# get the prediction index
soft_max = torch.nn.Softmax(dim=1)
probs = soft_max(outputs.data)
prob, indices = torch.topk(probs, k)
Top_k = indices[0]
Classes_nameTop_k=[CLASSES_LIST[item].strip() for item in Top_k]
ProbTop_k=prob[0].tolist()
ProbTop_k = [round(elem, 5) for elem in ProbTop_k]
return Classes_nameTop_k[0] #list(zip(Classes_nameTop_k,ProbTop_k))
def PredTopKProb(k,clips,model):
with torch.no_grad(): # we do not want to backprop any gradients
code
input_frames = np.array(clips)
# add an extra dimension
input_frames = np.expand_dims(input_frames, axis=0)
# transpose to get [1, 3, num_clips, height, width]
input_frames = np.transpose(input_frames, (0, 4, 1, 2, 3))
# convert the frames to tensor
input_frames = torch.tensor(input_frames, dtype=torch.float32)
input_frames = input_frames.to(device)
# forward pass to get the predictions
outputs = model(input_frames)
# get the prediction index
soft_max = torch.nn.Softmax(dim=1)
probs = soft_max(outputs.data)
prob, indices = torch.topk(probs, k)
Top_k = indices[0]
Classes_nameTop_k=[CLASSES_LIST[item].strip() for item in Top_k]
ProbTop_k=prob[0].tolist()
ProbTop_k = [round(elem, 5) for elem in ProbTop_k]
return list(zip(Classes_nameTop_k,ProbTop_k))
def downloadYouTube(videourl, path):
code
yt = YouTube(videourl)
yt = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
if not os.path.exists(path):
os.makedirs(path)
yt.download(path)
def predict_on_video(video_file_path, output_file_path, model, SEQUENCE_LENGTH,skip=2,showInfo=False):
'''
This function will perform action recognition on a video using the LRCN model.
Args:
video_file_path: The path of the video stored in the disk on which the action recognition is to be performed.
output_file_path: The path where the ouput video with the predicted action being performed overlayed will be stored.
SEQUENCE_LENGTH: The fixed number of frames of a video that can be passed to the model as one sequence.
'''
code
# Initialize the VideoCapture object to read from the video file.
video_reader = cv2.VideoCapture(video_file_path)
# Get the width and height of the video.
original_video_width = int(video_reader.get(cv2.CAP_PROP_FRAME_WIDTH))
original_video_height = int(video_reader.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Initialize the VideoWriter Object to store the output video in the disk.
video_writer = cv2.VideoWriter(output_file_path, cv2.VideoWriter_fourcc('H', '2', '6', '4'),
video_reader.get(cv2.CAP_PROP_FPS), (original_video_width, original_video_height))
# Declare a queue to store video frames.
frames_queue = deque(maxlen = SEQUENCE_LENGTH)
transform= transform_()
# Initialize a variable to store the predicted action being performed in the video.
predicted_class_name = ''
# Iterate until the video is accessed successfully.
counter=0
while video_reader.isOpened():
# Read the frame.
ok, frame = video_reader.read()
# Check if frame is not read properly then break the loop.
if not ok:
break
image = frame.copy()
framee = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
framee = transform(image=framee)['image']
if counter % skip==0:
# Appending the pre-processed frame into the frames list.
frames_queue.append(framee)
# Check if the number of frames in the queue are equal to the fixed sequence length.
if len(frames_queue) == SEQUENCE_LENGTH:
predicted_class_name= PredTopKClass(1,frames_queue, model)
if showInfo:
print(predicted_class_name)
frames_queue = deque(maxlen = SEQUENCE_LENGTH)
else:
frames_queue = deque(maxlen = SEQUENCE_LENGTH)
# Write predicted class name on top of the frame.
if predicted_class_name=="fight":
cv2.putText(frame, predicted_class_name, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)
else:
cv2.putText(frame, predicted_class_name, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
counter+=1
# Write The frame into the disk using the VideoWriter Object.
video_writer.write(frame)
# time.sleep(2)
if showInfo:
print(counter)
# Release the VideoCapture and VideoWriter objects.
video_reader.release()
video_writer.release()
def showIference(model, sequence,skip,input_video_file_path,output_video_file_path,showInfo):
# Perform Accident Detection on the Test Video.
predict_on_video(input_video_file_path, output_video_file_path, model,sequence,skip,showInfo)
return output_video_file_path
def Fight_PipeLine(modelPath,inputPath,seq,skip,outputPath,showInfo=False):
model = loadModel(modelPath)
# Perform Accident Detection on the Test Video.
predict_on_video(inputPath, outputPath, model,seq,skip,showInfo)
return outputPath
# Append the normalized frame into the frames list
clips.append(frame)
first = PredTopKClass(1, clips, model)
print(first)
print(PredTopKProb(2, clips, model))
return first
model = loadModel(args.modelPath)
# Perform Fight Detection on the Test Video.
if args.streaming==True:
start_streaming(model,args.inputPath)
else:
start=time.time()
predict_on_video(args.inputPath, args.outputPath, model, args.sequenceLength, args.skip, args.showInfo)
end = time.time()
print(end-start)
if name == 'main':
main()
I want to make the code so that if i open the web cam it should detect from the model and give the putput like fight detected or not
from flask import Flask, request, render_template, redirect, url_for, send_from_directory, Response
import os
import subprocess
import cv2
def generate_frames():
cap = cv2.VideoCapture(0) # Open webcam
while True:
success, frame = cap.read()
if not success:
break
else:
# Process frame for fight detection (replace this with model inference code)
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
cap.release()
To modify your Flask web application so that it can perform fight detection using the webcam feed, you'll need to integrate the prediction logic into the generate_frames() function. This will involve using the model to process each frame captured from the webcam and display the results accordingly.
Here’s an outline of how you can achieve this:
Refactor the generate_frames() function: Modify it to include the fight detection model's inference process for each frame captured from the webcam.
Update the model prediction logic: Ensure that the frames are processed correctly and the predictions are made for each frame.
Display predictions: Annotate each frame with the prediction result ("fight" or "no fight").
Here's the updated code for the Flask app with these modifications:
python
from flask import Flask, request, render_template, redirect, url_for, send_from_directory, Response
import os
import subprocess
import cv2
import torch
from Fight_utils import loadModel, streaming_framesInference # Ensure streaming_framesInference is imported.
import time
app = Flask(__name__)
# Define upload and output folders
UPLOAD_FOLDER = 'uploads'
OUTPUT_FOLDER = 'outputs'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER
# Ensure the folders exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
# Load the model globally to be used in webcam
model = loadModel("model.pth") # Specify your actual model path here
model.eval() # Set the model to evaluation mode
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
if 'video' not in request.files:
return redirect(request.url)
file = request.files['video']
if file.filename == '':
return redirect(request.url)
if file:
video_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(video_path)
output_filename = 'output_' + file.filename
output_path = os.path.join(app.config['OUTPUT_FOLDER'], output_filename)
command = f'python infer.py --modelPath "model.pth" --inputPath "{video_path}" --outputPath "{output_path}"'
subprocess.run(command, shell=True)
return render_template('result.html', output_video=output_filename)
@app.route('/outputs/<filename>')
def output_file(filename):
return send_from_directory(app.config['OUTPUT_FOLDER'], filename)
# Webcam feed route
def generate_frames():
cap = cv2.VideoCapture(0) # Open webcam
frames_queue = [] # Initialize queue for frames
SEQUENCE_LENGTH = 16 # Set your desired sequence length
skip = 2 # Set how many frames to skip
predicted_class_name = ''
while True:
success, frame = cap.read()
if not success:
break
else:
# Preprocess the frame for model input
image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (171, 128)) # Resize as per your model's input
image = image.astype(np.float32) / 255.0 # Normalize the image
frames_queue.append(image)
# Process if we have enough frames
if len(frames_queue) == SEQUENCE_LENGTH:
predicted_class_name = streaming_framesInference(frames_queue, model)
# Clear the frame queue after processing
frames_queue = []
# Annotate the frame with prediction result
label_position = (10, 30)
if predicted_class_name == "fight":
cv2.putText(frame, predicted_class_name, label_position, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)
else:
cv2.putText(frame, predicted_class_name, label_position, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# Encode the frame to JPEG
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
cap.release()
@app.route('/webcam')
def webcam():
return render_template('webcam.html')
@app.route('/video_feed')
def video_feed():
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(debug=True)
Key Changes:
Model Loading in Global Scope: The model is loaded once when the app starts, which improves performance compared to loading it for each request.
Frames Queue for Inference: The frames_queue collects frames up to the specified SEQUENCE_LENGTH. When the queue is full, it calls streaming_framesInference() to make predictions.
Real-time Annotation: The predicted class name is displayed directly on the frame, allowing for real-time feedback on the webcam feed.
Frame Processing: Each captured frame is resized and normalized, similar to how frames from video files are processed in your previous code.
Make sure to adjust the frame preprocessing according to your model's specific requirements (like resizing).
Additional Notes:
Be cautious with the number of frames being collected for inference, especially regarding performance and model input size.
Depending on the capabilities of your hardware, you might want to incorporate techniques to handle frame dropping if your model inference is too slow for real-time detection.
Certainly! To set up the Flask application to detect fights on a streaming video feed (such as from an RTSP stream or a webcam feed) using your existing start_streaming function, you'll need to adjust the routing and handling of the streaming input.
Given your requirements, I'll outline how to incorporate the start_streaming function into your Flask app. The start_streaming function is used to process a streaming URL. However, since start_streaming works in a continuous loop, you'll have to adjust it to work within the Flask context.
Updated Flask Code
Below is the modified Flask application that incorporates your start_streaming function:
python
from flask import Flask, request, render_template, redirect, url_for, send_from_directory, Response
import os
import subprocess
import cv2
import threading
import torch
from Fight_utils import loadModel, start_streaming # Import your streaming function
import time
app = Flask(__name__)
# Define upload and output folders
UPLOAD_FOLDER = 'uploads'
OUTPUT_FOLDER = 'outputs'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER
# Ensure the folders exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
# Load the model globally to be used in webcam
model = loadModel("model.pth") # Specify your actual model path here
model.eval() # Set the model to evaluation mode
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
if 'video' not in request.files:
return redirect(request.url)
file = request.files['video']
if file.filename == '':
return redirect(request.url)
if file:
video_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(video_path)
output_filename = 'output_' + file.filename
output_path = os.path.join(app.config['OUTPUT_FOLDER'], output_filename)
command = f'python infer.py --modelPath "model.pth" --inputPath "{video_path}" --outputPath "{output_path}"'
subprocess.run(command, shell=True)
return render_template('result.html', output_video=output_filename)
@app.route('/outputs/<filename>')
def output_file(filename):
return send_from_directory(app.config['OUTPUT_FOLDER'], filename)
@app.route('/stream')
def stream():
streamingURL = request.args.get('url') # Get the streaming URL from request query parameters
if not streamingURL:
return "No streaming URL provided", 400
# Start the streaming in a separate thread
threading.Thread(target=start_streaming, args=(model, streamingURL)).start()
return redirect(url_for('webcam'))
# Webcam feed route
def generate_frames():
# The thread for processing frames can handle streaming
pass # Placeholder for webcam functionality, if needed. You may omit this if not using a separate webcam feed.
@app.route('/webcam')
def webcam():
return render_template('webcam.html')
if __name__ == '__main__':
app.run(debug=True)
Explanation of Changes:
Streaming URL Retrieval: The /stream route retrieves a streaming URL from query parameters when called (e.g., /stream?url=rtsp://your_stream_url_here).
Threading for Continuous Processing: The start_streaming function is started in a separate thread. This allows the Flask app to remain responsive while the detection runs continuously in the background.
Redirect After Starting Streaming: After starting the streaming, you can redirect the user to a different page (like a webcam page) that could display the results or a simple message indicating that streaming has started.
Generate Frames Placeholder: The generate_frames() function is set up but doesn't contain logic currently, as the logic for rendering the streaming feed is handled by start_streaming. If you want to process webcam frames separately in addition to streaming, you would implement it here.
Usage:
Start the Flask application and, in your web browser, navigate to the /stream?url=your_stream_url endpoint to initiate fight detection on the given video stream.
Keep in mind that how start_streaming processes and provides feedback to the user would depend on its specific implementation, as it is running indefinitely. You may want to implement some form of status checking or visual feedback on the Flask front end if necessary.
BuildError
werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'video_feed'. Did you mean 'index' instead?
Traceback (most recent call last)
File "C:\Users\mani3\miniconda3\envs\fight_detection\lib\site-packages\flask\app.py", line 1536, in call
return self.wsgi_app(environ, start_response)
File "C:\Users\mani3\miniconda3\envs\fight_detection\lib\site-packages\flask\app.py", line 1514, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\mani3\miniconda3\envs\fight_detection\lib\site-packages\flask\app.py", line 1511, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\mani3\miniconda3\envs\fight_detection\lib\site-packages\flask\app.py", line 919, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\mani3\miniconda3\envs\fight_detection\lib\site-packages\flask\app.py", line 917, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\mani3\miniconda3\envs\fight_detection\lib\site-packages\flask\app.py", line 902, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return]
File "C:\Users\mani3\Downloads\Fight_Detection_From_Surveillance_Cameras-PyTorch_Project-main\Fight_Detection_From_Surveillance_Cameras-PyTorch_Project-main\frontend\app.py", line 74, in webcam
return render_template('webcam.html')
File "C:\Users\mani3\miniconda3\envs\fight_detection\lib\site-packages\flask\templating.py", line 150, in render_template
return _render(app, template, context)
File "C:\Users\mani3\miniconda3\envs\fight_detection\lib\site-packages\flask\templating.py", line 131, in _render
rv = template.render(context)
File "C:\Users\mani3\miniconda3\envs\fight_detection\lib\site-packages\jinja2\environment.py", line 1295, in render
self.environment.handle_exception()
File "C:\Users\mani3\miniconda3\envs\fight_detection\lib\site-packages\jinja2\environment.py", line 942, in handle_exception
raise rewrite_traceback_stack(source=source)
File "C:\Users\mani3\Downloads\Fight_Detection_From_Surveillance_Cameras-PyTorch_Project-main\Fight_Detection_From_Surveillance_Cameras-PyTorch_Project-main\frontend\templates\webcam.html", line 44, in top-level template code
}
You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:
dump() shows all variables in the frame
dump(obj) dumps all that's known about the object
The error you're encountering suggests that Flask couldn't find an endpoint named video_feed, which is referenced in your webcam.html template. This issue can arise for a few reasons:
Missing Route for /video_feed: Make sure that you have defined a route in your Flask app that corresponds to video_feed.
Typo or Route Declaration Issue: Ensure that the route name is correctly defined and matches what you reference in the url_for function within your template.
Conditional Execution: In the previous implementation, I mentioned having a generate_frames() function as a placeholder. If this function is not correctly implemented or not returning any frames, you may not have an active route for video_feed.
Step-by-Step Solution
Define the /video_feed Route: If you do not intend to use a separate webcam feed that directly corresponds to video_feed, you can either remove the reference to it in your webcam.html or ensure that the route exists.
Characterize generate_frames: If you're using start_streaming for recurring detections, you'll want to ensure that the responses from that function are being directed to an appropriate endpoint if needed.
Implement a Working /video_feed Route: Here's a simplified version of the route, which serves as the feed from the start_streaming function or uses webcam input directly.
Updated Flask Application Code
Here’s the complete structure with the necessary /video_feed route implemented:
python
from flask import Flask, request, render_template, redirect, url_for, send_from_directory, Response
import os
import subprocess
import cv2
import threading
import torch
from Fight_utils import loadModel, start_streaming # Ensure your Fight_utils is correctly imported
import time
app = Flask(__name__)
# Define upload and output folders
UPLOAD_FOLDER = 'uploads'
OUTPUT_FOLDER = 'outputs'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER
# Ensure the folders exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
# Load the model globally for use in the application
model = loadModel("model.pth") # Adjust to your actual model path
model.eval() # Make sure model is in evaluation mode
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
if 'video' not in request.files:
return redirect(request.url)
file = request.files['video']
if file.filename == '':
return redirect(request.url)
if file:
video_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(video_path)
output_filename = 'output_' + file.filename
output_path = os.path.join(app.config['OUTPUT_FOLDER'], output_filename)
command = f'python infer.py --modelPath "model.pth" --inputPath "{video_path}" --outputPath "{output_path}"'
subprocess.run(command, shell=True)
return render_template('result.html', output_video=output_filename)
@app.route('/outputs/<filename>')
def output_file(filename):
return send_from_directory(app.config['OUTPUT_FOLDER'], filename)
@app.route('/stream')
def stream():
streamingURL = request.args.get('url') # Get the streaming URL from request query parameters
if not streamingURL:
return "No streaming URL provided", 400
# Start the streaming detection in a separate thread
threading.Thread(target=start_streaming, args=(model, streamingURL)).start()
return redirect(url_for('webcam'))
@app.route('/webcam')
def webcam():
return render_template('webcam.html')
def generate_frames():
cap = cv2.VideoCapture(0) # Open the webcam
while True:
success, frame = cap.read()
if not success:
break
# Process frames here or update to handle video feed logic
# e.g., use your model to predict on 'frame'
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
cap.release()
@app.route('/video_feed') # Ensure this route is defined
def video_feed():
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(debug=True)
Important Points:
Check Template References: Ensure that webcam.html contains the correct reference to video_feed:
Debugging Output: You can temporarily print debug statements in the terminal to troubleshoot and verify that the routes are returning correctly and the server is responding.
Thread Safety: Make sure your implementation of start_streaming does not conflict with Flask's environment since it might affect concurrency.
Performance: Adjust webcam reading and model prediction logic appropriately within the streaming context to ensure that frame processing isn't too slow for real-time demands.
Check Environment: If you're switching between testing in different environments (e.g., locally vs. a server), ensure the model is properly uploaded or accessible on those systems.
With these adjustments, the video_feed route should be recognized by Flask, and the associated webcam feed will work properly without route-related errors.
Certainly! Below is a complete example of a Flask application that performs fight detection using a webcam feed. The app captures frames from the webcam, runs the detection model on these frames, and displays the results on a web page.
Complete Flask Application Code
python
from flask import Flask, render_template, Response
import cv2
import torch
from Fight_utils import loadModel, streaming_framesInference # Ensure your utils are correctly imported
import numpy as np
import threading
app = Flask(__name__)
# Load the model globally to be used in the application
model = loadModel("model.pth") # Specify your actual model path here
model.eval() # Set the model to evaluation mode
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
predicted_class_name = '' # Global variable to hold prediction results
def generate_frames():
global predicted_class_name
cap = cv2.VideoCapture(0) # Open the webcam
frames_queue = [] # Queue to hold frames for prediction
SEQUENCE_LENGTH = 16 # Adjust as necessary
skip = 2 # Skip frames if too many are captured immediately
while True:
success, frame = cap.read()
if not success:
break
# Resize frame for processing
resized_frame = cv2.resize(frame, (171, 128)) # Adjust to your model's expected input size
formatted_frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB)
formatted_frame = formatted_frame.astype(np.float32) / 255.0 # Normalize
frames_queue.append(formatted_frame)
# Make predictions on a batch of frames
if len(frames_queue) == SEQUENCE_LENGTH:
# Get prediction class
predicted_class_name = streaming_framesInference(frames_queue, model)
frames_queue = [] # Clear the queue after processing
# Annotate the frame with the prediction result
label_position = (10, 30)
if predicted_class_name == "fight":
cv2.putText(frame, predicted_class_name, label_position, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)
else:
cv2.putText(frame, predicted_class_name, label_position, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# Encode the frame to JPEG
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
cap.release()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/video_feed')
def video_feed():
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/webcam')
def webcam():
return render_template('webcam.html')
if __name__ == '__main__':
app.run(debug=True)
HTML Template Files
You'll need an HTML file for the main page (index.html) and another for displaying the webcam feed (webcam.html).
Dependencies: Make sure you have Flask, OpenCV, and any other necessary libraries installed in your environment. You can install them using pip if they are not installed:
bash
pip install Flask opencv-python torch torchvision
Model Loading: Ensure that your model.pth file path points to the correct location of your trained PyTorch model.
Running the Application: Save the Python script as app.py. Ensure the HTML templates are saved in a templates folder in the same directory as app.py.
Start the Flask Server:
bash
python app.py
Access the Application: Open your web browser and navigate to http://127.0.0.1:5000. Click on "Start Webcam Detection" to see the live feed with fight detection.
Important Notes:
Frame Processing: Ensure that the function streaming_framesInference processes the frames correctly. You might need to adjust it according to the expected input size of your model.
Performance: Depending on your hardware, ensure that processing is efficient enough to provide real-time feedback. If the detection is slow, consider optimizing the frame skip or batch processing logic.
Permissions: The application might require permissions to access the webcam; ensure your browser or OS grants them.
This setup should work for detecting fights using a webcam feed, displaying the results in real-time on a web page.
from flask import Flask, request, render_template, redirect, url_for, send_from_directory, Response
import os
import subprocess
import cv2
import threading
import torch
from Fight_utils import loadModel, start_streaming # Ensure your Fight_utils is correctly imported
import time
Load the model globally for use in the application
model = loadModel(r"C:\Users\mani3\Downloads\Fight_Detection_From_Surveillance_Cameras-PyTorch_Project-main\Fight_Detection_From_Surveillance_Cameras-PyTorch_Project-main\frontend\model_16_m3_0.8888.pth") # Adjust to your actual model path
model.eval() # Make sure model is in evaluation mode
@app.route('/stream')
def stream():
streamingURL = request.args.get('url') # Get the streaming URL from request query parameters
if not streamingURL:
return "No streaming URL provided", 400
code
# Start the streaming detection in a separate thread
threading.Thread(target=start_streaming, args=(model, streamingURL)).start()
return redirect(url_for('webcam'))
def generate_frames():
cap = cv2.VideoCapture(0) # Open the webcam
while True:
success, frame = cap.read()
if not success:
break
code
# Process frames here or update to handle video feed logic
# e.g., use your model to predict on 'frame'
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
cap.release()
@app.route('/video_feed') # Ensure this route is defined
def video_feed():
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
if name == 'main':
app.run(debug=True)
add in tjis code
Certainly! Below is the modified version of your Flask application code that integrates fight detection using a webcam feed while displaying the output in real-time. This implementation uses the existing infrastructure you provided and ensures that the fight detection model is applied to each frame from the webcam.
Complete Flask Application Code with WebCam Detection
python
from flask import Flask, render_template, Response
import os
import cv2
import numpy as np
import torch
from Fight_utils import loadModel, streaming_framesInference # Ensure your utils are correctly imported
app = Flask(__name__)
# Define upload and output folders
UPLOAD_FOLDER = 'uploads'
OUTPUT_FOLDER = 'outputs'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER
# Ensure the folders exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
# Load the model globally for use in the application
model = loadModel(r"C:\Users\mani3\Downloads\Fight_Detection_From_Surveillance_Cameras-PyTorch_Project-main\Fight_Detection_From_Surveillance_Cameras-PyTorch_Project-main\frontend\model_16_m3_0.8888.pth") # Adjust to your actual model path
model.eval() # Make sure the model is in evaluation mode
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Global variable to hold prediction results
predicted_class_name = ''
def generate_frames():
global predicted_class_name
cap = cv2.VideoCapture(0) # Open the webcam
frames_queue = [] # Queue to hold frames for prediction
SEQUENCE_LENGTH = 16 # Change according to your model's requirement
while True:
success, frame = cap.read()
if not success:
break
# Resize and prepare the frame for the model
resized_frame = cv2.resize(frame, (171, 128)) # Adjust to your model's expected input size
formatted_frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB)
formatted_frame = formatted_frame.astype(np.float32) / 255.0 # Normalize
frames_queue.append(formatted_frame)
# Make predictions on a batch of frames
if len(frames_queue) == SEQUENCE_LENGTH:
# Get prediction class
predicted_class_name = streaming_framesInference(frames_queue, model)
frames_queue = [] # Clear the queue after processing
# Annotate the frame with the prediction result
label_position = (10, 30)
if predicted_class_name == "fight":
cv2.putText(frame, predicted_class_name, label_position, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)
else:
cv2.putText(frame, predicted_class_name, label_position, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# Encode the frame to JPEG
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
cap.release()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/webcam')
def webcam():
return render_template('webcam.html')
@app.route('/video_feed')
def video_feed():
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(debug=True)
HTML Template Files
Make sure to set up your HTML files in a folder named templates within the same directory where your Flask app is located.
Real-time Detection: The webcam feed is processed in real-time, with each frame being analyzed by the fight detection model.
Annotation: The detected class (either "fight" or "no fight") is displayed directly on the video feed.
Thread Safety: The application uses Flask's built-in capabilities to manage responses while processing frames.
Model Handling: The model is loaded once, ensuring that performance is optimized by avoiding repeated loading.
Running the Application:
Install Dependencies: Ensure you have all required packages installed in your Python environment:
bash
pip install Flask opencv-python torch torchvision
Adjust Model Path: Be sure that the path to your model in the loadModel call is correct.
Run the Application: Save the Python script as app.py and run it using:
bash
python app.py
Access the Application: Open your web browser and navigate to http://127.0.0.1:5000 to access the main page, and click on "Start Webcam Detection" to view the live feed with fight detection.
Make sure to adjust any parameters according to your model's requirements (such as input dimensions). This setup should provide a basic framework for fight detection using a webcam feed displayed in a web application.