yolov8使用,以及进行检测代码编写

1、环境安装
在github上下载ultralytics框架源码,安装库参照requestment.txt,yolov8对python版本有一定要求。如果使用pip install ultralytics==8.0.0,那么这个库会存放在环境/site_packages里面,更改源码时候,到该路径下更改。

2、数据处理
数据处理的方式和其它版本yolo一样,生成标签的txt文件,在ultralytics/cfg/datasets里面,设定自己的数据集yaml文件。
data.yaml

第一种写法
path: D:\dataset\Test  # dataset root dir
train: images/train  # train images (relative to 'path')
val: images/val  # val images (relative to 'path')
test:  # test images (optional)
# Classes
names:
  0: C1
  1: C2

第二种写法
train: images/train.txt  # train images (relative to 'path')
val: images/val.txt  # val images (relative to 'path')
test: images/test.txt# test images (optional)
nc:1   #num of class
# Classes
names:["c1","c2"]

3、模型训练
训练前:
1、配置ultralytics/models/v8/yolov8.yaml中的类别数目
2、配置ultralytics/cfg/default.yaml中的任务,以及其它配置信息
官方训练、验证、测试、模型导出代码:

yolo task=detect    mode=train    model=yolov8n.pt        args...
          classify       predict        yolov8n-cls.yaml  args...
          segment        val            yolov8n-seg.yaml  args...
                         export         yolov8n.pt        format=onnx  args...
              
              
训练:yolo task=detect mode=train model=weights/yolov8n.pt data=data/mydata.yaml batch=16 epochs=50 imgsz=640 workers=16 device=0
验证:yolo task=detect mode=val model=runs/detect/train3/weights/best.pt data=data/mydata.yaml device=0
预测:yolo task=detect mode=predict model=weights/best.pt source=data/test_images save=True

第二种写法:

# train model
from ultralytics import YOLO
# Load a model 三选一
model = YOLO('yolov8n.yaml')  # build a new model from YAML 配置好模型和训练数据yaml文件信息
model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)
model = YOLO('yolov8n.yaml').load('yolov8n.pt')  # build from YAML and transfer weights
# Train the model
model.train(data='coco128.yaml', epochs=100, imgsz=640)

#val model
from ultralytics import YOLO
# Load a model  二选一
model = YOLO('yolov8n.pt')  # load an official model
model = YOLO('path/to/best.pt')  # load a custom model
# Validate the model
metrics = model.val()  # no arguments needed, dataset and settings remembered
metrics.box.map    # map50-95
metrics.box.map50  # map50
metrics.box.map75  # map75
metrics.box.maps   # a list contains map50-95 of each category

#predict 
from ultralytics import YOLO
import cv2
import os,datetime
os.environ['KMP_DUPLICATE_LIB_OK']='True'    #如果训练时候报Initializing libiomp5md.dll, but found libiomp5md.dll already initialized错误,加上这句
model = YOLO('best.pt') #已经训练好的模型
# Define path to the image file
source = 'img or video' #待预测的数据保存路径
# Run inference on the source
results = model(source, mode='predict', save=True)  # list of Results objects

#export model
from ultralytics import YOLO
# Load a model
model = YOLO('yolov8n.pt')  # load an official model
model = YOLO('path/to/best.pt')  # load a custom trained
# Export the model
model.export(format='onnx')

自己做的检测代码,实现boxes的显示,可根据需求进行修改:

