yolov8推理由avi改為mp4

修改\ultralytics-main\ultralytics\engine\predictor.py,即可

# Ultralytics YOLO 🚀, AGPL-3.0 license
"""
Run prediction on images, videos, directories, globs, YouTube, webcam, streams, etc.Usage - sources:$ yolo mode=predict model=yolov8n.pt source=0                               # webcamimg.jpg                         # imagevid.mp4                         # videoscreen                          # screenshotpath/                           # directorylist.txt                        # list of imageslist.streams                    # list of streams'path/*.jpg'                    # glob'https://youtu.be/LNwODJXcvt4'  # YouTube'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP, TCP streamUsage - formats:$ yolo mode=predict model=yolov8n.pt                 # PyTorchyolov8n.torchscript        # TorchScriptyolov8n.onnx               # ONNX Runtime or OpenCV DNN with dnn=Trueyolov8n_openvino_model     # OpenVINOyolov8n.engine             # TensorRTyolov8n.mlpackage          # CoreML (macOS-only)yolov8n_saved_model        # TensorFlow SavedModelyolov8n.pb                 # TensorFlow GraphDefyolov8n.tflite             # TensorFlow Liteyolov8n_edgetpu.tflite     # TensorFlow Edge TPUyolov8n_paddle_model       # PaddlePaddleyolov8n_ncnn_model         # NCNN
"""import platform
import re
import threading
from pathlib import Pathimport cv2
import numpy as np
import torchfrom ultralytics.cfg import get_cfg, get_save_dir
from ultralytics.data import load_inference_source
from ultralytics.data.augment import LetterBox, classify_transforms
from ultralytics.nn.autobackend import AutoBackend
from ultralytics.utils import DEFAULT_CFG, LOGGER, MACOS, WINDOWS, callbacks, colorstr, ops
from ultralytics.utils.checks import check_imgsz, check_imshow
from ultralytics.utils.files import increment_path
from ultralytics.utils.torch_utils import select_device, smart_inference_modeSTREAM_WARNING = """
WARNING ?? inference results will accumulate in RAM unless `stream=True` is passed, causing potential out-of-memory
errors for large sources or long-running streams and videos. See https://docs.ultralytics.com/modes/predict/ for help.Example:results = model(source=..., stream=True)  # generator of Results objectsfor r in results:boxes = r.boxes  # Boxes object for bbox outputsmasks = r.masks  # Masks object for segment masks outputsprobs = r.probs  # Class probabilities for classification outputs
"""class BasePredictor:"""BasePredictor.A base class for creating predictors.Attributes:args (SimpleNamespace): Configuration for the predictor.save_dir (Path): Directory to save results.done_warmup (bool): Whether the predictor has finished setup.model (nn.Module): Model used for prediction.data (dict): Data configuration.device (torch.device): Device used for prediction.dataset (Dataset): Dataset used for prediction.vid_writer (dict): Dictionary of {save_path: video_writer, ...} writer for saving video output."""def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):"""Initializes the BasePredictor class.Args:cfg (str, optional): Path to a configuration file. Defaults to DEFAULT_CFG.overrides (dict, optional): Configuration overrides. Defaults to None."""self.args = get_cfg(cfg, overrides)self.save_dir = get_save_dir(self.args)if self.args.conf is None:self.args.conf = 0.25  # default conf=0.25self.done_warmup = Falseif self.args.show:self.args.show = check_imshow(warn=True)# Usable if setup is doneself.model = Noneself.data = self.args.data  # data_dictself.imgsz = Noneself.device = Noneself.dataset = Noneself.vid_writer = {}  # dict of {save_path: video_writer, ...}self.plotted_img = Noneself.source_type = Noneself.seen = 0self.windows = []self.batch = Noneself.results = Noneself.transforms = Noneself.callbacks = _callbacks or callbacks.get_default_callbacks()self.txt_path = Noneself._lock = threading.Lock()  # for automatic thread-safe inferencecallbacks.add_integration_callbacks(self)def preprocess(self, im):"""Prepares input image before inference.Args:im (torch.Tensor | List(np.ndarray)): BCHW for tensor, [(HWC) x B] for list."""not_tensor = not isinstance(im, torch.Tensor)if not_tensor:im = np.stack(self.pre_transform(im))im = im[..., ::-1].transpose((0, 3, 1, 2))  # BGR to RGB, BHWC to BCHW, (n, 3, h, w)im = np.ascontiguousarray(im)  # contiguousim = torch.from_numpy(im)im = im.to(self.device)im = im.half() if self.model.fp16 else im.float()  # uint8 to fp16/32if not_tensor:im /= 255  # 0 - 255 to 0.0 - 1.0return imdef inference(self, im, *args, **kwargs):"""Runs inference on a given image using the specified model and arguments."""visualize = (increment_path(self.save_dir / Path(self.batch[0][0]).stem, mkdir=True)if self.args.visualize and (not self.source_type.tensor)else False)return self.model(im, augment=self.args.augment, visualize=visualize, embed=self.args.embed, *args, **kwargs)def pre_transform(self, im):"""Pre-transform input image before inference.Args:im (List(np.ndarray)): (N, 3, h, w) for tensor, [(h, w, 3) x N] for list.Returns:(list): A list of transformed images."""same_shapes = len({x.shape for x in im}) == 1letterbox = LetterBox(self.imgsz, auto=same_shapes and self.model.pt, stride=self.model.stride)return [letterbox(image=x) for x in im]def postprocess(self, preds, img, orig_imgs):"""Post-processes predictions for an image and returns them."""return predsdef __call__(self, source=None, model=None, stream=False, *args, **kwargs):"""Performs inference on an image or stream."""self.stream = streamif stream:return self.stream_inference(source, model, *args, **kwargs)else:return list(self.stream_inference(source, model, *args, **kwargs))  # merge list of Result into onedef predict_cli(self, source=None, model=None):"""Method used for CLI prediction.It uses always generator as outputs as not required by CLI mode."""gen = self.stream_inference(source, model)for _ in gen:  # noqa, running CLI inference without accumulating any outputs (do not modify)passdef setup_source(self, source):"""Sets up source and inference mode."""self.imgsz = check_imgsz(self.args.imgsz, stride=self.model.stride, min_dim=2)  # check image sizeself.transforms = (getattr(self.model.model,"transforms",classify_transforms(self.imgsz[0], crop_fraction=self.args.crop_fraction),)if self.args.task == "classify"else None)self.dataset = load_inference_source(source=source,batch=self.args.batch,vid_stride=self.args.vid_stride,buffer=self.args.stream_buffer,)self.source_type = self.dataset.source_typeif not getattr(self, "stream", True) and (self.source_type.streamor self.source_type.screenshotor len(self.dataset) > 1000  # many imagesor any(getattr(self.dataset, "video_flag", [False]))):  # videosLOGGER.warning(STREAM_WARNING)self.vid_writer = {}@smart_inference_mode()def stream_inference(self, source=None, model=None, *args, **kwargs):"""Streams real-time inference on camera feed and saves results to file."""if self.args.verbose:LOGGER.info("")# Setup modelif not self.model:self.setup_model(model)with self._lock:  # for thread-safe inference# Setup source every time predict is calledself.setup_source(source if source is not None else self.args.source)# Check if save_dir/ label file existsif self.args.save or self.args.save_txt:(self.save_dir / "labels" if self.args.save_txt else self.save_dir).mkdir(parents=True, exist_ok=True)# Warmup modelif not self.done_warmup:self.model.warmup(imgsz=(1 if self.model.pt or self.model.triton else self.dataset.bs, 3, *self.imgsz))self.done_warmup = Trueself.seen, self.windows, self.batch = 0, [], Noneprofilers = (ops.Profile(device=self.device),ops.Profile(device=self.device),ops.Profile(device=self.device),)self.run_callbacks("on_predict_start")for self.batch in self.dataset:self.run_callbacks("on_predict_batch_start")paths, im0s, s = self.batch# Preprocesswith profilers[0]:im = self.preprocess(im0s)# Inferencewith profilers[1]:preds = self.inference(im, *args, **kwargs)if self.args.embed:yield from [preds] if isinstance(preds, torch.Tensor) else preds  # yield embedding tensorscontinue# Postprocesswith profilers[2]:self.results = self.postprocess(preds, im, im0s)self.run_callbacks("on_predict_postprocess_end")# Visualize, save, write resultsn = len(im0s)for i in range(n):self.seen += 1self.results[i].speed = {"preprocess": profilers[0].dt * 1e3 / n,"inference": profilers[1].dt * 1e3 / n,"postprocess": profilers[2].dt * 1e3 / n,}if self.args.verbose or self.args.save or self.args.save_txt or self.args.show:s[i] += self.write_results(i, Path(paths[i]), im, s)# Print batch resultsif self.args.verbose:LOGGER.info("\n".join(s))self.run_callbacks("on_predict_batch_end")yield from self.results# Release assetsfor v in self.vid_writer.values():if isinstance(v, cv2.VideoWriter):v.release()# Print final resultsif self.args.verbose and self.seen:t = tuple(x.t / self.seen * 1e3 for x in profilers)  # speeds per imageLOGGER.info(f"Speed: %.1fms preprocess, %.1fms inference, %.1fms postprocess per image at shape "f"{(min(self.args.batch, self.seen), 3, *im.shape[2:])}" % t)if self.args.save or self.args.save_txt or self.args.save_crop:nl = len(list(self.save_dir.glob("labels/*.txt")))  # number of labelss = f"\n{nl} label{'s' * (nl > 1)} saved to {self.save_dir / 'labels'}" if self.args.save_txt else ""LOGGER.info(f"Results saved to {colorstr('bold', self.save_dir)}{s}")self.run_callbacks("on_predict_end")def setup_model(self, model, verbose=True):"""Initialize YOLO model with given parameters and set it to evaluation mode."""self.model = AutoBackend(weights=model or self.args.model,device=select_device(self.args.device, verbose=verbose),dnn=self.args.dnn,data=self.args.data,fp16=self.args.half,batch=self.args.batch,fuse=True,verbose=verbose,)self.device = self.model.device  # update deviceself.args.half = self.model.fp16  # update halfself.model.eval()def write_results(self, i, p, im, s):"""Write inference results to a file or directory."""string = ""  # print stringif len(im.shape) == 3:im = im[None]  # expand for batch dimif self.source_type.stream or self.source_type.from_img or self.source_type.tensor:  # batch_size >= 1string += f"{i}: "frame = self.dataset.countelse:match = re.search(r"frame (\d+)/", s[i])frame = int(match.group(1)) if match else None  # 0 if frame undeterminedself.txt_path = self.save_dir / "labels" / (p.stem + ("" if self.dataset.mode == "image" else f"_{frame}"))string += "%gx%g " % im.shape[2:]result = self.results[i]result.save_dir = self.save_dir.__str__()  # used in other locationsstring += result.verbose() + f"{result.speed['inference']:.1f}ms"# Add predictions to imageif self.args.save or self.args.show:self.plotted_img = result.plot(line_width=self.args.line_width,boxes=self.args.show_boxes,conf=self.args.show_conf,labels=self.args.show_labels,im_gpu=None if self.args.retina_masks else im[i],)# Save resultsif self.args.save_txt:result.save_txt(f"{self.txt_path}.txt", save_conf=self.args.save_conf)if self.args.save_crop:result.save_crop(save_dir=self.save_dir / "crops", file_name=self.txt_path.stem)if self.args.show:self.show(str(p))if self.args.save:self.save_predicted_images(str(self.save_dir / p.name), frame)return stringdef save_predicted_images(self, save_path="", frame=0):"""Save video predictions as mp4 at specified path."""im = self.plotted_img# Save videos and streamsif self.dataset.mode in {"stream", "video"}:fps = self.dataset.fps if self.dataset.mode == "video" else 30frames_path = f'{save_path.split(".", 1)[0]}_frames/'if save_path not in self.vid_writer:  # new videoif self.args.save_frames:Path(frames_path).mkdir(parents=True, exist_ok=True)# Always save as MP4 regardless of OSsuffix, fourcc = (".mp4", "avc1")self.vid_writer[save_path] = cv2.VideoWriter(filename=str(Path(save_path).with_suffix(suffix)),fourcc=cv2.VideoWriter_fourcc(*fourcc),fps=fps,  # integer required, floats produce error in MP4 codecframeSize=(im.shape[1], im.shape[0]),  # (width, height))# Save videoself.vid_writer[save_path].write(im)if self.args.save_frames:cv2.imwrite(f"{frames_path}{frame}.jpg", im)# Save imageselse:cv2.imwrite(save_path, im)def show(self, p=""):"""Display an image in a window using OpenCV imshow()."""im = self.plotted_imgif platform.system() == "Linux" and p not in self.windows:self.windows.append(p)cv2.namedWindow(p, cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)cv2.resizeWindow(p, im.shape[1], im.shape[0])  # (width, height)cv2.imshow(p, im)cv2.waitKey(300 if self.dataset.mode == "image" else 1)  # 1 milliseconddef run_callbacks(self, event: str):"""Runs all registered callbacks for a specific event."""for callback in self.callbacks.get(event, []):callback(self)def add_callback(self, event: str, func):"""Add callback."""self.callbacks[event].append(func)

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/15354.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/15354.shtml
英文地址,請注明出處:http://en.pswp.cn/web/15354.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Android開發-Android開發中的TCP與UDP通信策略的實現

