Question: Please help me , when I record a video it freezes. I will attach my code below import cv 2 from flask import Flask, Response,

Please help me, when I record a video it freezes. I will attach my code below
import cv2
from flask import Flask, Response, request, redirect, render_template, url_for
from ultralytics import YOLO
import supervision as sv
from datetime import datetime
import os
import numpy as np
from werkzeug.utils import secure_filename
from collections import deque
from scipy.spatial import distance as dist
import matplotlib.pyplot as plt
import io
UPLOAD_FOLDER = 'static/videos/'
temp_path =0
stream = False
frame = np.zeros((640,480), np.uint8)
app = Flask(__name__)
app.secret_key = 'akwdhawwdjhawkdh'
app.config['UPLOAD_FOLDER']= UPLOAD_FOLDER
# Initialize the custom YOLOv8 model
weights = 'models/yolov8s.pt' # Path to custom YOLOv8 weights file
model = YOLO(weights)
ALLOWED_EXTENSIONS = set(['mp4','mkv'])
total_cars =0
cars_north =0
cars_south =0
car_centroids = deque(maxlen=64)
@app.route('/', methods=['GET', 'POST'])
def index():
global stream, temp_path
if request.method == "POST":
if request.form.get('submit')== "Upload Video":
file = request.files['file']
if file.filename =='':
return redirect('/')
if file and allowed_file(file.filename):
filename = secure_filename(str(datetime.now())+ file.filename)
temp_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(temp_path)
stream = True
return render_template('index.html')
if request.form.get('submit')== "Start Recording":
temp_path =0
stream = True
return redirect("/")
if request.form.get('submit')== "Stop Recording" and stream == True:
stream = False
return redirect("/")
return render_template('index.html', total_cars=total_cars, cars_north=cars_north, cars_south=cars_south)
def allowed_file(filename):
return '.' in filename and filename.rsplit('.',1)[1].lower() in ALLOWED_EXTENSIONS
def detect_objects(frame):
results = model(frame, verbose=False)[0]
frame = results.plot()
return results, frame
def gen_frames():
global total_cars, cars_north, cars_south, car_centroids, temp_path
if stream:
if temp_path ==0:
cap = cv2.VideoCapture(0)
else:
cap = cv2.VideoCapture(temp_path)
while True:
success, frame = cap.read()
if not success:
break
if not stream:
break
else:
results, frame = detect_objects(frame)
current_centroids =[]
for result in results.boxes:
x1, y1, x2, y2= map(int, result.xyxy[0])
centroid =(int((x1+ x2)/2), int((y1+ y2)/2))
current_centroids.append(centroid)
if len(car_centroids)>0:
D = dist.cdist(car_centroids, current_centroids)
rows = D.min(axis=1).argsort()
cols = D.argmin(axis=1)[rows]
used_rows, used_cols = set(), set()
for (row, col) in zip(rows, cols):
if row in used_rows or col in used_cols:
continue
car_centroids[row]= current_centroids[col]
used_rows.add(row)
used_cols.add(col)
(x, y)= car_centroids[row]
if y < frame.shape[0]//2:
cars_north +=1
else:
cars_south +=1
total_cars +=1
unused_rows = set(range(0, D.shape[0])).difference(used_rows)
unused_cols = set(range(0, D.shape[1])).difference(used_cols)
for row in unused_rows:
car_centroids[row]= None
for col in unused_cols:
car_centroids.append(current_centroids[col])
else:
car_centroids = current_centroids
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r
'
b'Content-Type: image/jpeg\r
\r
'+ frame + b'\r
')
@app.route('/video_feed')
def video_feed():
return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__=='__main__':
app.run(port=8081, debug=True)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!