Repository navigation
Expand file tree
/
Copy pathMetDetPy.py
More file actions
461 lines (418 loc) · 19.8 KB
/
Copy pathMetDetPy.py
File metadata and controls
461 lines (418 loc) · 19.8 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
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import argparse
import json
import time
from typing import Optional
import tqdm
from MetLib import get_detector, get_loader, get_wrapper
from MetLib.profiling import StageProfiler, profile_loader, profile_stage
from MetLib.collector import MeteorCollector
from MetLib.Detector import (BaseDetector, M3Detector, DiffAreaGuidingDetecor,
LineDetector, MLDetector)
from MetLib.fileio import save_path_handler
from MetLib.metlog import get_default_logger, set_default_logger
from MetLib.metstruct import (MDRF, BinaryCfg, ClipCfg, DLCfg, MainDetectCfg,
RuntimeParams)
from MetLib.metvisu import (BaseVisuAttrs, OpenCVMetVisu, TextColorPair,
TextVisu)
from MetLib.model import validate_provider_key
from MetLib.recheck_cache import RecheckFrameCache
from MetLib.utils import (CLIP_CONFIG_PATH, LIVE_MODE_SPEED_CTRL_CONST,
SWITCH2BOOL, VERSION, frame2time, frame2ts,
relative2abs_path)
def detect_video(video_name: str,
mask_name: str,
cfg: MainDetectCfg,
debug_mode: bool = False,
visual_mode: bool = False,
work_mode: str = "frontend",
time_range: tuple[Optional[str],
Optional[str]] = (None, None),
live_mode: bool = False,
provider_key: Optional[str] = None,
profile: bool = False) -> MDRF:
"""The main API of MetDetPy, detecting meteors from the given video.
Args:
video_name (str): The path to the video file.
mask_name (str): The path to the mask file.
cfg (MainDetectCfg): Configuration dict.
debug_mode (bool, optional): when applying debug mode, more details will be logged. Defaults to False.
visual_mode (bool, optional): when applying visual mode, display a window showing the current detecting frames. Defaults to False.
work_mode (str, optional): stdout stream working mode. Select from "backend" and "frontend". Defaults to "frontend".
time_range (tuple, optional): time range from the start to the end. Defaults to (None, None).
live_mode (bool, optional): Whether to apply live mode, detect video at approximate recording time. Defaults to False.
provider_key (Optional[str], optional): provider device. Defaults to None.
profile (bool): Log aggregate stage timings, excluding initialization.
Returns:
dict: a dict that records detection config and results.
"""
if provider_key:
cfg.collector.recheck_cfg.model.providers_key = provider_key
if isinstance(cfg.detector.cfg, DLCfg):
cfg.detector.cfg.model.providers_key = provider_key
# set output mode
set_default_logger(debug_mode, work_mode)
logger = get_default_logger()
logger.start()
# initialization
t0 = time.perf_counter()
try:
# parse preprocessing params
VideoLoaderCls = get_loader(cfg.loader.name)
VideoWrapperCls = get_wrapper(cfg.loader.wrapper)
DetectorCls = get_detector(cfg.detector.name)
resize_option = cfg.loader.resize
exp_option = cfg.loader.exp_time
exp_upper_bound = cfg.loader.upper_bound
merge_func = cfg.loader.merge_func
grayscale = cfg.loader.grayscale
start_time, end_time = time_range
if issubclass(DetectorCls, (LineDetector, DiffAreaGuidingDetecor)):
assert grayscale, "Require grayscale ON when using subclass of LineDetector."
elif issubclass(DetectorCls, MLDetector):
assert not grayscale, "Require grayscale OFF when using MLDetector."
else:
raise NotImplementedError("Detector not ready to use.")
# Load global config
global_config = ClipCfg.from_json_file(CLIP_CONFIG_PATH)
# 复核叠图的旁路帧缓存创建与接线只有存在消费者时才建
recheck_cfg = cfg.collector.recheck_cfg
gate_on = bool(recheck_cfg.gate is not None and recheck_cfg.gate.switch)
needs_frame_cache = (gate_on or recheck_cfg.yolo_stack_source == "cache")
if gate_on and not recheck_cfg.frame_cache:
# 成本退化警告
logger.warning(
"ROI gate is enabled but recheck_cfg.frame_cache is false: the "
"gate will fall back to re-reading the whole window for every "
"candidate, which could be much slower.")
frame_cache = (RecheckFrameCache()
if recheck_cfg.switch and recheck_cfg.frame_cache
and needs_frame_cache else None)
# Init VideoLoader
# Since v2.0.0, VideoLoader will control most video-related varibles and functions.
video_loader = VideoLoaderCls(
VideoWrapperCls,
video_name,
mask_name,
resize_option,
hwaccel=cfg.loader.hwaccel,
start_time=start_time,
end_time=end_time,
grayscale=grayscale,
exp_option=exp_option,
exp_upper_bound=exp_upper_bound,
merge_func=merge_func,
continue_on_err=cfg.loader.continue_on_err,
frame_sink=frame_cache.push if frame_cache is not None else None)
video_info = video_loader.summary()
logger.info(video_loader.__repr__())
# get properties from VideoLoader
start_frame, end_frame = video_loader.start_frame, video_loader.end_frame
rt_param = RuntimeParams(
fps=video_loader.fps,
exp_frame=video_loader.exp_frame,
eq_fps=video_loader.eq_fps,
eq_int_fps=video_loader.eq_int_fps,
exp_time=video_loader.exp_time,
runtime_size=video_loader.runtime_size,
raw_size=video_loader.raw_size,
positive_category_list=global_config.export.positive_category_list)
logger.info(
f"Preprocessing finished. Time cost: {(time.perf_counter() - t0):.1f}s."
)
# wait for logger clear
while not logger.is_empty:
continue
# 对于 M3Detector 类型检测器,需要 window_sec * fps >= 3,否则帧差法可能无法正常工作。
if issubclass(DetectorCls, M3Detector) and (cfg.detector.window_sec *
rt_param.eq_fps < 3):
# 如果原始fps就偏低(<3),即使不进行帧合并也无法运行,抛出错误
if video_loader.fps < 3:
raise ValueError(
"You are using M3Det detector, but the video FPS is too low (less than 3). "
f"{DetectorCls.__name__} cannot work for this video. Consider increasing the video FPS"
" or using the deep learning detector (DLDet) instead.")
else:
logger.info(
f"The calculated video equivalent FPS is {rt_param.eq_fps:.2f}. This may be too slow "
f"for {DetectorCls.__name__}. If this estimate seems inaccurate, consider inputting "
"the actual FPS value instead.")
# Init detector
cfg_det = cfg.detector
detector: BaseDetector = DetectorCls(window_sec=cfg_det.window_sec,
fps=rt_param.eq_fps,
mask=video_loader.mask,
cfg=cfg_det.cfg,
logger=logger)
# Init meteor collector
recheck_loader = None
if recheck_cfg.switch:
recheck_loader = VideoLoaderCls(VideoWrapperCls,
video_name,
None,
resize_option,
hwaccel=cfg.loader.hwaccel,
grayscale=False,
exp_option="real-time",
merge_func=merge_func,
continue_on_err=True)
meteor_collector = MeteorCollector(cfg.collector,
rt_param,
video_loader=recheck_loader,
logger=logger,
mask_name=mask_name,
frame_cache=frame_cache,
producer_maxsize=getattr(
video_loader, "maxsize", 0))
# Init visualizer
# TODO: 可视化模块暂未完全支持参数化设置。
visual_manager = OpenCVMetVisu(exp_time=rt_param.exp_time,
resolution=video_loader.runtime_size,
flag=visual_mode)
# Init main iterator
main_iterator = range(start_frame, end_frame, rt_param.exp_frame)
if work_mode == 'frontend':
main_iterator = tqdm.tqdm(main_iterator, ncols=100)
except Exception as e:
logger.error(e.__repr__())
logger.error(
'Fatal error occured when initializing. MetDetPy will exit.')
logger.stop()
raise e
t1 = time.perf_counter()
logger.info(f"Initialization elapsed: {t1 - t0:.4f}s.")
profilers = []
main_profiler = (StageProfiler(
"main_loop", cpu_stages={"detector.detect", "collector.update"})
if profile else None)
if profile:
profilers.append(profile_loader(video_loader, "main_loader"))
if recheck_loader is not None:
profilers.append(profile_loader(recheck_loader, "recheck_loader"))
profilers.append(main_profiler)
if isinstance(detector, MLDetector):
model_profiler = StageProfiler("main_model")
detector.model.stage_profiler = model_profiler
profilers.append(model_profiler)
if recheck_cfg.switch:
model_profiler = StageProfiler("recheck_model")
meteor_collector.met_exporter.recheck_model.stage_profiler = model_profiler
profilers.append(model_profiler)
if isinstance(detector, M3Detector):
detector.stack.stage_profiler = main_profiler
# MAIN DETECTION PART
tot_wait_time = 0
visu_info: list[BaseVisuAttrs] = []
try:
video_loader.start()
for prog_int, i in enumerate(main_iterator):
# Logging for backend only.
if work_mode == 'backend' and (
(i - start_frame) //
rt_param.exp_frame) % rt_param.eq_int_fps == 0:
logger.processing(str(frame2time(i, rt_param.fps)))
with profile_stage(main_profiler, "pop.total"):
x = video_loader.pop()
if (video_loader.stopped or x is None):
break
with profile_stage(main_profiler, "detector.update"):
detector.update(x)
with profile_stage(main_profiler, "detector.detect"):
lines, cates = detector.detect()
if len(lines) or (((i - start_frame) // rt_param.exp_frame) %
rt_param.eq_int_fps == 0):
with profile_stage(main_profiler, "collector.update"):
meteor_collector.update(i, lines=lines, cates=cates)
if visual_mode:
# 仅在可视化模式下通过detector和collector的可视化接口获取需要渲染的所有内容。
visu_info.append(
TextVisu(
"timestamp",
text_list=[TextColorPair(frame2ts(i, rt_param.fps))],
position="left-bottom",
color="white"))
visu_info.extend(detector.visu())
visu_info.extend(meteor_collector.visu(frame_num=i))
visual_manager.display_a_frame(x, visu_info)
visu_info.clear()
if visual_manager.manual_stop:
logger.info('Manual interrupt signal detected.')
break
# 直播模式等待进度
if live_mode:
expect_time_cost = (prog_int * rt_param.exp_frame /
rt_param.fps) * LIVE_MODE_SPEED_CTRL_CONST
cur_time_cost = time.perf_counter() - t0
if (cur_time_cost < expect_time_cost):
tot_wait_time += (expect_time_cost - cur_time_cost)
time.sleep(expect_time_cost - cur_time_cost)
# 仅正常结束时(即 手动结束或视频读取完)打印。
if not visual_manager.manual_stop:
logger.info('VideoLoader-stop detected.')
except Exception as e:
logger.error(e.__repr__())
raise e
finally:
video_loader.release()
meteor_collector.clear()
visual_manager.stop()
logger.info("Time cost: %.4fs." % (time.perf_counter() - t1))
logger.info(
"Recheck model call count = "
f"{meteor_collector.met_exporter.recheck_model_call_count}.")
exporter = meteor_collector.met_exporter
logger.debug(
"Recheck stack health: gap_patched="
f"{exporter.stack_patched_gaps}; gate_skipped_incomplete="
f"{exporter.gate_skipped_incomplete}.")
recheck_read_failure_count = (recheck_loader.read_failure_count
if recheck_loader is not None else 0)
logger.info(
"Video read failure count: "
f"main={video_loader.read_failure_count}; "
f"recheck={recheck_read_failure_count}; "
f"total={video_loader.read_failure_count + recheck_read_failure_count}."
)
if profile:
logger.info("[Profile] Wall-clock timings after initialization; "
"nested stages and concurrent threads overlap.")
logger.info("[Profile] Selected stages also report calling-thread "
"CPU time.")
for profiler in profilers:
for line in profiler.summary():
logger.info(line)
if live_mode:
logger.debug(f"Total Wait Time = {tot_wait_time:.4f}s.")
logger.stop()
return MDRF(version=VERSION,
basic_info=video_info,
config=cfg,
type="prediction",
anno_size=video_info.resolution,
results=meteor_collector.met_exporter.meteor_list)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=f'MetDetPy {VERSION}')
parser.add_argument(
'target',
help="input video. Support common video encoding like H264, HEVC, etc."
)
parser.add_argument('--cfg',
'-C',
help="Path to the config file.",
default=None)
parser.add_argument('--mask', '-M', help="Mask image.", default=None)
parser.add_argument('--start-time',
help="The start time (ms) of the video.",
type=str,
default=None)
parser.add_argument('--end-time',
help="The end time (ms) of the video.",
type=str,
default=None)
parser.add_argument(
'--mode',
choices=['backend', 'frontend'],
default='frontend',
type=str,
help='Working mode. Logging will change according to the working mode.'
)
parser.add_argument('--debug',
'-D',
action='store_true',
help="Apply Debug Mode",
default=False)
parser.add_argument('--visual',
'-V',
action='store_true',
help="Apply Visual Mode",
default=False)
parser.add_argument('--resize',
help="Running-time resolution",
type=str,
default=None)
parser.add_argument(
'--exp-time',
help=
"The exposure time (s) of the video. \"auto\", \"real-time\",\"slow\" are also supported.",
type=str,
default=None)
parser.add_argument('--adaptive-thre',
nargs='?',
const='on',
choices=['on', 'off'],
default=None,
type=str,
help="Apply adaptive binary threshold.")
group_bi = parser.add_mutually_exclusive_group(required=False)
group_bi.add_argument('--bi-thre',
type=int,
default=None,
help="Constant binary threshold value.")
group_bi.add_argument('--sensitivity',
type=str,
default=None,
help="The sensitivity of detection.")
parser.add_argument('--recheck',
type=str,
choices=['on', 'off'],
default=None,
help="Apply recheck before the result is printed"
" (the model must specified in the config file).")
parser.add_argument(
"--provider",
type=validate_provider_key,
default=None,
help="Select provider: cpu, default, dml[:N], cuda[:N], coreml.")
parser.add_argument("--live-mode",
type=str,
nargs='?',
const='on',
choices=['on', 'off'],
default=None,
help="Apply live mode, detect video as real-time.")
parser.add_argument("--save-path",
type=str,
default=None,
help="Save detection results as a json file.")
parser.add_argument(
"--profile",
action="store_true",
help="Print aggregate stage wall-clock timings at exit.")
args = parser.parse_args()
if args.cfg is None:
args.cfg = relative2abs_path("./config/m3det_normal.json")
cfg = MainDetectCfg.from_json_file(args.cfg)
# 当通过参数的指定部分选项时,替代配置文件中的缺省项
# replace cfg value
if args.exp_time:
cfg.loader.exp_time = args.exp_time
if args.resize:
cfg.loader.resize = args.resize
# 与二值化有关的参数仅在使用直线型检测器时生效
if isinstance(cfg.detector.cfg, BinaryCfg):
if args.adaptive_thre:
cfg.detector.cfg.binary.adaptive_bi_thre = SWITCH2BOOL[
args.adaptive_thre]
if args.sensitivity:
cfg.detector.cfg.binary.sensitivity = args.sensitivity
if args.bi_thre:
cfg.detector.cfg.binary.init_value = args.bi_thre
if args.recheck:
cfg.collector.recheck_cfg.switch = SWITCH2BOOL[args.recheck]
if args.live_mode:
live_mode = SWITCH2BOOL[args.live_mode]
else:
live_mode = False
result = detect_video(args.target,
args.mask,
cfg,
args.debug,
args.visual,
work_mode=args.mode,
time_range=(args.start_time, args.end_time),
live_mode=live_mode,
provider_key=args.provider,
profile=args.profile)
if args.save_path:
save_path = save_path_handler(args.save_path, args.target, ext="json")
with open(save_path, mode="w", encoding="utf-8") as f:
json.dump(result.to_dict(), f, ensure_ascii=False, indent=4)