from ultralytics import YOLO
import cv2
import os,datetime,time
os.environ['KMP_DUPLICATE_LIB_OK']='True'
path_pt="x.pt"
model=YOLO(path_pt)
img_dir="./img"
image_files=[os.path.join(img_dir,file) for file in os.listdir(img_dir) if file.endswith((".jpg","png","jpeg","mp4"))]
for img_file in image_files:
	mat_img=cv2.imread(img_file)
	res=model(img_file,save=True,conf=0.4,iou=0.2,imgsz=640,device="cuda:0")  #use cuda
	res_coord=[]
	outputs=res[0]
	boxes=res[0].boxes  # include xyxy xywh xywhn
	boxes=boxes.xyxy
	boxes=boxes.cpu()  #cuda data transfer cpu data
	boxes=boxes.tolist()
	count=0
	for box in boxes:
		count+=1
		width=int(box[2])-int(box[0])
		height=int(box[3])-int(box[1])
		x_center=(int(box[2])+int(box[0]))//2
		y_center=(int(box[3])+int(box[1]))//2
		res_coord.append((x_center,y_center))
		img=cv2.circle(mat_img,(x_center,y_center),5,(0,0,255),-1)
	date_time=datetime.datetime.strftime(datetime.datetime.now(),"%Y%m%d%H%M%S")
	path=".res/"+date_time+".jpg"
	cv2.imwrite(path,img)
	res.coord.append(path)  # include box(center) and the result path of img
	
	


  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 你好,以下是 YOLOv8 实时检测推理 Python 代码的示例: ``` import cv2 import numpy as np # Load YOLOv8 model net = cv2.dnn.readNet("yolov8.weights", "yolov8.cfg") # Load input image img = cv2.imread("input.jpg") # Resize image to input size of the model img = cv2.resize(img, (416, 416)) # Create a blob from the image blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False) # Feed the blob to the model net.setInput(blob) # Get the output layer names of the model layer_names = net.getLayerNames() layer_names = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] # Perform forward pass to get detections detections = net.forward(layer_names) # Get the detections from the output detections = np.squeeze(detections) # Get the class IDs and confidences for each detection class_ids, confidences, boxes = [], [], [] for detection in detections: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: center_x, center_y, w, h = (detection[0:4] * np.array([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])).astype('int') x, y = int(center_x - w / 2), int(center_y - h / 2) boxes.append([x, y, int(w), int(h)]) confidences.append(float(confidence)) class_ids.append(class_id) # Perform non-maximum suppression to get the final detections indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) # Draw the detections on the image for i in indices: i = i[0] box = boxes[i] x, y, w, h = box[0], box[1], box[2], box[3] cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # Display the image cv2.imshow("detections", img) cv2.waitKey() cv2.destroyAllWindows() ``` 希望这对你有帮助。 ### 回答2: YOLOv8是一个实时目标检测算法,它是YOLO(You Only Look Once)系列的最新版本。下面是一个示例的Python代码,用于进行YOLOv8实时检测推理: ```python import cv2 import torch from torchvision import transforms from yolov5.models.experimental import attempt_load from yolov5.utils.general import non_max_suppression, scale_coords from yolov5.utils.torch_utils import select_device # 加载模型 weights = 'yolov5s.pt' # 替换为YOLOv8的权重文件路径 device = select_device('') model = attempt_load(weights, map_location=device) stride = int(model.stride.max()) # 计算特征提取步长 # 准备图像 img_size = 640 # 设置输入图像的大小 transform = transforms.Compose([ transforms.ToPILImage(), transforms.Resize(img_size), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # 设置阈值和类别 conf_thres = 0.3 # 检测置信度阈值 iou_thres = 0.5 # 非最大值抑制的IOU阈值 names = model.module.names if hasattr(model, 'module') else model.names # 开启实时摄像头 cap = cv2.VideoCapture(0) while cap.isOpened(): success, frame = cap.read() if not success: break # 图像预处理 img = transform(frame).unsqueeze(0).to(device) img /= 255.0 # 像素值归一化到[0, 1] if img.ndimension() == 3: img = img.unsqueeze(0) # 检测推理 pred = model(img)[0] pred = non_max_suppression(pred, conf_thres, iou_thres)[0] pred = scale_coords(img_size, pred[:, :4], frame.shape).round() # 绘制边界框和标签 for x1, y1, x2, y2, conf, cls in pred: cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2) cv2.putText(frame, f'{names[int(cls)]} {conf:.2f}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2) # 展示结果 cv2.imshow('YOLOv8 - Real-time Object Detection', frame) if cv2.waitKey(1) == 27: break # 释放资源 cap.release() cv2.destroyAllWindows() ``` 这段代码使用了OpenCV和PyTorch,首先加载YOLOv8模型的权重文件,然后设置输入图像的大小和预处理方式。接下来,通过调用摄像头获取实时图像,并将其进行预处理。然后通过模型进行推理,获得目标检测结果。最后,将检测结果绘制在原始图像上,并实时展示在窗口中。用户可以按下ESC键停止检测。 注意,这段代码仅提供了一个基本的框架,可能需要根据具体情况进行适当的调整和优化。 ### 回答3: YOLOv8是一种实时目标检测算法,它在Python中有相应的推理代码YOLOv8的推理代码可以用来将模型训练所得的权重文件加载到内存中,并使用这些权重来进行实时目标检测。 在Python中,我们首先需要安装相应的库和依赖项,如PyTorch、OpenCV等。安装完成后,我们可以编写推理代码。 推理代码的第一步是加载YOLOv8的模型权重文件。通过调用PyTorch提供的相关函数,我们可以将预训练好的权重文件加载到内存中。 接下来,我们需要定义模型的输入和输出。对于YOLOv8,输入是一张图像,输出是检测到的目标的边界框和类别信息。 在推理过程中,我们将输入图像传递给模型,模型将返回一组预测框。然后,我们可以根据预测框的置信度和类别信息进行筛选和筛除,以得到最终的检测结果。 为了实现实时检测,我们可以将推理过程放入一个循环中。在每一次循环中,我们读取一帧图像,并将其传递给模型进行检测。然后,我们可以将检测结果可视化或保存下来。 需要注意的是,YOLOv8的推理代码需要在具备足够计算资源的机器上运行,因为它需要高性能的GPU来实现实时检测。 总之,YOLOv8的实时检测推理Python代码包括加载权重文件、定义输入输出、进行推理过程,以及在循环中实现实时检测。这些代码可以帮助我们实现基于YOLOv8的目标检测应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值