You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

yolo_detect_distince.py 7.6 kB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Author : linjie
  4. # detection: 基于yolov5社交距离
  5. import argparse
  6. from utils.datasets import *
  7. from utils.utils import *
  8. def detect(save_img=False):
  9. out, source, weights, view_img, save_txt, imgsz = \
  10. opt.output, opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
  11. webcam = source == '0' or source.startswith('rtsp') or source.startswith('http') or source.endswith('.txt')
  12. # Initialize
  13. device = torch_utils.select_device(opt.device)
  14. if os.path.exists(out):
  15. shutil.rmtree(out) # delete output folder
  16. os.makedirs(out) # make new output folder
  17. half = device.type != 'cpu' # half precision only supported on CUDA
  18. # Load model
  19. google_utils.attempt_download(weights)
  20. model = torch.load(weights, map_location=device)['model'].float() # load to FP32
  21. # torch.save(torch.load(weights, map_location=device), weights) # update model if SourceChangeWarning
  22. # model.fuse()
  23. model.to(device).eval()
  24. if half:
  25. model.half() # to FP16
  26. # Second-stage classifier
  27. classify = False
  28. if classify:
  29. modelc = torch_utils.load_classifier(name='resnet101', n=2) # initialize
  30. modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights
  31. modelc.to(device).eval()
  32. # Set Dataloader
  33. vid_path, vid_writer = None, None
  34. if webcam:
  35. view_img = True
  36. torch.backends.cudnn.benchmark = True # set True to speed up constant image size inference
  37. dataset = LoadStreams(source, img_size=imgsz)
  38. else:
  39. save_img = True
  40. dataset = LoadImages(source, img_size=imgsz)
  41. # Get names and colors
  42. names = model.names if hasattr(model, 'names') else model.modules.names
  43. colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]
  44. # Run inference
  45. t0 = time.time()
  46. img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
  47. _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
  48. for path, img, im0s, vid_cap in dataset:
  49. img = torch.from_numpy(img).to(device)
  50. img = img.half() if half else img.float() # uint8 to fp16/32
  51. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  52. if img.ndimension() == 3:
  53. img = img.unsqueeze(0)
  54. # Inference
  55. t1 = torch_utils.time_synchronized()
  56. pred = model(img, augment=opt.augment)[0]
  57. # Apply NMS
  58. pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres,
  59. fast=True, classes=opt.classes, agnostic=opt.agnostic_nms)
  60. t2 = torch_utils.time_synchronized()
  61. # Apply Classifier
  62. if classify:
  63. pred = apply_classifier(pred, modelc, img, im0s)
  64. # List to store bounding coordinates of people
  65. people_coords = []
  66. # Process detections
  67. for i, det in enumerate(pred): # detections per image
  68. if webcam: # batch_size >= 1
  69. p, s, im0 = path[i], '%g: ' % i, im0s[i].copy()
  70. else:
  71. p, s, im0 = path, '', im0s
  72. save_path = str(Path(out) / Path(p).name)
  73. s += '%gx%g ' % img.shape[2:] # print string
  74. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  75. if det is not None and len(det):
  76. # Rescale boxes from img_size to im0 size
  77. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  78. # Print results
  79. for c in det[:, -1].unique():
  80. n = (det[:, -1] == c).sum() # detections per class
  81. s += '%g %ss, ' % (n, names[int(c)]) # add to string
  82. # Write results
  83. for *xyxy, conf, cls in det:
  84. if save_txt: # Write to file
  85. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  86. with open(save_path[:save_path.rfind('.')] + '.txt', 'a') as file:
  87. file.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format
  88. if save_img or view_img: # Add bbox to image
  89. label = '%s %.2f' % (names[int(cls)], conf)
  90. if label is not None:
  91. if (label.split())[0] == 'person':
  92. people_coords.append(xyxy)
  93. # plot_one_box(xyxy, im0, line_thickness=3)
  94. plot_dots_on_people(xyxy, im0)
  95. # Plot lines connecting people
  96. distancing(people_coords, im0, dist_thres_lim=(200,250))
  97. # Print time (inference + NMS)
  98. print('%sDone. (%.3fs)' % (s, t2 - t1))
  99. # Stream results
  100. if view_img:
  101. cv2.imshow(p, im0)
  102. if cv2.waitKey(1) == ord('q'): # q to quit
  103. raise StopIteration
  104. # Save results (image with detections)
  105. if save_img:
  106. if dataset.mode == 'images':
  107. cv2.imwrite(save_path, im0)
  108. else:
  109. if vid_path != save_path: # new video
  110. vid_path = save_path
  111. if isinstance(vid_writer, cv2.VideoWriter):
  112. vid_writer.release() # release previous video writer
  113. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  114. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  115. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  116. vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*opt.fourcc), fps, (w, h))
  117. vid_writer.write(im0)
  118. if save_txt or save_img:
  119. print('Results saved to %s' % os.getcwd() + os.sep + out)
  120. if platform == 'darwin': # MacOS
  121. os.system('open ' + save_path)
  122. print('Done. (%.3fs)' % (time.time() - t0))
  123. if __name__ == '__main__':
  124. parser = argparse.ArgumentParser()
  125. parser.add_argument('--weights', type=str, default='weights/yolov5s.pt', help='model.pt path')
  126. parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam
  127. parser.add_argument('--output', type=str, default='inference/output', help='output folder') # output folder
  128. parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
  129. parser.add_argument('--conf-thres', type=float, default=0.4, help='object confidence threshold')
  130. parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS')
  131. parser.add_argument('--fourcc', type=str, default='mp4v', help='output video codec (verify ffmpeg support)')
  132. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  133. parser.add_argument('--view-img', action='store_true', help='display results')
  134. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  135. parser.add_argument('--classes', nargs='+', type=int, help='filter by class')
  136. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  137. parser.add_argument('--augment', action='store_true', help='augmented inference')
  138. opt = parser.parse_args()
  139. opt.img_size = check_img_size(opt.img_size)
  140. print(opt)
  141. with torch.no_grad():
  142. detect()

随着人工智能和大数据的发展,任一方面对自动化工具有着一定的需求,在当下疫情防控期间,使用mindspore来实现yolo模型来进行目标检测及语义分割,对视频或图片都可以进行口罩佩戴检测和行人社交距离检测,来对公共场所的疫情防控来实行自动化管理。