当前位置:   article > 正文

YOLO+SlowFast+DeepSORT 简单实现视频行为识别_rknn slowfast

rknn slowfast

前言

前段时间刷短视频看到过别人用摄像头自动化监控员工上班状态,比如标注员工是不是离开了工位,在位置上是不是摸鱼。虽然是段子,但是这个是可以用识别技术实现一下,于是我在网上找,知道发现了 SlowFast,那么下面就用 SlowFast 简单测试一下视频的行为识别。

工具简介

YOLO

YOLO 是一个基于深度学习神经网络的对象识别和定位算法,前面我也用 v5s 训练了标注的扑克牌,实现了图片或视频中的点数识别,这里就跳过了。

DeepSORT

DeepSORT 是一个实现目标跟踪的算法,其使用卡尔曼滤波器预测所检测对象的运动轨迹。也就是当视频中有多个目标,算法能知道上一帧与下一帧各目标对象的匹配,从而完成平滑锁定,而不是在视频播放或记录时,检测框一闪一闪的。

SlowFast

SlowFast 是一个行为分类模型 (pytorchvideo 内置),可以通过输入视频序列和检测框信息,输出每个检测框的行为类别。所以需要借助类似 YOLO 的多目标检测模型,当然 SlowFast 也可以自行标注数据集训练,来完成自定义的行为识别。

流程

读取视频或者摄像头中的图片

通过 yolo 检测出画面的目标

通过 deep_sort 对目标进行跟踪

通过 slowfast 识别出目标的动作

根据识别的动作进行业务处理等

编码

