龙岩做网站哪家最好,百度邮箱注册申请免费注册,怎么打击对手网站排名,开发聊天软件成本一、YOLOv8环境搭建
这篇文章将跳过基础的深度学习环境的搭建#xff0c;如果没有完成的可以看我的这篇博客#xff1a;超详细||深度学习环境搭建记录cudaanacondapytorchpycharm-CSDN博客
1. 在github上下载源码#xff1a;
GitHub - ultralytics/ultralytics: NEW - YO…一、YOLOv8环境搭建
这篇文章将跳过基础的深度学习环境的搭建如果没有完成的可以看我的这篇博客超详细||深度学习环境搭建记录cudaanacondapytorchpycharm-CSDN博客
1. 在github上下载源码
GitHub - ultralytics/ultralytics: NEW - YOLOv8 in PyTorch ONNX OpenVINO CoreML TFLite
2. 安装ultralyticsYOLOv8改名为ultralytics
这里有两种方式安装ultralytics
直接使用CLI
pip install ultralytics使用requirements.txt安装这种方法是在上面下载的源码处安装方便对yolov8进行改进
cd ultralytics
pip install -r requirements.txt3. 安装wandb
pip install wandb
登录自己的wandb账号
wandb login
二、开始训练
1. 构建数据集
数据集要严格按照下面的目录格式image的格式为jpglabel的格式为txt对应的image和label的名字要一致
Dataset└─images└─train└─val└─labels└─train└─val
2. 创建一个dataset.yaml文件
更换自己的image train和image val的地址labels地址不用它会自动索引
将classes改为自己的类别从0开始
path: ../datasets/coco128 # dataset root dir
train: images/train2017 # train images (relative to path) 128 images
val: images/train2017 # val images (relative to path) 128 images
test: # test images (optional)# Classes
names:0: person1: bicycle2: car3: motorcycle4: airplane5: bus6: train7: truck8: boat
3. 新建一个train.py修改相关参数运行即可开始训练
from ultralytics import YOLOif __name__ __main__:# Load a modelmodel YOLO(r\ultralytics\detection\yolov8n\yolov8n.yaml) # 不使用预训练权重训练# model YOLO(ryolov8p.yaml).load(yolov8n.pt) # 使用预训练权重训练# Trainparameters ----------------------------------------------------------------------------------------------model.train(datar\ultralytics\detection\dataset\appledata.yaml,epochs 30 , # (int) number of epochs to train forpatience 50 , # (int) epochs to wait for no observable improvement for early stopping of trainingbatch 8 , # (int) number of images per batch (-1 for AutoBatch)imgsz 320 , # (int) size of input images as integer or w,hsave True , # (bool) save train checkpoints and predict resultssave_period -1, # (int) Save checkpoint every x epochs (disabled if 1)cache False , # (bool) True/ram, disk or False. Use cache for data loadingdevice 0 , # (int | str | list, optional) device to run on, i.e. cuda device0 or device0,1,2,3 or devicecpuworkers 16 , # (int) number of worker threads for data loading (per RANK if DDP)project result, # (str, optional) project namename yolov8n ,# (str, optional) experiment name, results saved to project/name directoryexist_ok False , # (bool) whether to overwrite existing experimentpretrained False , # (bool | str) whether to use a pretrained model (bool) or a model to load weights from (str)optimizer SGD, # (str) optimizer to use, choices[SGD, Adam, Adamax, AdamW, NAdam, RAdam, RMSProp, auto]verbose True ,# (bool) whether to print verbose outputseed 0 , # (int) random seed for reproducibilitydeterministic True , # (bool) whether to enable deterministic modesingle_cls True , # (bool) train multi-class data as single-classrect False ,# (bool) rectangular training if modetrain or rectangular validation if modevalcos_lr False , # (bool) use cosine learning rate schedulerclose_mosaic 0, # (int) disable mosaic augmentation for final epochsresume False , # (bool) resume training from last checkpointamp False, # (bool) Automatic Mixed Precision (AMP) training, choices[True, False], True runs AMP checkfraction 1.0 , # (float) dataset fraction to train on (default is 1.0, all images in train set)profile False, # (bool) profile ONNX and TensorRT speeds during training for loggers# Segmentationoverlap_mask True , # (bool) masks should overlap during training (segment train only)mask_ratio 4, # (int) mask downsample ratio (segment train only)# Classificationdropout 0.0, # (float) use dropout regularization (classify train only)# Hyperparameters ----------------------------------------------------------------------------------------------lr00.01, # (float) initial learning rate (i.e. SGD1E-2, Adam1E-3)lrf0.01, # (float) final learning rate (lr0 * lrf)momentum0.937, # (float) SGD momentum/Adam beta1weight_decay0.0005, # (float) optimizer weight decay 5e-4warmup_epochs3.0, # (float) warmup epochs (fractions ok)warmup_momentum0.8, # (float) warmup initial momentumwarmup_bias_lr0.1, # (float) warmup initial bias lrbox7.5, # (float) box loss gaincls0.5, # (float) cls loss gain (scale with pixels)dfl1.5, # (float) dfl loss gainpose12.0, # (float) pose loss gainkobj1.0, # (float) keypoint obj loss gainlabel_smoothing0.0, # (float) label smoothing (fraction)nbs64, # (int) nominal batch sizehsv_h0.015, # (float) image HSV-Hue augmentation (fraction)hsv_s0.7, # (float) image HSV-Saturation augmentation (fraction)hsv_v0.4, # (float) image HSV-Value augmentation (fraction)degrees0.0, # (float) image rotation (/- deg)translate0.1, # (float) image translation (/- fraction)scale0.5, # (float) image scale (/- gain)shear0.0, # (float) image shear (/- deg)perspective0.0, # (float) image perspective (/- fraction), range 0-0.001flipud0.0, # (float) image flip up-down (probability)fliplr0.5, # (float) image flip left-right (probability)mosaic1.0, # (float) image mosaic (probability)mixup0.0, # (float) image mixup (probability)copy_paste0.0, # (float) segment copy-paste (probability))
三、测试与验证
1. 新建一个test.py, 这个可以打印网路信息参数量以及FLOPs还有每一层网络的信息
from ultralytics import YOLOif __name__ __main__:# Load a modelmodel YOLO(r\ultralytics\detection\yolov8n\yolov8n.yaml) # build a new model from YAMLmodel.info()
2. 新建一个val.py这个可以打印模型在验证集上的结果如mAP推理速度等
from ultralytics import YOLOif __name__ __main__:# Load a modelmodel YOLO(r\ultralytics\detection\yolov8n\result\yolov8n4\weights\best.pt) # build a new model from YAML# Validate the modelmodel.val(valTrue, # (bool) validate/test during trainingdatar\ultralytics\detection\dataset\appledata.yaml,splitval, # (str) dataset split to use for validation, i.e. val, test or trainbatch1, # 测试速度时一般设置为 1 设置越大速度越快。 (int) number of images per batch (-1 for AutoBatch)imgsz320, # (int) size of input images as integer or w,hdevice0, # (int | str | list, optional) device to run on, i.e. cuda device0 or device0,1,2,3 or devicecpuworkers8, # (int) number of worker threads for data loading (per RANK if DDP)save_jsonFalse, # (bool) save results to JSON filesave_hybridFalse, # (bool) save hybrid version of labels (labels additional predictions)conf0.001, # (float, optional) object confidence threshold for detection (default 0.25 predict, 0.001 val)iou0.7, # (float) intersection over union (IoU) threshold for NMSprojectval, # (str, optional) project namename, # (str, optional) experiment name, results saved to project/name directorymax_det300, # (int) maximum number of detections per imagehalfTrue, # (bool) use half precision (FP16)dnnFalse, # (bool) use OpenCV DNN for ONNX inferenceplotsTrue, # (bool) save plots during train/val)
3. 新建一个predict.py这个可以根据训练好的权重文件进行推理权重文件格式支持ptonnx等支持图片视频摄像头等进行推理
from ultralytics import YOLOif __name__ __main__:# Load a modelmodel YOLO(r\deploy\yolov8n.pt) # pretrained YOLOv8n modelmodel.predict(sourcer\deploy\output_video.mp4,saveFalse, # save predict resultsimgsz320, # (int) size of input images as integer or w,hconf0.25, # object confidence threshold for detection (default 0.25 predict, 0.001 val)iou0.7, # # intersection over union (IoU) threshold for NMSshowTrue, # show results if possibleproject, # (str, optional) project namename, # (str, optional) experiment name, results saved to project/name directorysave_txtFalse, # save results as .txt filesave_confTrue, # save results with confidence scoressave_cropFalse, # save cropped images with resultsshow_labelsTrue, # show object labels in plotsshow_confTrue, # show object confidence scores in plotsvid_stride1, # video frame-rate strideline_width1, # bounding box thickness (pixels)visualizeFalse, # visualize model featuresaugmentFalse, # apply image augmentation to prediction sourcesagnostic_nmsFalse, # class-agnostic NMSretina_masksFalse, # use high-resolution segmentation masksboxesTrue, # Show boxes in segmentation predictions)
四、onnx模型部署
1. 新建一个export.py将pt文件转化为onnx文件
from ultralytics import YOLO# Load a model
model YOLO(/ultralytics/weight file/yolov8n.pt) # load a custom trained model# Export the model
model.export(formatonnx)
2. 将onnx文件添加到之前提到的predict.py中进行推理。
3. 如果想在推理的视频中添加FPS信息请把ultralytics/engine/predictor.py替换为下面的代码。
# Ultralytics YOLO , AGPL-3.0 licenseRun prediction on images, videos, directories, globs, YouTube, webcam, streams, etc.Usage - sources:$ yolo modepredict modelyolov8n.pt source0 # webcamimg.jpg # imagevid.mp4 # videoscreen # screenshotpath/ # directorylist.txt # list of imageslist.streams # list of streamspath/*.jpg # globhttps://youtu.be/Zgi9g1ksQHc # YouTubertsp://example.com/media.mp4 # RTSP, RTMP, HTTP streamUsage - formats:$ yolo modepredict modelyolov8n.pt # PyTorchyolov8n.torchscript # TorchScriptyolov8n.onnx # ONNX Runtime or OpenCV DNN with dnnTrueyolov8n_openvino_model # OpenVINOyolov8n.engine # TensorRTyolov8n.mlmodel # CoreML (macOS-only)yolov8n_saved_model # TensorFlow SavedModelyolov8n.pb # TensorFlow GraphDefyolov8n.tflite # TensorFlow Liteyolov8n_edgetpu.tflite # TensorFlow Edge TPUyolov8n_paddle_model # PaddlePaddleimport platform
from pathlib import Pathimport cv2
import numpy as np
import torchfrom ultralytics.cfg import get_cfg
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, SETTINGS, 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 ⚠️ stream/video/webcam/dir predict source will accumulate results in RAM unless streamTrue is passed,causing potential out-of-memory errors for large sources or long-running streams/videos.Usage:results model(source..., streamTrue) # 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:BasePredictorA 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_path (str): Path to video file.vid_writer (cv2.VideoWriter): Video writer for saving video output.data_path (str): Path to data.def __init__(self, cfgDEFAULT_CFG, overridesNone, _callbacksNone):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 self.get_save_dir()if self.args.conf is None:self.args.conf 0.25 # default conf0.25self.done_warmup Falseif self.args.show:self.args.show check_imshow(warnTrue)# Usable if setup is doneself.model Noneself.data self.args.data # data_dictself.imgsz Noneself.device Noneself.dataset Noneself.vid_path, self.vid_writer None, Noneself.plotted_img Noneself.data_path Noneself.source_type Noneself.batch Noneself.results Noneself.transforms Noneself.callbacks _callbacks or callbacks.get_default_callbacks()self.txt_path Nonecallbacks.add_integration_callbacks(self)def get_save_dir(self):project self.args.project or Path(SETTINGS[runs_dir]) / self.args.taskname self.args.name or f{self.args.mode}return increment_path(Path(project) / name, exist_okself.args.exist_ok)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)img im.to(self.device)img img.half() if self.model.fp16 else img.float() # uint8 to fp16/32if not_tensor:img / 255 # 0 - 255 to 0.0 - 1.0return imgdef inference(self, im, *args, **kwargs):visualize increment_path(self.save_dir / Path(self.batch[0][0]).stem,mkdirTrue) if self.args.visualize and (not self.source_type.tensor) else Falsereturn self.model(im, augmentself.args.augment, visualizevisualize)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.Return: A list of transformed imgs.same_shapes all(x.shape im[0].shape for x in im)auto same_shapes and self.model.ptreturn [LetterBox(self.imgsz, autoauto, strideself.model.stride)(imagex) for x in im]def write_results(self, idx, results, batch):Write inference results to a file or directory.p, im, _ batchlog_string if len(im.shape) 3:im im[None] # expand for batch dimif self.source_type.webcam or self.source_type.from_img or self.source_type.tensor: # batch_size 1log_string f{idx}: frame self.dataset.countelse:frame getattr(self.dataset, frame, 0)self.data_path pself.txt_path str(self.save_dir / labels / p.stem) ( if self.dataset.mode image else f_{frame})log_string %gx%g % im.shape[2:] # print stringresult results[idx]log_string result.verbose()if self.args.save or self.args.show: # Add bbox to imageplot_args {line_width: self.args.line_width,boxes: self.args.boxes,conf: self.args.show_conf,labels: self.args.show_labels}if not self.args.retina_masks:plot_args[im_gpu] im[idx]self.plotted_img result.plot(**plot_args)# Writeif self.args.save_txt:result.save_txt(f{self.txt_path}.txt, save_confself.args.save_conf)if self.args.save_crop:result.save_crop(save_dirself.save_dir / crops,file_nameself.data_path.stem ( if self.dataset.mode image else f_{frame}))return log_stringdef postprocess(self, preds, img, orig_imgs):Post-processes predictions for an image and returns them.return predsdef __call__(self, sourceNone, modelNone, streamFalse, *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, sourceNone, modelNone):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: # 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, strideself.model.stride, min_dim2) # check image sizeself.transforms getattr(self.model.model, transforms, classify_transforms(self.imgsz[0])) if self.args.task classify else Noneself.dataset load_inference_source(sourcesource, imgszself.imgsz, vid_strideself.args.vid_stride)self.source_type self.dataset.source_typeif not getattr(self, stream, True) and (self.dataset.mode stream or # streamslen(self.dataset) 1000 or # imagesany(getattr(self.dataset, video_flag, [False]))): # videosLOGGER.warning(STREAM_WARNING)self.vid_path, self.vid_writer [None] * self.dataset.bs, [None] * self.dataset.bssmart_inference_mode()def stream_inference(self, sourceNone, modelNone, *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)# 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(parentsTrue, exist_okTrue)# 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, self.profilers 0, [], None, (ops.Profile(), ops.Profile(), ops.Profile())self.run_callbacks(on_predict_start)for batch in self.dataset:self.run_callbacks(on_predict_batch_start)self.batch batchpath, im0s, vid_cap, s batch# Preprocesswith self.profilers[0]:im self.preprocess(im0s)# Inferencewith self.profilers[1]:preds self.inference(im, *args, **kwargs)# Postprocesswith self.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: self.profilers[0].dt * 1E3 / n,inference: self.profilers[1].dt * 1E3 / n,postprocess: self.profilers[2].dt * 1E3 / n}p, im0 path[i], None if self.source_type.tensor else im0s[i].copy()p Path(p)if self.args.verbose or self.args.save or self.args.save_txt or self.args.show:s self.write_results(i, self.results, (p, im, im0))if self.args.save or self.args.save_txt:self.results[i].save_dir self.save_dir.__str__()if self.args.show and self.plotted_img is not None:self.show(p)if self.args.save and self.plotted_img is not None:self.save_preds(vid_cap, i, str(self.save_dir / p.name))self.run_callbacks(on_predict_batch_end)yield from self.results# Print time (inference-not only)if self.args.verbose:LOGGER.info(f{s}{(self.profilers[0].dtself.profilers[1].dtself.profilers[2].dt) * 1E3:.2f}ms)# Release assetsif isinstance(self.vid_writer[-1], cv2.VideoWriter):self.vid_writer[-1].release() # release final video writer# Print resultsif self.args.verbose and self.seen:t tuple(x.t / self.seen * 1E3 for x in self.profilers) # speeds per imageLOGGER.info(fSpeed: %.2fms preprocess, %.2fms inference, %.2fms postprocess per image at shape f{(1, 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(fResults saved to {colorstr(bold, self.save_dir)}{s})self.run_callbacks(on_predict_end)def setup_model(self, model, verboseTrue):Initialize YOLO model with given parameters and set it to evaluation mode.self.model AutoBackend(model or self.args.model,deviceselect_device(self.args.device, verboseverbose),dnnself.args.dnn,dataself.args.data,fp16self.args.half,fuseTrue,verboseverbose)self.device self.model.device # update deviceself.args.half self.model.fp16 # update halfself.model.eval()def show(self, p):Display an image in a window using OpenCV imshow().im0 self.plotted_img#--------------------后添加-----------------------------str_FPS FPS: %.2f % (1. / (self.profilers[0].dt self.profilers[1].dt self.profilers[2].dt))cv2.putText(im0, str_FPS, (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 3)# --------------------后添加-----------------------------if platform.system() Linux and p not in self.windows:self.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(500 if self.batch[3].startswith(image) else 1) # 1 milliseconddef save_preds(self, vid_cap, idx, save_path):Save video predictions as mp4 at specified path.im0 self.plotted_img# Save imgsif self.dataset.mode image:cv2.imwrite(save_path, im0)else: # video or streamif self.vid_path[idx] ! save_path: # new videoself.vid_path[idx] save_pathif isinstance(self.vid_writer[idx], cv2.VideoWriter):self.vid_writer[idx].release() # release previous video writerif vid_cap: # videofps int(vid_cap.get(cv2.CAP_PROP_FPS)) # integer required, floats produce error in MP4 codecw 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]suffix .mp4 if MACOS else .avi if WINDOWS else .avifourcc avc1 if MACOS else WMV2 if WINDOWS else MJPGsave_path str(Path(save_path).with_suffix(suffix))self.vid_writer[idx] cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (w, h))self.vid_writer[idx].write(im0)def 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 callbackself.callbacks[event].append(func)