camera.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. import os
  2. import cv2
  3. from base_camera import BaseCamera
  4. import torch
  5. import torch.nn as nn
  6. import torchvision
  7. import numpy as np
  8. import argparse
  9. from utils.datasets import *
  10. from utils.plots import *
  11. from utils.general import *
  12. from utils.torch_utils import *
  13. def time_synchronized():
  14. # pytorch-accurate time
  15. if torch.cuda.is_available():
  16. torch.cuda.synchronize()
  17. return time.time()
  18. def select_device(device='', batch_size=None):
  19. # device = 'cpu' or '0' or '0,1,2,3'
  20. s = f'YOLOR 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string
  21. cpu = device.lower() == 'cpu'
  22. if cpu:
  23. os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
  24. elif device: # non-cpu device requested
  25. # os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
  26. assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability
  27. cuda = not cpu and torch.cuda.is_available()
  28. if cuda:
  29. n = torch.cuda.device_count()
  30. if n > 1 and batch_size: # check that batch_size is compatible with device_count
  31. assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
  32. space = ' ' * len(s)
  33. for i, d in enumerate(device.split(',') if device else range(n)):
  34. p = torch.cuda.get_device_properties(i)
  35. s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB
  36. else:
  37. s += 'CPU\n'
  38. logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
  39. return torch.device('cuda:0' if cuda else 'cpu')
  40. class Camera(BaseCamera):
  41. video_source = 'rtsp://astrodom:hdci12@192.168.170.73:554/stream1'
  42. def __init__(self):
  43. if os.environ.get('OPENCV_CAMERA_SOURCE'):
  44. Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))
  45. super(Camera, self).__init__()
  46. @staticmethod
  47. def set_video_source(source):
  48. Camera.video_source = source
  49. @staticmethod
  50. def frames():
  51. out, weights, imgsz = \
  52. 'inference/output', 'models/best.pt', 640
  53. source = 'rtsp://astrodom:hdci12@192.168.170.73:554/stream1'
  54. # device = torch_utils.select_device()
  55. device = select_device()
  56. if os.path.exists(out):
  57. shutil.rmtree(out) # delete output folder
  58. os.makedirs(out) # make new output folder
  59. # Load model
  60. # google_utils.attempt_download(weights)
  61. model = torch.load(weights, map_location=device)['model']
  62. model.to(device).eval()
  63. # # Second-stage classifier
  64. # classify = False
  65. # if classify:
  66. # modelc = torch_utils.load_classifier(name='resnet101', n=2) # initialize
  67. # modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights
  68. # modelc.to(device).eval()
  69. # Half precision
  70. half = True and device.type != 'cpu'
  71. print('half = ' + str(half))
  72. if half:
  73. model.half()
  74. # Set Dataloader
  75. vid_path, vid_writer = None, None
  76. dataset = LoadStreams(source, img_size=imgsz)
  77. #dataset = LoadStreams(source, img_size=imgsz)
  78. names = model.names if hasattr(model, 'names') else model.modules.names
  79. colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]
  80. # Run inference
  81. t0 = time.time()
  82. img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
  83. _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
  84. for path, img, im0s, vid_cap in dataset:
  85. img = torch.from_numpy(img).to(device)
  86. img = img.half() if half else img.float() # uint8 to fp16/32
  87. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  88. if img.ndimension() == 3:
  89. img = img.unsqueeze(0)
  90. # Inference
  91. # t1 = torch_utils.time_synchronized()
  92. t1 = time_synchronized()
  93. pred = model(img, augment=False)[0]
  94. # Apply NMS
  95. pred = non_max_suppression(pred, 0.4, 0.5, classes=None, agnostic=False)
  96. # t2 = torch_utils.time_synchronized()
  97. t2 = time_synchronized()
  98. # # Apply Classifier
  99. # if classify:
  100. # pred = apply_classifier(pred, modelc, img, im0s)
  101. for i, det in enumerate(pred): # detections per image
  102. p, s, im0 = path, '', im0s
  103. # save_path = str(Path(out) / Path(p).name)
  104. s += '%gx%g ' % img.shape[2:] # print string
  105. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  106. if det is not None and len(det):
  107. # Rescale boxes from img_size to im0 size
  108. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  109. #for c in det[:, -1].unique(): #probably error with torch 1.5
  110. for c in det[:, -1].detach().unique():
  111. n = (det[:, -1] == c).sum() # detections per class
  112. s += '%g %s, ' % (n, names[int(c)]) # add to string
  113. for *xyxy, conf, cls in det:
  114. label = '%s %.2f' % (names[int(cls)], conf)
  115. plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
  116. print('%sDone. (%.3fs)' % (s, t2 - t1))
  117. yield cv2.imencode('.jpg', im0)[1].tobytes()