-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebapp.py
More file actions
165 lines (120 loc) · 5.73 KB
/
webapp.py
File metadata and controls
165 lines (120 loc) · 5.73 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
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')
@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)
global imgpath
predict_img.imgpath = f.filename
print("printing predict_img :::::: ", predict_img)
file_extension = f.filename.rsplit('.', 1)[1].lower()
if file_extension in ['jpg', 'jpeg', 'png']:
img = cv2.imread(filepath)
script_path = 'predict_modified.py'
model_path = 'train_model/weights/best.pt'
source_path = filepath
# Run the predict_modified.py script with specified arguments
subprocess.run(['python' ,script_path, f'model={model_path}', f'source={source_path}'])
# Perform the detection
# model = YOLO('train_model/weights/best.pt')
# detections = model(img, save=True)
return display(f.filename)
elif file_extension == 'mp4':
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('train_model/weights/best.pt')
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# do YOLOv9 detection on the frame here
#model = YOLO('train_model/weights/best.pt')
script_path = 'predict_modified.py'
model_path = 'train_model/weights/best.pt'
source_path = filepath
# Run the predict_modified.py script with specified arguments
subprocess.run(['python', script_path, f'model={model_path}', f'source={source_path}'])
return display(f.filename)
# return video_feed()
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)))
image_path = folder_path+'/'+latest_subfolder+'/'+f.filename
return render_template('index.html', image_path=image_path)
#return "done"
# #The display function is used to serve the image or video from the folder_path directory.
@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 = folder_path+'/'+latest_subfolder
print("printing directory: ",directory)
files = os.listdir(directory)
latest_file = files[0]
print(latest_file)
filename = os.path.join(folder_path, latest_subfolder, latest_file)
file_extension = filename.rsplit('.', 1)[1].lower()
environ = request.environ
if file_extension in ['jpg', 'jpeg', 'png', 'bmp', 'gif','mp4']:
return send_from_directory(directory,latest_file,environ) #shows the result in seperate tab
else:
return "Invalid file format"
def get_frame():
folder_path = os.getcwd()
mp4_files = 'output.mp4'
video = cv2.VideoCapture(mp4_files) # detected video path
while True:
success, image = video.read()
if not success:
break
ret, jpeg = cv2.imencode('.jpg', image)
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + jpeg.tobytes() + 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():
print("function called")
return Response(get_frame(),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Flask app exposing yolov9 models")
parser.add_argument("--port", default=5000, type=int, help="port number")
args = parser.parse_args()
model = YOLO('train_model/weights/best.pt')
app.run(host="0.0.0.0", port=args.port)