-
Notifications
You must be signed in to change notification settings - Fork 1
/
webapp.py
222 lines (174 loc) · 7.18 KB
/
webapp.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
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
import argparse
import io
from PIL import Image
import datetime
import torch
import cv2
import numpy as np
import tensorflow as tf
from re import DEBUG, sub
from flask import (
Flask,
render_template,
request,
redirect,
send_file,
url_for,
Response,
)
from werkzeug.utils import secure_filename, send_from_directory
import os
import subprocess
from subprocess import Popen
import re
import requests
import shutil
import time
import glob
from ultralytics import YOLO
app = Flask(__name__)
@app.route("/")
def hello_world():
# return render_template("index.html")
if "image_path" in request.args:
image_path = request.args["image_path"]
return render_template("index.html", image_path=image_path)
return render_template("index.html")
@app.route("/", methods=["GET", "POST"])
def predict_img():
if request.method == "POST":
if 'file' in request.files:
f = request.files['file']
basepath = os.path.dirname(__file__)
filepath = os.path.join(basepath, 'uploads', f.filename)
print("upload folder is ", filepath)
f.save(filepath)
predict_img.imgpath = f.filename
print("printing predict_img :::::: ", predict_img)
file_extension = f.filename.rsplit('.', 1)[1].lower()
if file_extension == 'jpg':
# Handle image upload
img = cv2.imread(filepath)
# Perform the detection
model = YOLO('yolov8n.pt')
detections = model(img, save=True)
# Find the latest subdirectory in the 'runs/detect' folder
folder_path = os.path.join(basepath, 'runs', 'detect')
subfolders = [f for f in os.listdir(folder_path) if os.path.isdir(os.path.join(folder_path, f))]
latest_subfolder = max(subfolders, key=lambda x: os.path.getctime(os.path.join(folder_path, x)))
# Construct the relative path to the detected image file
static_folder = os.path.join(basepath, 'static', 'assets')
relative_image_path = os.path.relpath(os.path.join(folder_path, latest_subfolder, f.filename), static_folder)
image_path = os.path.join(folder_path, latest_subfolder, f.filename)
print("Relative image path:", relative_image_path) # Print the relative_image_path for debugging
return render_template('index.html', image_path=relative_image_path, media_type='image')
elif file_extension == "mp4":
# Handle video upload
video_path = filepath # replace with your video path
cap = cv2.VideoCapture(video_path)
# get video dimensions
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
out = cv2.VideoWriter(
"output.mp4", fourcc, 30.0, (frame_width, frame_height)
)
# initialize the YOLOv8 model here
model = YOLO("yolov8n.pt")
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# do YOLOv9 detection on the frame here
# model = YOLO('yolov9c.pt')
results = model(frame, save=True) # working
print(results)
cv2.waitKey(1)
res_plotted = results[0].plot()
cv2.imshow("result", res_plotted)
# write the frame to the output video
out.write(res_plotted)
if cv2.waitKey(1) == ord("q"):
break
return render_template('index.html', video_path='output.mp4', media_type='video')
# If no file uploaded or GET request, return the template with default values
return render_template("index.html", image_path="", media_type='image')
@app.route("/<path:filename>")
def display(filename):
folder_path = "runs/detect"
subfolders = [
f
for f in os.listdir(folder_path)
if os.path.isdir(os.path.join(folder_path, f))
]
latest_subfolder = max(
subfolders, key=lambda x: os.path.getctime(os.path.join(folder_path, x))
)
directory = os.path.join(folder_path, latest_subfolder)
print("printing directory: ", directory)
files = os.listdir(directory)
latest_file = files[0]
print(latest_file)
image_path = os.path.join(directory, latest_file)
file_extension = latest_file.rsplit(".", 1)[1].lower()
if file_extension == "jpg":
return send_file(image_path, mimetype="image/jpeg")
elif file_extension == "mp4":
return send_file(image_path, mimetype="video/mp4")
else:
return "Invalid file format"
def get_frame():
folder_path = os.getcwd()
mp4_files = "output.mp4"
print("files being read...")
video = cv2.VideoCapture(mp4_files) # detected video path
while True:
success, frame = video.read()
if not success:
print("file not being read")
break
else:
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\r\n"
)
time.sleep(0.1) # Control the frame rate to display one frame every 100 milliseconds:
# function to display the detected objects video on html page
@app.route("/video_feed")
def video_feed():
# folder_path = os.getcwd()
# mp4_file = "output.mp4"
# video_path = os.path.join(folder_path, mp4_file)
# return send_file(video_path, mimetype="video")
return Response(get_frame(), mimetype="multipart/x-mixed-replace; boundary=frame")
@app.route("/webcam_feed")
def webcam_feed():
cap = cv2.VideoCapture(0) # 0 for camera
def generate():
while True:
success, frame = cap.read()
if not success:
break
# Perform object detection on the frame
img = Image.fromarray(frame)
model = YOLO("yolov8n.pt")
results = model(img, save=True)
# Plot the detected objects on the frame
res_plotted = results[0].plot()
img_BGR = cv2.cvtColor(res_plotted, cv2.COLOR_RGB2BGR)
# Convert the frame to JPEG format for streaming
ret, buffer = cv2.imencode(".jpg", img_BGR)
frame = buffer.tobytes()
yield (
b"--frame\r\n" b"Content-Type: image/jpeg\r\n\r\n" + frame + b"\r\n\r\n"
)
return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Flask app exposing yolov8 models")
parser.add_argument("--port", default=5000, type=int, help="port number")
args = parser.parse_args()
model = YOLO("yolov8n.pt")
app.run(host="0.0.0.0", port=args.port, debug=True)