-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
199 lines (173 loc) · 8.35 KB
/
app.py
File metadata and controls
199 lines (173 loc) · 8.35 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
import os
import cv2
import streamlit as st
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip
from ultralytics import YOLO
from ultralytics.solutions import object_counter
from PIL import Image
import subprocess
import shutil
st.set_page_config(
page_title="Object Detection",
page_icon="🤖",
layout="wide"
)
st.markdown("""
<style>
.css-1rs6os.edgvbvh3
{
visibility:hidden;
}
.css-10pw50.egzxvld1
{
visibility:hidden;
}
<style/>
""", unsafe_allow_html=True)
def convert_avi_to_mp4(avi_file, mp4_file):
command = ["ffmpeg", "-i", avi_file, mp4_file]
subprocess.run(command)
def convert_mp4_to_avi(avi_file, mp4_file):
command = ["ffmpeg", "-i", mp4_file, avi_file]
subprocess.run(command)
def clear_session():
st.session_state.clear()
if os.path.exists("runs"):
shutil.rmtree("runs", ignore_errors=True)
if os.path.exists("user"):
shutil.rmtree("user", ignore_errors=True)
def get_keys(names, values):
res = []
for key, value in names.items():
for target in values:
if value == target:
res.append(key)
return res
def count_objects(model, video_path, classes, output_dir):
cap = cv2.VideoCapture(video_path)
assert cap.isOpened(), "Error reading video file"
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
line_points = [(100, 400), (1900, 400)] # line or region points
classes_to_count = classes # person and car classes for count
# Init Object Counter
counter = object_counter.ObjectCounter()
counter.set_args(view_img=True,
reg_pts=line_points,
classes_names=model.names,
draw_tracks=True)
images = []
while cap.isOpened():
success, im0 = cap.read()
if not success:
print("Video frame is empty or video processing has been successfully completed.")
break
tracks = model.track(im0, persist=True, show=False,
classes=classes_to_count)
im0 = counter.start_counting(im0, tracks)
images.append(im0)
clip = ImageSequenceClip(images, fps=fps)
clip.write_videofile(output_dir, fps=fps)
def main():
st.title("Object Detection")
task = st.selectbox("Select type of file", [None, "Image", "Video"], on_change=clear_session)
# Load a model
model = YOLO("yolov8x.pt")
classes = model.names
if task == "Image":
files = st.file_uploader("Upload your image:", accept_multiple_files=True,
type=["jpg",
"jpeg",
"png",
"jfif"])
if files:
for file in files:
if model:
image = Image.open(file)
if not os.path.exists("user"):
os.makedirs("user")
if not os.path.exists(f"user/{file.name.split('.')[0]}.png"):
image.save(f"user/{file.name.split('.')[0]}.png")
st.subheader("Original Image")
st.image(file)
st.subheader("Detected Image")
counter = 0
if os.path.exists(r"runs\detect"):
counter = len(os.listdir(r"runs\detect"))
if counter > 1:
if not os.path.exists(
fr"runs\detect\predict{counter}\{file.name.split('.')[0]}.png"):
model.predict(f"user/{file.name.split('.')[0]}.png",
save=True)
if os.path.exists(
fr"runs\detect\predict{counter}\{file.name.split('.')[0]}.png"):
st.image(
fr"runs\detect\predict{counter}\{file.name.split('.')[0]}.png")
else:
if not os.path.exists(fr"runs\detect\predict\{file.name.split('.')[0]}.png"):
model.predict(f"user/{file.name.split('.')[0]}.png",
save=True)
if os.path.exists(fr"runs\detect\predict\{file.name.split('.')[0]}.png"):
st.image(fr"runs\detect\predict\{file.name.split('.')[0]}.png")
elif task == "Video":
files = st.file_uploader("Upload your video:",
accept_multiple_files=True,
type=["mp4"])
c_d_task = st.selectbox("Select from count object or detect object:",
[None, "count", "detect"], on_change=clear_session)
if files:
for file in files:
if not os.path.exists("user"):
os.makedirs("user")
if not os.path.exists(f"user/{file.name.split('.')[0]}.mp4"):
with open(f"user/{file.name.split('.')[0]}.mp4", "wb") as f:
f.write(file.read())
st.subheader("Original Video")
st.video(file)
if c_d_task == "count":
objects = st.multiselect("Select objects:",
list(classes.values()), on_change=clear_session)
classes_n = get_keys(classes, objects)
proc = st.button("Process")
if classes_n and proc:
if not os.path.exists(f"user/{file.name.split('.')[0]}c.mp4"):
count_objects(model=model,
video_path=f"user/{file.name.split('.')[0]}.mp4",
classes=classes_n, output_dir=f"user/{file.name.split('.')[0]}c.mp4")
if os.path.exists(f"user/{file.name.split('.')[0]}c.mp4"):
st.subheader("object counted")
st.video(f"user/{file.name.split('.')[0]}c.mp4")
elif c_d_task == "detect":
st.subheader("Detected Video")
counter = 0
if os.path.exists(r"runs\detect"):
counter = len(os.listdir(r"runs\detect"))
if counter > 1:
if not os.path.exists(
fr"runs\detect\predict\{file.name.split('.')[0]}.mp4") \
and not os.path.exists(fr"runs\detect\predict\{file.name.split('.')[0]}.mp4"):
model.predict(f"user/{file.name.split('.')[0]}.mp4",
save=True)
convert_avi_to_mp4(
fr"runs\detect\predict{counter}\{file.name.split('.')[0]}.avi",
fr"runs\detect\predict{counter}\{file.name.split('.')[0]}.mp4")
if os.path.exists(
fr"runs\detect\predict{counter}\{file.name.split('.')[0]}.mp4"):
st.video(
fr"runs\detect\predict{counter}\{file.name.split('.')[0]}.mp4",
)
convert_avi_to_mp4(
fr"runs\detect\predict{counter}\{file.name.split('.')[0]}.avi",
fr"runs\detect\predict{counter}\{file.name.split('.')[0]}.mp4")
elif os.path.exists(fr"runs\detect\predict\{file.name.split('.')[0]}.mp4"):
st.video(fr"runs\detect\predict\{file.name.split('.')[0]}.mp4")
else:
if not os.path.exists(fr"runs\detect\predict\{file.name.split('.')[0]}.mp4"):
model.predict(f"user/{file.name.split('.')[0]}.mp4",
save=True)
convert_avi_to_mp4(
fr"runs\detect\predict\{file.name.split('.')[0]}.avi",
fr"runs\detect\predict\{file.name.split('.')[0]}.mp4")
if os.path.exists(fr"runs\detect\predict\{file.name.split('.')[0]}.mp4"):
st.video(fr"runs\detect\predict\{file.name.split('.')[0]}.mp4")
if __name__ == "__main__":
main()