yolov5视频流实时检测实现

news/2024/9/30 9:19:23

yolov5

https://github.com/ultralytics/yolov5

 

对rtsp视频流的支持

https://github.com/ultralytics/yolov5/blob/master/detect.py

 

@smart_inference_mode()
def run(weights=ROOT / 'yolov5s.pt',  # model path or triton URLsource=ROOT / 'data/images',  # file/dir/URL/glob/screen/0(webcam)data=ROOT / 'data/coco128.yaml',  # dataset.yaml pathimgsz=(640, 640),  # inference size (height, width)conf_thres=0.25,  # confidence thresholdiou_thres=0.45,  # NMS IOU thresholdmax_det=1000,  # maximum detections per imagedevice='',  # cuda device, i.e. 0 or 0,1,2,3 or cpuview_img=False,  # show resultssave_txt=False,  # save results to *.txtsave_conf=False,  # save confidences in --save-txt labelssave_crop=False,  # save cropped prediction boxesnosave=False,  # do not save images/videosclasses=None,  # filter by class: --class 0, or --class 0 2 3agnostic_nms=False,  # class-agnostic NMSaugment=False,  # augmented inferencevisualize=False,  # visualize featuresupdate=False,  # update all modelsproject=ROOT / 'runs/detect',  # save results to project/namename='exp',  # save results to project/nameexist_ok=False,  # existing project/name ok, do not incrementline_thickness=3,  # bounding box thickness (pixels)hide_labels=False,  # hide labelshide_conf=False,  # hide confidenceshalf=False,  # use FP16 half-precision inferencednn=False,  # use OpenCV DNN for ONNX inferencevid_stride=1,  # video frame-rate stride
):source = str(source)save_img = not nosave and not source.endswith('.txt')  # save inference imagesis_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)screenshot = source.lower().startswith('screen')if is_url and is_file:source = check_file(source)  # download# Directoriessave_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir# Load modeldevice = select_device(device)model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)stride, names, pt = model.stride, model.names, model.ptimgsz = check_img_size(imgsz, s=stride)  # check image size# Dataloaderbs = 1  # batch_sizeif webcam:view_img = check_imshow(warn=True)dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)bs = len(dataset)elif screenshot:dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)else:dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)vid_path, vid_writer = [None] * bs, [None] * bs# Run inferencemodel.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz))  # warmupseen, windows, dt = 0, [], (Profile(), Profile(), Profile())for path, im, im0s, vid_cap, s in dataset:with dt[0]:im = torch.from_numpy(im).to(model.device)im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32im /= 255  # 0 - 255 to 0.0 - 1.0if len(im.shape) == 3:im = im[None]  # expand for batch dim# Inferencewith dt[1]:visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else Falsepred = model(im, augment=augment, visualize=visualize)# NMSwith dt[2]:pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)# Second-stage classifier (optional)# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)# Process predictionsfor i, det in enumerate(pred):  # per imageseen += 1if webcam:  # batch_size >= 1p, im0, frame = path[i], im0s[i].copy(), dataset.counts += f'{i}: 'else:p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)p = Path(p)  # to Pathsave_path = str(save_dir / p.name)  # im.jpgtxt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txts += '%gx%g ' % im.shape[2:]  # print stringgn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwhimc = im0.copy() if save_crop else im0  # for save_cropannotator = Annotator(im0, line_width=line_thickness, example=str(names))if len(det):# Rescale boxes from img_size to im0 sizedet[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()# Print resultsfor c in det[:, 5].unique():n = (det[:, 5] == c).sum()  # detections per classs += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string# Write resultsfor *xyxy, conf, cls in reversed(det):if save_txt:  # Write to filexywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywhline = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label formatwith open(f'{txt_path}.txt', 'a') as f:f.write(('%g ' * len(line)).rstrip() % line + '\n')if save_img or save_crop or view_img:  # Add bbox to imagec = int(cls)  # integer classlabel = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')annotator.box_label(xyxy, label, color=colors(c, True))if save_crop:save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)# Stream resultsim0 = annotator.result()if view_img:if platform.system() == 'Linux' and p not in windows:windows.append(p)cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])cv2.imshow(str(p), im0)cv2.waitKey(1)  # 1 millisecond# Save results (image with detections)if save_img:if dataset.mode == 'image':cv2.imwrite(save_path, im0)else:  # 'video' or 'stream'if vid_path[i] != save_path:  # new videovid_path[i] = save_pathif isinstance(vid_writer[i], cv2.VideoWriter):vid_writer[i].release()  # release previous video writerif vid_cap:  # videofps = vid_cap.get(cv2.CAP_PROP_FPS)w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))else:  # streamfps, w, h = 30, im0.shape[1], im0.shape[0]save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videosvid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))vid_writer[i].write(im0)# Print time (inference-only)LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")# Print resultst = tuple(x.t / seen * 1E3 for x in dt)  # speeds per imageLOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)if save_txt or save_img:s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")if update:strip_optimizer(weights[0])  # update model (to fix SourceChangeWarning)

 

