-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflaskaap.py
More file actions
243 lines (194 loc) · 8.21 KB
/
flaskaap.py
File metadata and controls
243 lines (194 loc) · 8.21 KB
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
from flask import Flask, render_template, Response, jsonify, request, session , redirect ,url_for
from flask_wtf import FlaskForm
from wtforms import FileField, SubmitField, IntegerRangeField
from werkzeug.utils import secure_filename
from flask_bootstrap import Bootstrap
from wtforms.validators import InputRequired
import cv2
import numpy as np
from hubconfCustom import video_detection # Your YOLOv11 detection function
from lane import process_frame
import os
from ultralytics import YOLO
from motion import video_detectionn
app = Flask(__name__)
Bootstrap(app)
app.config['SECRET_KEY'] = 'muhammadmoin'
UPLOAD_FOLDER = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'static', 'uploads')
ALLOWED_EXTENSIONS = {'mp4', 'avi', 'mov', 'mkv', 'jpg', 'jpeg', 'png', 'bmp'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Ensure upload folder exists
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
# WTForms setup
class UploadFileForm(FlaskForm):
file = FileField("Upload Video", validators=[InputRequired()])
conf_slide = IntegerRangeField("Confidence", default=25, validators=[InputRequired()])
submit = SubmitField("Run")
# Helpers
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# Global Variables
frames = 0
sizeImage = 0
detectedObjects = 0
def generate_combined_frames(path_x='', conf_=0.25):
cap = cv2.VideoCapture(path_x)
if not cap.isOpened():
print("Error opening video stream or file.")
return
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Failed to read frame.")
break
# Run YOLO detection on the current frame
yolo_output = video_detection(frame, conf_)
for detection_, FPS_, xl, yl in yolo_output:
global frames, sizeImage, detectedObjects
frames = str(FPS_)
sizeImage = str(xl[0]) if xl else "0"
detectedObjects = str(yl)
# Run lane detection on the same frame
final_output = process_frame(frame)
if final_output is None:
final_output = frame # Fallback to original if lane detection fails
# Combine YOLO + Lane output (ensure same size)
detection_resized = cv2.resize(detection_, (final_output.shape[1], final_output.shape[0]))
combined_output = cv2.addWeighted(final_output, 0.5, detection_resized, 0.5, 0)
_, jpeg = cv2.imencode('.jpg', combined_output)
frame_bytes = jpeg.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n\r\n')
cap.release()
@app.route("/", methods=['GET', 'POST'])
@app.route("/home", methods=['GET', 'POST'])
def home():
session.clear()
return render_template('indexproject.html')
@app.route("/motion_detection", methods=['GET', 'POST'])
def lane_vedio():
form = UploadFileForm()
if form.validate_on_submit():
file = form.file.data
conf_ = form.conf_slide.data
file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
app.config['UPLOAD_FOLDER'], secure_filename(file.filename))
file.save(file_path)
session['video_path'] = file_path
session['conf_'] = conf_
return render_template('ui2.html', form=form)
@app.route('/FrontPage', methods=['GET', 'POST'])
def front():
form = UploadFileForm()
if form.validate_on_submit():
file = form.file.data
conf_ = form.conf_slide.data
file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
app.config['UPLOAD_FOLDER'], secure_filename(file.filename))
file.save(file_path)
session['video_path'] = file_path
session['conf_'] = conf_
return render_template('videoprojectnew.html', form=form)
@app.route('/video')
def video():
conf_val = session.get('conf_')
video_path = session.get('video_path')
if conf_val is None or video_path is None:
return "Video or confidence value not set. Please upload a video first.", 400
return Response(generate_combined_frames(
path_x=video_path,
conf_=round(float(conf_val) / 100, 2)),
mimetype='multipart/x-mixed-replace; boundary=frame'
)
@app.route('/lane')
def lane():
video_path = session.get('video_path')
if not video_path:
return "No video file found in session", 400
return Response(generate_combined_frames(path_x=video_path),
mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/fpsgenerate', methods=['GET'])
def fps_fun():
global frames
return jsonify(result=frames)
@app.route('/sizegenerate', methods=['GET'])
def size_fun():
global sizeImage
return jsonify(imageSize=sizeImage)
@app.route('/detectionCount', methods=['GET'])
def detect_fun():
global detectedObjects
return jsonify(detectCount=detectedObjects)
# Load YOLO model once
model = YOLO(r"C:\Users\mihar\OneDrive\Documents\Deep Leaning Project\ultralytics\motion.pt")
# Helpers
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# Home Page
@app.route('/')
def index():
return render_template('ui2.html')
# Upload Video Route
@app.route('/upload_video', methods=['POST'])
def upload_video():
if 'video' not in request.files:
return redirect(request.url)
video_file = request.files['video']
if video_file and allowed_file(video_file.filename):
filename = secure_filename("dataset.mp4") # Overwrite name to standard
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
video_file.save(filepath)
return redirect(url_for('motion_video')) # Redirect to play uploaded video
return "Invalid file format", 400
# Webcam Streaming
@app.route('/start_webcam')
def start_webcam():
def generate():
ip_camera_url = 'http://10.139.34.6:8080/video' # Common IP camera URL format
while True:
cap = cv2.VideoCapture(ip_camera_url)
if not cap.isOpened():
print("🚫 Cannot open IP camera stream.")
time.sleep(2)
continue
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("⚠️ Frame read failed. Reconnecting...")
break # Break inner loop to reinit capture
# Run your YOLO or custom detection
results = video_detectionn(frame)
frame_out = results[0][0]
# Encode frame as JPEG
_, buffer = cv2.imencode('.jpg', frame_out, [int(cv2.IMWRITE_JPEG_QUALITY), 60])
frame_bytes = buffer.tobytes()
# Stream frame
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n\r\n')
cap.release()
time.sleep(1) # Short delay before attempting to reconnect
return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')
# Motion Detection from Uploaded Video
@app.route('/motion_video')
def motion_video():
def generate():
video_path = os.path.join(app.config['UPLOAD_FOLDER'], 'dataset.mp4')
if not os.path.exists(video_path):
yield b""
return
cap = cv2.VideoCapture(video_path)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
results = video_detectionn(frame)
frame_out = results[0][0]
_, buffer = cv2.imencode('.jpg', frame_out)
frame_bytes = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n\r\n')
cap.release()
return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == "__main__":
app.run(debug=True)