Android 開發中的 TCP 與 UDP 通信策略的實現 1. 前言2. 準備工作3. Kotlin 中 TCP 通信實現客戶端代碼示例:服務器代碼示例: 4. Kotlin 中 UDP 通信實現客戶端代碼示例:服務器代碼示例: 5. TCP 與 UDP 應用場景分析TCP 實現可靠傳…

搭建訪問阿里云百煉大模型環境

最近這波大降價,還有限時免費,還不趕快試試在線大模型?下面整理訪問百煉平臺的千問模型方法。 創建RAM子賬號并授權 創建RAM子賬號 1. “訪問控制RAM”入口(控制臺URL) 然后點擊進入“RAM管理控制臺” 2. 添加用戶 …

vue 區分多環境打包

需求:區分不同的環境(測試、正式環境),接口文檔地址不同; 配置步驟: 1、在根目錄下面新建 .env.xxx 文件(xxx 根據環境不同配置) 文件中一定要配置的參數項為:NODE_ENV…

【Python搞定車載自動化測試】——Python實現CAN總線Bootloader刷寫(含Python源碼)

系列文章目錄 【Python搞定車載自動化測試】系列文章目錄匯總 文章目錄 系列文章目錄💯💯💯 前言💯💯💯一、環境搭建1.軟件環境2.硬件環境 二、目錄結構三、源碼展示1.診斷基礎函數方法2.診斷業務函數方法…

