ntsc207 commited on
Commit
d980547
·
verified ·
1 Parent(s): 0e5e340

Update detect_deepsort.py

Browse files
Files changed (1) hide show
  1. detect_deepsort.py +41 -43
detect_deepsort.py CHANGED
@@ -1,4 +1,3 @@
1
- #import spaces
2
  import argparse
3
  import os
4
  import platform
@@ -23,7 +22,6 @@ from utils.general import (LOGGER, Profile, check_file, check_img_size, check_im
23
  from utils.plots import Annotator, colors, save_one_box
24
  from utils.torch_utils import select_device, smart_inference_mode
25
 
26
- #@spaces.GPU(duration=120)
27
  # def initialize_deepsort():
28
  # # Create the Deep SORT configuration object and load settings from the YAML file
29
  # cfg_deep = get_config()
@@ -42,12 +40,12 @@ from utils.torch_utils import select_device, smart_inference_mode
42
  # max_age=cfg_deep.DEEPSORT.MAX_AGE, n_init=cfg_deep.DEEPSORT.N_INIT,
43
  # #nn_budget: It sets the budget for the nearest-neighbor search.
44
  # nn_budget=cfg_deep.DEEPSORT.NN_BUDGET,
45
- # use_cuda=True
46
  # )
47
 
48
  # return deepsort
49
 
50
- # deepsort = initialize_deepsort()
51
  data_deque = {}
52
  def classNames():
53
  cocoClassNames = ["Bus", "Bike", "Car", "Pedestrian", "Truck"
@@ -56,16 +54,16 @@ def classNames():
56
  className = classNames()
57
 
58
  def colorLabels(classid):
59
- if classid == 0: #person
60
- color = (85, 45, 255)
61
- elif classid == 1: #car
62
- color = (222, 82, 175)
63
- elif classid == 2: #Motorbike
64
- color = (0, 204, 255)
65
- elif classid == 3: #Bus
66
- color = (0,149,255)
67
- else:
68
- color = (200, 100,0)
69
  return tuple(color)
70
 
71
  def draw_boxes(frame, bbox_xyxy, draw_trails, identities=None, categories=None, offset=(0,0)):
@@ -110,7 +108,6 @@ def draw_boxes(frame, bbox_xyxy, draw_trails, identities=None, categories=None,
110
  cv2.line(frame, data_deque[id][i - 1], data_deque[id][i], color, thickness)
111
  return frame
112
 
113
- #@spaces.GPU(duration=120)
114
  @smart_inference_mode()
115
  def run_deepsort(
116
  weights=ROOT / 'yolo.pt', # model path or triton URL
@@ -149,17 +146,11 @@ def run_deepsort(
149
  save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
150
  save_dir.mkdir(parents=True, exist_ok=True) # make dir
151
 
152
- # Load model
153
- device = select_device(device)
154
- model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
155
- stride, names, pt = model.stride, model.names, model.pt
156
- imgsz = check_img_size(imgsz, s=stride) # check image size
157
-
158
- #Initalize deep sort
159
  # Create the Deep SORT configuration object and load settings from the YAML file
160
  cfg_deep = get_config()
161
  cfg_deep.merge_from_file("deep_sort_pytorch/configs/deep_sort.yaml")
162
-
163
  # Initialize the DeepSort tracker
164
  deepsort = DeepSort(cfg_deep.DEEPSORT.REID_CKPT,
165
  max_dist=cfg_deep.DEEPSORT.MAX_DIST,
@@ -173,8 +164,15 @@ def run_deepsort(
173
  max_age=cfg_deep.DEEPSORT.MAX_AGE, n_init=cfg_deep.DEEPSORT.N_INIT,
174
  #nn_budget: It sets the budget for the nearest-neighbor search.
175
  nn_budget=cfg_deep.DEEPSORT.NN_BUDGET,
176
- use_cuda=True
177
  )
 
 
 
 
 
 
 
178
  # Dataloader
179
  bs = 1 # batch_size
180
  if webcam:
@@ -202,7 +200,7 @@ def run_deepsort(
202
  with dt[1]:
203
  visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
204
  pred = model(im, augment=augment, visualize=visualize)
205
- pred = pred[0][0]
206
 
207
  # NMS
208
  with dt[2]:
@@ -216,14 +214,14 @@ def run_deepsort(
216
  seen += 1
217
  if webcam: # batch_size >= 1
218
  p, im0, frame = path[i], im0s[i].copy(), dataset.count
219
- #s += f'{i}: '
220
  else:
221
  p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
222
 
223
  p = Path(p) # to Path
224
  save_path = str(save_dir / p.name) # im.jpg
225
  txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
226
- #s += '%gx%g ' % im.shape[2:] # print string
227
  gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
228
  ims = im0.copy()
229
  if len(det):
@@ -233,7 +231,7 @@ def run_deepsort(
233
  # Print results
234
  for c in det[:, 5].unique():
235
  n = (det[:, 5] == c).sum() # detections per class
236
- #s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
237
  xywh_bboxs = []
238
  confs = []
239
  oids = []
@@ -271,23 +269,23 @@ def run_deepsort(
271
  cv2.imshow(str(p), ims)
272
  cv2.waitKey(1) # 1 millisecond
273
  # Save results (image with detections)
274
- #if save_img:
275
- #if vid_path[i] != save_path: # new video
276
- #vid_path[i] = save_path
277
- if isinstance(vid_writer[i], cv2.VideoWriter):
278
- vid_writer[i].release() # release previous video writer
279
- if vid_cap: # video
280
- fps = vid_cap.get(cv2.CAP_PROP_FPS)
281
- w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
282
- h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
283
- else: # stream
284
- fps, w, h = 30, ims.shape[1], ims.shape[0]
285
- save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
286
- vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
287
- vid_writer[i].write(ims)
288
 
289
  # Print time (inference-only)
290
- #LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
291
  if update:
292
  strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
293
  return save_path
 
 
1
  import argparse
2
  import os
3
  import platform
 
22
  from utils.plots import Annotator, colors, save_one_box
23
  from utils.torch_utils import select_device, smart_inference_mode
24
 
 
25
  # def initialize_deepsort():
26
  # # Create the Deep SORT configuration object and load settings from the YAML file
27
  # cfg_deep = get_config()
 
40
  # max_age=cfg_deep.DEEPSORT.MAX_AGE, n_init=cfg_deep.DEEPSORT.N_INIT,
41
  # #nn_budget: It sets the budget for the nearest-neighbor search.
42
  # nn_budget=cfg_deep.DEEPSORT.NN_BUDGET,
43
+ # use_cuda=False
44
  # )
45
 
46
  # return deepsort
47
 
48
+ #deepsort = initialize_deepsort()
49
  data_deque = {}
50
  def classNames():
51
  cocoClassNames = ["Bus", "Bike", "Car", "Pedestrian", "Truck"
 
54
  className = classNames()
55
 
56
  def colorLabels(classid):
57
+ if classid == 0: #Bus
58
+ color = (0, 0, 255)
59
+ elif classid == 1: #Bike 250, 247, 0
60
+ color = (0,148,255)
61
+ elif classid == 2: #Car
62
+ color = (0, 255, 10)
63
+ elif classid == 3: #Pedestrian
64
+ color = (250,247,0)
65
+ else: #Truck
66
+ color = (235,0,255)
67
  return tuple(color)
68
 
69
  def draw_boxes(frame, bbox_xyxy, draw_trails, identities=None, categories=None, offset=(0,0)):
 
108
  cv2.line(frame, data_deque[id][i - 1], data_deque[id][i], color, thickness)
109
  return frame
110
 
 
111
  @smart_inference_mode()
112
  def run_deepsort(
113
  weights=ROOT / 'yolo.pt', # model path or triton URL
 
146
  save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
147
  save_dir.mkdir(parents=True, exist_ok=True) # make dir
148
 
149
+ #Initalize deepsort
 
 
 
 
 
 
150
  # Create the Deep SORT configuration object and load settings from the YAML file
151
  cfg_deep = get_config()
152
  cfg_deep.merge_from_file("deep_sort_pytorch/configs/deep_sort.yaml")
153
+
154
  # Initialize the DeepSort tracker
155
  deepsort = DeepSort(cfg_deep.DEEPSORT.REID_CKPT,
156
  max_dist=cfg_deep.DEEPSORT.MAX_DIST,
 
164
  max_age=cfg_deep.DEEPSORT.MAX_AGE, n_init=cfg_deep.DEEPSORT.N_INIT,
165
  #nn_budget: It sets the budget for the nearest-neighbor search.
166
  nn_budget=cfg_deep.DEEPSORT.NN_BUDGET,
167
+ use_cuda=False
168
  )
169
+
170
+ # Load model
171
+ device = select_device(device)
172
+ model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
173
+ stride, names, pt = model.stride, model.names, model.pt
174
+ imgsz = check_img_size(imgsz, s=stride) # check image size
175
+
176
  # Dataloader
177
  bs = 1 # batch_size
178
  if webcam:
 
200
  with dt[1]:
201
  visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
202
  pred = model(im, augment=augment, visualize=visualize)
203
+ pred = pred[0][1]
204
 
205
  # NMS
206
  with dt[2]:
 
214
  seen += 1
215
  if webcam: # batch_size >= 1
216
  p, im0, frame = path[i], im0s[i].copy(), dataset.count
217
+ s += f'{i}: '
218
  else:
219
  p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
220
 
221
  p = Path(p) # to Path
222
  save_path = str(save_dir / p.name) # im.jpg
223
  txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
224
+ s += '%gx%g ' % im.shape[2:] # print string
225
  gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
226
  ims = im0.copy()
227
  if len(det):
 
231
  # Print results
232
  for c in det[:, 5].unique():
233
  n = (det[:, 5] == c).sum() # detections per class
234
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
235
  xywh_bboxs = []
236
  confs = []
237
  oids = []
 
269
  cv2.imshow(str(p), ims)
270
  cv2.waitKey(1) # 1 millisecond
271
  # Save results (image with detections)
272
+ if save_img:
273
+ if vid_path[i] != save_path: # new video
274
+ vid_path[i] = save_path
275
+ if isinstance(vid_writer[i], cv2.VideoWriter):
276
+ vid_writer[i].release() # release previous video writer
277
+ if vid_cap: # video
278
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
279
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
280
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
281
+ else: # stream
282
+ fps, w, h = 30, ims.shape[1], ims.shape[0]
283
+ save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
284
+ vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc('m','p','4','v'), fps, (w, h))
285
+ vid_writer[i].write(ims)
286
 
287
  # Print time (inference-only)
288
+ LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
289
  if update:
290
  strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
291
  return save_path