https://github.com/ultralytics/yolov5/blob/master/utils/dataloaders.py

class LoadStreams:# YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP streams`def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):torch.backends.cudnn.benchmark = True  # faster for fixed-size inferenceself.mode = 'stream'self.img_size = img_sizeself.stride = strideself.vid_stride = vid_stride  # video frame-rate stridesources = Path(sources).read_text().rsplit() if os.path.isfile(sources) else [sources]n = len(sources)self.sources = [clean_str(x) for x in sources]  # clean source names for laterself.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * nfor i, s in enumerate(sources):  # index, source# Start thread to read frames from video streamst = f'{i + 1}/{n}: {s}... 'if urlparse(s).hostname in ('www.youtube.com', 'youtube.com', 'youtu.be'):  # if source is YouTube video# YouTube format i.e. 'https://www.youtube.com/watch?v=Zgi9g1ksQHc' or 'https://youtu.be/Zgi9g1ksQHc'check_requirements(('pafy', 'youtube_dl==2020.12.2'))import pafys = pafy.new(s).getbest(preftype="mp4").url  # YouTube URLs = eval(s) if s.isnumeric() else s  # i.e. s = '0' local webcamif s == 0:assert not is_colab(), '--source 0 webcam unsupported on Colab. Rerun command in a local environment.'assert not is_kaggle(), '--source 0 webcam unsupported on Kaggle. Rerun command in a local environment.'cap = cv2.VideoCapture(s)assert cap.isOpened(), f'{st}Failed to open {s}'w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))fps = cap.get(cv2.CAP_PROP_FPS)  # warning: may return 0 or nanself.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf')  # infinite stream fallbackself.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30  # 30 FPS fallback
_, self.imgs[i] = cap.read()  # guarantee first frameself.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)LOGGER.info(f"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)")self.threads[i].start()LOGGER.info('')  # newline# check for common shapess = np.stack([letterbox(x, img_size, stride=stride, auto=auto)[0].shape for x in self.imgs])self.rect = np.unique(s, axis=0).shape[0] == 1  # rect inference if all shapes equalself.auto = auto and self.rectself.transforms = transforms  # optionalif not self.rect:LOGGER.warning('WARNING ⚠️ Stream shapes differ. For optimal performance supply similarly-shaped streams.')def update(self, i, cap, stream):# Read stream `i` frames in daemon threadn, f = 0, self.frames[i]  # frame number, frame arraywhile cap.isOpened() and n < f:n += 1cap.grab()  # .read() = .grab() followed by .retrieve()if n % self.vid_stride == 0:success, im = cap.retrieve()if success:self.imgs[i] = imelse:LOGGER.warning('WARNING ⚠️ Video stream unresponsive, please check your IP camera connection.')self.imgs[i] = np.zeros_like(self.imgs[i])cap.open(stream)  # re-open stream if signal was losttime.sleep(0.0)  # wait timedef __iter__(self):self.count = -1return selfdef __next__(self):self.count += 1if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'):  # q to quit
            cv2.destroyAllWindows()raise StopIterationim0 = self.imgs.copy()if self.transforms:im = np.stack([self.transforms(x) for x in im0])  # transformselse:im = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0] for x in im0])  # resizeim = im[..., ::-1].transpose((0, 3, 1, 2))  # BGR to RGB, BHWC to BCHWim = np.ascontiguousarray(im)  # contiguousreturn self.sources, im, im0, None, ''def __len__(self):return len(self.sources)  # 1E12 frames = 32 streams at 30 FPS for 30 years

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ryyt.cn/news/66408.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

