123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144 |
- import os
- import cv2
- from base_camera import BaseCamera
- import torch
- import torch.nn as nn
- import torchvision
- import numpy as np
- import argparse
- from utils.datasets import *
- from utils.plots import *
- from utils.general import *
- from utils.torch_utils import *
- def time_synchronized():
-
- if torch.cuda.is_available():
- torch.cuda.synchronize()
- return time.time()
- def select_device(device='', batch_size=None):
-
- s = f'YOLOR 🚀 {git_describe() or date_modified()} torch {torch.__version__} '
- cpu = device.lower() == 'cpu'
- if cpu:
- os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
- elif device:
-
- assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested'
- cuda = not cpu and torch.cuda.is_available()
- if cuda:
- n = torch.cuda.device_count()
- if n > 1 and batch_size:
- assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
- space = ' ' * len(s)
- for i, d in enumerate(device.split(',') if device else range(n)):
- p = torch.cuda.get_device_properties(i)
- s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n"
- else:
- s += 'CPU\n'
- logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s)
- return torch.device('cuda:0' if cuda else 'cpu')
- class Camera(BaseCamera):
- video_source = 'rtsp://astrodom:hdci12@192.168.170.73:554/stream1'
- def __init__(self):
- if os.environ.get('OPENCV_CAMERA_SOURCE'):
- Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))
- super(Camera, self).__init__()
- @staticmethod
- def set_video_source(source):
- Camera.video_source = source
- @staticmethod
- def frames():
- out, weights, imgsz = \
- 'inference/output', 'models/best.pt', 640
- source = 'rtsp://astrodom:hdci12@192.168.170.73:554/stream1'
-
- device = select_device()
- if os.path.exists(out):
- shutil.rmtree(out)
- os.makedirs(out)
-
-
- model = torch.load(weights, map_location=device)['model']
-
- model.to(device).eval()
-
-
-
-
-
-
-
- half = True and device.type != 'cpu'
- print('half = ' + str(half))
- if half:
- model.half()
-
-
- vid_path, vid_writer = None, None
- dataset = LoadStreams(source, img_size=imgsz)
-
- names = model.names if hasattr(model, 'names') else model.modules.names
- colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]
-
- t0 = time.time()
- img = torch.zeros((1, 3, imgsz, imgsz), device=device)
- _ = model(img.half() if half else img) if device.type != 'cpu' else None
- for path, img, im0s, vid_cap in dataset:
- img = torch.from_numpy(img).to(device)
- img = img.half() if half else img.float()
- img /= 255.0
- if img.ndimension() == 3:
- img = img.unsqueeze(0)
-
-
- t1 = time_synchronized()
- pred = model(img, augment=False)[0]
-
-
- pred = non_max_suppression(pred, 0.4, 0.5, classes=None, agnostic=False)
-
- t2 = time_synchronized()
-
-
-
- for i, det in enumerate(pred):
- p, s, im0 = path, '', im0s
-
- s += '%gx%g ' % img.shape[2:]
- gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]
- if det is not None and len(det):
-
- det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
-
-
- for c in det[:, -1].detach().unique():
- n = (det[:, -1] == c).sum()
- s += '%g %s, ' % (n, names[int(c)])
-
- for *xyxy, conf, cls in det:
- label = '%s %.2f' % (names[int(cls)], conf)
- plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
- print('%sDone. (%.3fs)' % (s, t2 - t1))
-
- yield cv2.imencode('.jpg', im0)[1].tobytes()
|