python 火焰檢測

在日常生活,總是離不開火,有時候我們需要預防火災發生,但是我們又不可能一直盯著,這時候我們就需要一款程序幫我們盯著,一旦發生火災從而告知我們,今天就帶大家編寫這么一款應用。 安裝需要的庫 pip install opencv-python 代碼實現 import cv2 # Library for…

qmt量化教程4----訂閱全推數據

文章鏈接 qmt量化教程4----訂閱全推數據 (qq.com) 上次寫了訂閱單股數據的教程 量化教程3---miniqmt當作第三方庫設置,提供源代碼 全推就主動推送,當行情有變化就會觸發回調函數,推送實時數據,可以理解為數據驅動類型&#xff0…

mysql中使用 mysqldump 實現跨機器備份|數據同步

1.如果同步數據庫,必須先創建數據庫: mysqldump -h 192.168.1.10 --lock-tablesfalse -uroot -proot db_name | mysql -h127.0.0.1 -uroot -proot db_name2.過濾掉不想要的表(沒試過,但是試過轉為sql文件的) mysqldump -h 192.168.1.10 --…

vs2019 c++ 函數的返回值是對象的值傳遞時候,將調用對象的移動構造函數

以前倒沒有注意過這個問題。但編譯器這么處理也符合移動構造的語義。因為本來函數體內的變量也要離開作用域被銷毀回收了。測試如下: 謝謝