小白生于天地之间,岂能郁郁难挖高危?

想要在挂了WAF的站点挖出高危,很难,因为这些站点,你但凡鼠标点快点,检测出了不正确动作都要给你禁IP,至于WAF绕过对于小白更是难搞。其实在众测,大部分漏洞都并非那些什么SQL注入RCE等等,而小白想要出高危,可能也只有寄托希望与未授权。小白的众测高危: 记先前某次众测…

opencascade TopoDS_Iterator源码学习拓扑迭代器

opencascade TopoDS_Iterator 前言 遍历给定 TopoDS_Shape 对象的底层形状,提供对其组件子形状的访问。每个组件形状作为带有方向的 TopoDS_Shape 返回,并且由原始值和相对值组成的复合体。 方法 1 //! 创建一个空的迭代器。 TopoDS_Iterator(); 2 //! 子形状上创建一个迭代器…

浅谈笛卡尔树

[介绍(百度百科)](笛卡尔树_百度百科 (baidu.com)) 笛卡尔树是一种特定的二叉树数据结构,可由数列构造,在范围最值查询、范围\(top_k\)查询(range top k queries)等问题上有广泛应用。它具有堆的有序性,中序遍历可以输出原数列。笛卡尔树结构由Vuillmin(1980)在解决范围…

9.30

[实验任务一]:UML复习 阅读教材第一章复习UML,回答下述问题: 面向对象程序设计中类与类的关系都有哪几种?分别用类图实例说明。 1. 继承:2. 实现:3. 关联: 4. 聚合: 5. 组合: 6. 依赖:

9.30 实验1:UML与面向对象程序设计原则

[实验任务一]:UML复习阅读教材第一章复习UML,回答下述问题:面向对象程序设计中类与类的关系都有哪几种?分别用类图实例说明。 1. 继承关系 Students类继承People类 2.实现关系 一个class类实现interface接口(可以是多个)的功能 3.依赖关系 一个类A使用到了另一…

Windows平台下安装与配置MySQL9

要在Windows平台下安装MySQL,可以使用图行化的安装包。图形化的安装包提供了详细的安装向导,以便于用户一步一步地完成对MySQL的安装。本节将详细介绍使用图形化安装包安装MySQL的方法。 1.2.1 安装MySQL 要想在Windows中运行MySQL,需要32位或64位Windows操作系统,例如Win…

VMware ESXi 8.0U3 macOS Unlocker OEM BIOS 2.7 Dell HPE 定制版 9 月更新发布

VMware ESXi 8.0U3 macOS Unlocker & OEM BIOS 2.7 Dell HPE 定制版 9 月更新发布VMware ESXi 8.0U3 macOS Unlocker & OEM BIOS 2.7 Dell HPE 定制版 9 月更新发布 VMware ESXi 8.0U3 macOS Unlocker & OEM BIOS 2.7 标准版和厂商定制版 ESXi 8.0U3 标准版,Dell …

VMware Aria Suite Lifecycle 8.18 发布,新增功能概览

VMware Aria Suite Lifecycle 8.18 发布,新增功能概览VMware Aria Suite Lifecycle 8.18 - 应用生命周期管理 请访问原文链接:https://sysin.org/blog/vmware-aria-suite-lifecycle/,查看最新版。原创作品,转载请保留出处。 作者主页:sysin.org应用生命周期管理 VMware Ar…