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():
- # pytorch-accurate time
- if torch.cuda.is_available():
- torch.cuda.synchronize()
- return time.time()
- def select_device(device='', batch_size=None):
- # device = 'cpu' or '0' or '0,1,2,3'
- s = f'YOLOR 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string
- cpu = device.lower() == 'cpu'
- if cpu:
- os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
- elif device: # non-cpu device requested
- # os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
- assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability
- cuda = not cpu and torch.cuda.is_available()
- if cuda:
- n = torch.cuda.device_count()
- if n > 1 and batch_size: # check that batch_size is compatible with device_count
- 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" # bytes to MB
- else:
- s += 'CPU\n'
- logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
- 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 = torch_utils.select_device()
- device = select_device()
- if os.path.exists(out):
- shutil.rmtree(out) # delete output folder
- os.makedirs(out) # make new output folder
- # Load model
- # google_utils.attempt_download(weights)
- model = torch.load(weights, map_location=device)['model']
-
- model.to(device).eval()
- # # Second-stage classifier
- # classify = False
- # if classify:
- # modelc = torch_utils.load_classifier(name='resnet101', n=2) # initialize
- # modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights
- # modelc.to(device).eval()
- # Half precision
- half = True and device.type != 'cpu'
- print('half = ' + str(half))
- if half:
- model.half()
-
- # Set Dataloader
- vid_path, vid_writer = None, None
- dataset = LoadStreams(source, img_size=imgsz)
- #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))]
- # Run inference
- t0 = time.time()
- img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
- _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
- for path, img, im0s, vid_cap in dataset:
- img = torch.from_numpy(img).to(device)
- img = img.half() if half else img.float() # uint8 to fp16/32
- img /= 255.0 # 0 - 255 to 0.0 - 1.0
- if img.ndimension() == 3:
- img = img.unsqueeze(0)
- # Inference
- # t1 = torch_utils.time_synchronized()
- t1 = time_synchronized()
- pred = model(img, augment=False)[0]
-
- # Apply NMS
- pred = non_max_suppression(pred, 0.4, 0.5, classes=None, agnostic=False)
- # t2 = torch_utils.time_synchronized()
- t2 = time_synchronized()
- # # Apply Classifier
- # if classify:
- # pred = apply_classifier(pred, modelc, img, im0s)
- for i, det in enumerate(pred): # detections per image
- p, s, im0 = path, '', im0s
- # save_path = str(Path(out) / Path(p).name)
- s += '%gx%g ' % img.shape[2:] # print string
- gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
- if det is not None and len(det):
- # Rescale boxes from img_size to im0 size
- det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
-
- #for c in det[:, -1].unique(): #probably error with torch 1.5
- for c in det[:, -1].detach().unique():
- n = (det[:, -1] == c).sum() # detections per class
- s += '%g %s, ' % (n, names[int(c)]) # add to string
-
- 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()
|