整个流程下来,除了安装 slowfast 依赖 (pytorchvideo) 外,deep_sort 可以下载  然后 import 到项目中。如果要实时处理摄像头的视频,可以通过采用多线程,单独开一个线程读摄像头并一秒保存一张图,再开一个线程用于处理保存的图片,最后将处理后的结果保存为视频,或者只是做一些业务操作,以下只是一个例子。

  1. import torch
  2. import numpy as np
  3. import os,cv2,time,torch,random,pytorchvideo,warnings,argparse,math
  4. warnings.filterwarnings("ignore",category=UserWarning)
  5. from pytorchvideo.transforms.functional import (
  6. uniform_temporal_subsample,
  7. short_side_scale_with_boxes,
  8. clip_boxes_to_image,)
  9. from torchvision.transforms._functional_video import normalize
  10. from pytorchvideo.data.ava import AvaLabeledVideoFramePaths
  11. from pytorchvideo.models.hub import slowfast_r50_detection
  12. from deep_sort.deep_sort import DeepSort
  13. class MyVideoCapture:
  14. def __init__(self, source):
  15. self.cap = cv2.VideoCapture(source)
  16. self.idx = -1
  17. self.end = False
  18. self.stack = []
  19. def read(self):
  20. self.idx += 1
  21. ret, img = self.cap.read()
  22. if ret:
  23. self.stack.append(img)
  24. else:
  25. self.end = True
  26. return ret, img
  27. def to_tensor(self, img):
  28. img = torch.from_numpy(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  29. return img.unsqueeze(0)
  30. def get_video_clip(self):
  31. assert len(self.stack) > 0, "clip length must large than 0 !"
  32. self.stack = [self.to_tensor(img) for img in self.stack]
  33. clip = torch.cat(self.stack).permute(-1, 0, 1, 2)
  34. del self.stack
  35. self.stack = []
  36. return clip
  37. def release(self):
  38. self.cap.release()
  39. def tensor_to_numpy(tensor):
  40. img = tensor.cpu().numpy().transpose((1, 2, 0))
  41. return img
  42. def ava_inference_transform(
  43. clip,
  44. boxes,
  45. num_frames = 32, #if using slowfast_r50_detection, change this to 32, 4 for slow
  46. crop_size = 640,
  47. data_mean = [0.45, 0.45, 0.45],
  48. data_std = [0.225, 0.225, 0.225],
  49. slow_fast_alpha = 4, #if using slowfast_r50_detection, change this to 4, None for slow
  50. ):
  51. boxes = np.array(boxes)
  52. roi_boxes = boxes.copy()
  53. clip = uniform_temporal_subsample(clip, num_frames)
  54. clip = clip.float()
  55. clip = clip / 255.0
  56. height, width = clip.shape[2], clip.shape[3]
  57. boxes = clip_boxes_to_image(boxes, height, width)
  58. clip, boxes = short_side_scale_with_boxes(clip,size=crop_size,boxes=boxes,)
  59. clip = normalize(clip,
  60. np.array(data_mean, dtype=np.float32),
  61. np.array(data_std, dtype=np.float32),)
  62. boxes = clip_boxes_to_image(boxes, clip.shape[2], clip.shape[3])
  63. if slow_fast_alpha is not None:
  64. fast_pathway = clip
  65. slow_pathway = torch.index_select(clip,1,
  66. torch.linspace(0, clip.shape[1] - 1, clip.shape[1] // slow_fast_alpha).long())
  67. clip = [slow_pathway, fast_pathway]
  68. return clip, torch.from_numpy(boxes), roi_boxes
  69. def plot_one_box(x, img, color=[100,100,100], text_info="None",
  70. velocity=None, thickness=1, fontsize=0.5, fontthickness=1):
  71. c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
  72. cv2.rectangle(img, c1, c2, color, thickness, lineType=cv2.LINE_AA)
  73. t_size = cv2.getTextSize(text_info, cv2.FONT_HERSHEY_TRIPLEX, fontsize , fontthickness+2)[0]
  74. cv2.rectangle(img, c1, (c1[0] + int(t_size[0]), c1[1] + int(t_size[1]*1.45)), color, -1)
  75. cv2.putText(img, text_info, (c1[0], c1[1]+t_size[1]+2),
  76. cv2.FONT_HERSHEY_TRIPLEX, fontsize, [255,255,255], fontthickness)
  77. return img
  78. def deepsort_update(Tracker, pred, xywh, np_img):
  79. outputs = Tracker.update(xywh, pred[:,4:5],pred[:,5].tolist(),cv2.cvtColor(np_img,cv2.COLOR_BGR2RGB))
  80. return outputs
  81. def save_yolopreds_tovideo(yolo_preds, id_to_ava_labels, color_map, output_video, vis=False):
  82. for i, (im, pred) in enumerate(zip(yolo_preds.ims, yolo_preds.pred)):
  83. if pred.shape[0]:
  84. for j, (*box, cls, trackid, vx, vy) in enumerate(pred):
  85. if int(cls) != 0:
  86. ava_label = ''
  87. elif trackid in id_to_ava_labels.keys():
  88. ava_label = id_to_ava_labels[trackid].split(' ')[0]
  89. else:
  90. ava_label = 'Unknow'
  91. text = '{} {} {}'.format(int(trackid),yolo_preds.names[int(cls)],ava_label)
  92. color = color_map[int(cls)]
  93. im = plot_one_box(box,im,color,text)
  94. im = im.astype(np.uint8)
  95. output_video.write(im)
  96. if vis:
  97. cv2.imshow("demo", im)
  98. def main(config):
  99. device = config.device
  100. imsize = config.imsize
  101. # model = torch.hub.load('D:/3code/6pytorch/opencv_demo/05_yolo_v5.6', 'yolov5s', source='local', pretrained=True).to(device)
  102. model = torch.hub.load('ultralytics/yolov5', 'yolov5l6').to(device)
  103. model.conf = config.conf
  104. model.iou = config.iou
  105. model.max_det = 100
  106. if config.classes:
  107. model.classes = config.classes
  108. video_model = slowfast_r50_detection(True).eval().to(device)
  109. deepsort_tracker = DeepSort("deep_sort/deep_sort/deep/checkpoint/ckpt.t7")
  110. ava_labelnames,_ = AvaLabeledVideoFramePaths.read_label_map("selfutils/temp.pbtxt")
  111. coco_color_map = [[random.randint(0, 255) for _ in range(3)] for _ in range(80)]
  112. vide_save_path = config.output
  113. video=cv2.VideoCapture(config.input)
  114. width,height = int(video.get(3)),int(video.get(4))
  115. video.release()
  116. outputvideo = cv2.VideoWriter(vide_save_path,cv2.VideoWriter_fourcc(*'mp4v'), 25, (width,height))
  117. print("processing...")
  118. cap = MyVideoCapture(config.input)
  119. id_to_ava_labels = {}
  120. a=time.time()
  121. while not cap.end:
  122. ret, img = cap.read()
  123. if not ret:
  124. continue
  125. yolo_preds=model([img], size=imsize)
  126. yolo_preds.files=["img.jpg"]
  127. deepsort_outputs=[]
  128. for j in range(len(yolo_preds.pred)):
  129. temp=deepsort_update(deepsort_tracker,yolo_preds.pred[j].cpu(),yolo_preds.xywh[j][:,0:4].cpu(),yolo_preds.ims[j])
  130. if len(temp)==0:
  131. temp=np.ones((0,8))
  132. deepsort_outputs.append(temp.astype(np.float32))
  133. yolo_preds.pred=deepsort_outputs
  134. if len(cap.stack) == 25:
  135. print(f"processing {cap.idx // 25}th second clips")
  136. clip = cap.get_video_clip()
  137. if yolo_preds.pred[0].shape[0]:
  138. inputs, inp_boxes, _=ava_inference_transform(clip, yolo_preds.pred[0][:,0:4], crop_size=imsize)
  139. inp_boxes = torch.cat([torch.zeros(inp_boxes.shape[0],1), inp_boxes], dim=1)
  140. if isinstance(inputs, list):
  141. inputs = [inp.unsqueeze(0).to(device) for inp in inputs]
  142. else:
  143. inputs = inputs.unsqueeze(0).to(device)
  144. with torch.no_grad():
  145. slowfaster_preds = video_model(inputs, inp_boxes.to(device))
  146. slowfaster_preds = slowfaster_preds.cpu()
  147. for tid,avalabel in zip(yolo_preds.pred[0][:,5].tolist(), np.argmax(slowfaster_preds, axis=1).tolist()):
  148. id_to_ava_labels[tid] = ava_labelnames[avalabel+1]
  149. save_yolopreds_tovideo(yolo_preds, id_to_ava_labels, coco_color_map, outputvideo, config.show)
  150. print("total cost: {:.3f} s, video length: {} s".format(time.time()-a, cap.idx / 25))
  151. cap.release()
  152. outputvideo.release()
  153. print('saved video to:', vide_save_path)
  154. if __name__=="__main__":
  155. parser = argparse.ArgumentParser()
  156. parser.add_argument('--input', type=str, default="/home/wufan/images/video/vad.mp4", help='test imgs folder or video or camera')
  157. parser.add_argument('--output', type=str, default="output.mp4", help='folder to save result imgs, can not use input folder')
  158. parser.add_argument('--imsize', type=int, default=640, help='inference size (pixels)')
  159. parser.add_argument('--conf', type=float, default=0.4, help='object confidence threshold')
  160. parser.add_argument('--iou', type=float, default=0.4, help='IOU threshold for NMS')
  161. parser.add_argument('--device', default='cuda', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  162. parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
  163. parser.add_argument('--show', action='store_true', help='show img')
  164. config = parser.parse_args()
  165. if config.input.isdigit():
  166. print("using local camera.")
  167. config.input = int(config.input)
  168. print(config)
  169. main(config)

其他

demo 中用的是网络 yolo,默认下载位置 C:\Users\Administrator/.cache\torch\hub\ultralytics_yolov5_master,而 slowfast 权重文件位置是 C:\Users\Administrator\.cache\torch\hub\checkpoints\SLOWFAST_8x8_R50_DETECTION.pyth。

报错

运行执行命令,出现 AttributeError: ‘Upsample’ object has no attribute 'recompute_scale_factor’错误,根据提示,找到 torch 下的 upsampling.py,将 return F.interpolate (input, self.size, self.scale_factor, self.mode, self.align_corners,
                             # recompute_scale_factor=self.recompute_scale_factor) 修改为
return F.interpolate(input, self.size, self.scale_factor, self.mode, self.align_corners)。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/806721
推荐阅读
相关标签
  

闽ICP备14008679号