Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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