實現信號發生控制

1. 信號發生器的基本原理 信號發生器是一種能夠產生特定波形和頻率的電子設備,常用于模擬信號的產生和測試。 信號發生器的基本原理 信號發生器的工作原理基于不同的技術,但最常見的類型包括模擬信號發生器和數字信號發生器(DDS&#xff0…

[SCTF2019]babyre

打開看看還是有花指令 解除后首先pass1是解maze,好像又是三維的 x是25,也就是向下跳五層,注意是立體的 得到 passwd1: ddwwxxssxaxwwaasasyywwdd 接著往下看 有一個加密函數IDA逆向常用宏定義_lodword-CSDN博客 unsigned __int64 __fastca…

primeflex樣式庫筆記 Display相關的案例

回顧 寬度設置的基本總結 w-full:表示widtdh:100%;占滿父容器的寬度。 w-screen:表示占滿整個屏幕的寬度。 w-1到w-12,是按百分比劃分寬度,數字越大,占據的比例就越大。 w-1rem到w-30rem&…

Oracle的安裝以及一些相關問題

系列文章目錄 Oracle的安裝以及一些相關問題 文章目錄 系列文章目錄前言一、Oracle的安裝二、常用命令三、誤刪dbf四、PLSQL亂碼五、oracle更換數據庫字符集總結 前言 一段時間沒更新,主要最近一直在找工作,最終還是順著春招找到工作了,現在…

美信時代監控易:堆疊交換機的監控與配置管理策略

隨著企業數字化轉型的加速,網絡架構的複雜性日益提升,堆疊交換機作為高可靠性、靈活擴展性的解決方案,在網絡基礎設施中扮演著至關重要的角色。然而,如何確保堆疊交換機的穩定運行,實現高效監控與配置管理,…

剖析 OceanBase 應對高并發的技術策略

推薦一個AI網站,免費使用豆包AI模型,快去白嫖👉海鯨AI 在當今互聯網時代,高并發場景下的數據庫處理能力成為了許多應用的關鍵需求。為了滿足用戶對快速響應和高吞吐量的期望,數據庫系統需要采用一系列技術來優化并發性…

七大經典排序算法——冒泡排序

文章目錄 📑冒泡排序介紹🌤?代碼實現🌤?做個簡單的優化🌤?復雜度和穩定性分析??結語 📑冒泡排序介紹 冒泡排序是一種簡單但效率較低的排序算法。它重復地比較相鄰的兩個元素,如果順序不對則交換它們&…

C++ socket epoll IO多路復用

IO多路復用通常用于處理單進程高并發,在Linux中,一切皆文件,一個socket連接會對應一個文件描述符,在監聽多個文件描述符的狀態應用中epoll相對于select和poll效率更高 epoll本質是系統在內核維護了一顆紅黑樹,監聽的文…

Linux中bash腳本怎么表示一個字符串變量

Linux中bash腳本怎么表示一個字符串變量 在Bash腳本中,你可以使用單引號()或雙引號(")來表示一個字符串變量。以下是兩種方式的示例: 使用單引號(): my_variable…

flink 和 clipper搭配使用

Flink是一個用于流處理和批處理的開源框架,可以實時數據處理和分析。 Clipper 是一個用于機器學習模型服務化的開源框架,能夠輕松部署和管理機器學習模型,使模型可以通過統一的接口提供在線推理服務。 flink和clipper搭配使用: …

Leetcode | 5-21| 每日一題

2769. 找出最大的可達成數字 考點: 暴力 數學式子計算 思維 題解 通過式子推導: 第一想法是二分確定區間在區間內進行查找是否符合條件的, 本題最關鍵的便是 條件確定 , 第二種方法: 一般是通過數學公式推導的,這種題目我稱為數學式編程題 代碼 條件判斷式 class Solution { …

需求分析的任務

1 確定對系統的綜合要求 雖然功能需求是對軟件系統的一項基本需求,但卻并不是唯一的需求。通常對軟件系統有下述幾方面的綜合要求。 1.功能需求 這方面的需求指定系統必須提供的服務。通過需求分析應該劃分出系統必須完成的所有功能。 2.性能…