-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
290 lines (259 loc) · 11.4 KB
/
app.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import streamlit as st
import cv2
import torch
from utils.hubconf import custom
import numpy as np
import tempfile
import time
from collections import Counter
import json
import pandas as pd
from model_utils import get_yolo, color_picker_fn, get_system_stat
# from ultralytics import YOLO
import io
import os
p_time = 0
def open_image_as_file(path):
# 读取图像
img = cv2.imread(path)
if img is None:
st.error(f"Error: Unable to read the image from path: {path}")
return None
# 将图像编码为字节
success, img_encoded = cv2.imencode('.jpg', img)
if not success:
st.error(f"Error: Unable to encode the image to bytes")
return None
# 使用 io.BytesIO 模拟文件对象
img_file = io.BytesIO(img_encoded.tobytes())
img_file.name = path # 设置文件名属性
return img_file
st.sidebar.title('Settings')
# Choose the model
model_type = st.sidebar.selectbox(
# 'Choose YOLO Model', ('YOLO Model', 'YOLOv8', 'YOLOv7')
'Choose YOLO Model', ('yolov7', 'carnumber')
)
st.title(f'{model_type} Predictions')
sample_img = cv2.imread('logo.jpg')
FRAME_WINDOW = st.image(sample_img, channels='BGR')
cap = None
path_model_file = st.sidebar.text_input(
f'path to {model_type} Model:',
f'{model_type}.pt'
)
if st.sidebar.checkbox('Load Model'):
if model_type == 'carnumber':
model = custom(path_or_model=path_model_file)
if model_type == 'yolov7':
model = custom(path_or_model=path_model_file)
# Load Class names
class_labels = model.names
# Inference Mode
options = st.sidebar.radio(
'Options:', ('Image', 'Video','Webcam'), index=0)
# Confidence
confidence = st.sidebar.slider(
'Detection Confidence', min_value=0.0, max_value=1.0, value=0.25)
# Draw thickness
draw_thick = st.sidebar.slider(
'Draw Thickness:', min_value=1,
max_value=20, value=2
)
color_pick_list = []
for i in range(len(class_labels)):
classname = class_labels[i]
color = color_picker_fn(classname, i)
color_pick_list.append(color)
# Image
if options == 'Image':
option1 = st.sidebar.selectbox(
'you can select some image',
('default','image_1', 'image_2', 'image_3'))
if option1 =='image_1':
upload_img_file = open_image_as_file('image/1.jpg')
elif option1 =='image_2':
upload_img_file = open_image_as_file('image/2.jpg')
elif option1 =='image_3':
upload_img_file = open_image_as_file('image/3.jpg')
else:
upload_img_file = st.sidebar.file_uploader('Upload Image', type=['jpg', 'jpeg', 'png'])
if upload_img_file is not None:
pred = st.checkbox(f'Predict Using {model_type}')
file_bytes = np.asarray(
bytearray(upload_img_file.read()), dtype=np.uint8)
img = cv2.imdecode(file_bytes, 1)
FRAME_WINDOW.image(img, channels='BGR')
# # Image
# if options == 'Image':
# upload_img_file = st.sidebar.file_uploader(
# 'Upload Image', type=['jpg', 'jpeg', 'png'])
# if upload_img_file is not None:
# pred = st.checkbox(f'Predict Using {model_type}')
# file_bytes = np.asarray(
# bytearray(upload_img_file.read()), dtype=np.uint8)
# img = cv2.imdecode(file_bytes, 1)
# FRAME_WINDOW.image(img, channels='BGR')
if pred:
img, current_no_class = get_yolo(img, model_type, model, confidence, color_pick_list, class_labels, draw_thick)
FRAME_WINDOW.image(img, channels='BGR')
# Current number of classes
class_fq = dict(Counter(i for sub in current_no_class for i in set(sub)))
class_fq = json.dumps(class_fq, indent = 4)
class_fq = json.loads(class_fq)
df_fq = pd.DataFrame(class_fq.items(), columns=['Class', 'Number'])
# Updating Inference results
with st.container():
st.markdown("<h2>Inference Statistics</h2>", unsafe_allow_html=True)
st.markdown("<h3>Detected objects in curret Frame</h3>", unsafe_allow_html=True)
st.dataframe(df_fq, use_container_width=True)
# Video
# if options == 'Video':
# upload_video_file = st.sidebar.file_uploader(
# 'Upload Video', type=['mp4', 'avi', 'mkv'])
# if upload_video_file is not None:
# pred = st.checkbox(f'Predict Using {model_type}')
# tfile = tempfile.NamedTemporaryFile(delete=False)
# tfile.write(upload_video_file.read())
# cap = cv2.VideoCapture(tfile.name)
# # if pred:
def is_key_frame(prev_frame, curr_frame, threshold=300000):
diff = cv2.absdiff(prev_frame, curr_frame)
non_zero_count = np.count_nonzero(diff)
return non_zero_count > threshold
# 原有的代码
if options == 'Video':
upload_video_file = st.sidebar.file_uploader(
'Upload Video', type=['mp4', 'avi', 'mkv'])
if upload_video_file is not None:
pred = st.checkbox(f'Predict Using {model_type}')
extract_key_frames = st.checkbox('Extract Key Frames') # 新增的关键帧提取选项
key_frames = [] # 存储关键帧的列表
tfile = tempfile.NamedTemporaryFile(delete=False)
tfile.write(upload_video_file.read())
cap = cv2.VideoCapture(tfile.name)
if (cap is not None) and pred:
stframe1 = st.empty()
stframe2 = st.empty()
stframe3 = st.empty()
prev_frame = None
frame_count = 0 # 帧计数器
process_every_n_frames = 10 # 每隔 n 帧处理一次
while True:
success, img = cap.read()
if not success:
st.error(
f"{options} NOT working\nCheck {options} properly!!",
icon="🚨"
)
break
frame_count += 1
if extract_key_frames:
gray_frame = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if img is not None else None
if prev_frame is not None and gray_frame is not None and is_key_frame(prev_frame, gray_frame):
key_frames.append(img)
prev_frame = gray_frame
if frame_count % process_every_n_frames == 0:
img, current_no_class = get_yolo(img, model_type, model, confidence, color_pick_list, class_labels,
draw_thick)
FRAME_WINDOW.image(img, channels='BGR')
# 检查 current_no_class 是否存在
if current_no_class:
class_fq = dict(Counter(i for sub in current_no_class for i in set(sub)))
class_fq = json.dumps(class_fq, indent=4)
class_fq = json.loads(class_fq)
df_fq = pd.DataFrame(class_fq.items(), columns=['Class', 'Number'])
# 计算FPS
c_time = time.time()
fps = 1 / (c_time - p_time)
p_time = c_time
# 更新推理结果
get_system_stat(stframe1, stframe2, stframe3, fps, df_fq)
# if extract_key_frames:
# st.write(f'Extracted {len(key_frames)} key frames.')
# for i, frame in enumerate(key_frames):
# st.image(frame, caption=f'Key Frame {i+1}', channels='BGR')
# Web-cam
if options == 'Webcam':
cam_options = st.sidebar.selectbox('Webcam Channel',
('Select Channel', '0', '1', '2', '3'))
if not cam_options == 'Select Channel':
pred = st.checkbox(f'Predict Using {model_type}')
cap = cv2.VideoCapture(int(cam_options))
if not cap.isOpened():
st.error("Error: Could not open webcam.")
else:
st.success(f"Webcam channel {cam_options} opened successfully.")
else:
st.info("Please select a webcam channel.")
stop_button = st.button("Stop", key="stop_button")
if (cap is not None) and pred:
stframe1 = st.empty()
stframe2 = st.empty()
stframe3 = st.empty()
while True:
success, img = cap.read()
if not success:
st.error(
f"{options} NOT working\nCheck {options} properly!!",
icon="🚨"
)
break
#st.image(img, channels="BGR", use_column_width=True)
img, current_no_class = get_yolo(img, model_type, model, confidence, color_pick_list, class_labels,
draw_thick)
FRAME_WINDOW.image(img, channels='BGR')
if stop_button:
capture_frame = img.copy() # 复制当前帧以在停止后显示
break
# 检查 current_no_class 是否存在
if current_no_class:
class_fq = dict(Counter(i for sub in current_no_class for i in set(sub)))
class_fq = json.dumps(class_fq, indent=4)
class_fq = json.loads(class_fq)
df_fq = pd.DataFrame(class_fq.items(), columns=['Class', 'Number'])
if not df_fq.empty:
# 计算FPS
c_time = time.time()
fps = 1 / (c_time - p_time)
p_time = c_time
else:
st.error(
f"No plates detected",
icon="🚨"
)
get_system_stat(stframe1, stframe2, stframe3, fps, df_fq)
# RTSP
# if options == 'RTSP':
# rtsp_url = st.sidebar.text_input(
# 'RTSP URL:',
# 'eg: rtsp://admin:[email protected]/cam/realmonitor?channel=0&subtype=0'
# )
# pred = st.checkbox(f'Predict Using {model_type}')
# cap = cv2.VideoCapture(rtsp_url)
# if (cap != None) and pred:
# stframe1 = st.empty()
# stframe2 = st.empty()
# stframe3 = st.empty()
# while True:
# success, img = cap.read()
# if not success:
# st.error(
# f"{options} NOT working\nCheck {options} properly!!",
# icon="🚨"
# )
# break
# img, current_no_class = get_yolo(img, model_type, model, confidence, color_pick_list, class_labels, draw_thick)
# FRAME_WINDOW.image(img, channels='BGR')
# FPS
# c_time = time.time()
# fps = 1 / (c_time - p_time)
# p_time = c_time
# # 检查 current_no_class 是否存在
# if current_no_class:
# class_fq = dict(Counter(i for sub in current_no_class for i in set(sub)))
# class_fq = json.dumps(class_fq, indent=4)
# class_fq = json.loads(class_fq)
# df_fq = pd.DataFrame(class_fq.items(), columns=['Class', 'Number'])
# # Updating Inference results
# get_system_stat(stframe1, stframe2, stframe3, fps, df_fq)