【深度学习】yolov8 seg实例分割训练,交通灯

一、类别定义

类别0:

在这里插入图片描述

类别1:

在这里插入图片描述
类别2:

在这里插入图片描述

类别3:

在这里插入图片描述

类别4:

在这里插入图片描述
类别5:
在这里插入图片描述

类别6:

在这里插入图片描述

类别7:

在这里插入图片描述

二、标注后再清洗数据

删除没有标签json的图:

import os
import json

# Define the source directory containing the images and JSON files
src = r"G:\honglvdeng\images\xuanze_copy"

# List all files in the source directory
files = os.listdir(src)

# Separate image files and JSON files
image_files = [f for f in files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
json_files = [f for f in files if f.lower().endswith('.json')]

# Create a set of base names of JSON files (without extension)
json_base_names = set(os.path.splitext(f)[0] for f in json_files)

# Iterate over the image files
for image_file in image_files:
    # Get the base name of the image file (without extension)
    base_name = os.path.splitext(image_file)[0]

    # Check if the corresponding JSON file exists
    if base_name not in json_base_names:
        # If not, delete the image file
        image_path = os.path.join(src, image_file)
        os.remove(image_path)
        print(f"Deleted image without annotation: {image_path}")

将圆形标签json转为txt yolo seg 多边形标签:

import os
import json
import math


def circle_to_polygon(center, radius, num_points=40):
    """Convert a circle to a polygon with a given number of points."""
    points = []
    for i in range(num_points):
        angle = 2 * math.pi * i / num_points
        x = center[0] + radius * math.cos(angle)
        y = center[1] + radius * math.sin(angle)
        points.append((x, y))
    return points


def convert_json_to_yolov8_format(json_file_path, output_dir):
    """Convert a JSON file to YOLOv8 segmentation format."""
    with open(json_file_path, 'r') as f:
        data = json.load(f)

    shapes = data.get('shapes', [])
    image_path = data.get('imagePath', '')
    image_height = data.get('imageHeight', 0)
    image_width = data.get('imageWidth', 0)

    yolov8_data = []

    for shape in shapes:
        if shape['shape_type'] == 'circle':
            center = shape['points'][0]
            edge = shape['points'][1]
            radius = math.sqrt((center[0] - edge[0]) ** 2 + (center[1] - edge[1]) ** 2)
            polygon_points = circle_to_polygon(center, radius)
            normalized_polygon_points = [(x / image_width, y / image_height) for x, y in polygon_points]
            yolov8_data.append({
                "label": shape['label'],
                "points": normalized_polygon_points
            })

    output_file_path = os.path.join(output_dir, os.path.splitext(os.path.basename(json_file_path))[0] + '.txt')

    with open(output_file_path, 'w') as f:
        for item in yolov8_data:
            label = item['label']
            points = ' '.join([f"{round(x, 6)} {round(y, 6)}" for x, y in item['points']])
            f.write(f"{label} {points}\n")


def process_directory(src):
    """Process all JSON files in the given directory."""
    for file_name in os.listdir(src):
        if file_name.endswith('.json'):
            json_file_path = os.path.join(src, file_name)
            convert_json_to_yolov8_format(json_file_path, src)


# Define the source directory containing the images and JSON files
src = r"G:\honglvdeng\images\xuanze_copy"
process_directory(src)

转移到新的数据集文件夹:

import os
import json
import math

import os
import json
import shutil

# Define the source directory containing the images and JSON files
src = r"G:\honglvdeng\images\xuanze_copy"
dst = r"G:\honglvdeng\images\xuanze_copy_yolo_seg_datasets"
os.makedirs(dst, exist_ok=True)

files = os.listdir(src)
image_files = [f for f in files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
img_dst = os.path.join(dst, "images")
os.makedirs(img_dst, exist_ok=True)
for image_file in image_files:
    image_path = os.path.join(src, image_file)
    shutil.copy(image_path, img_dst)

json_files = [f for f in files if f.lower().endswith('.txt')]
json_dst = os.path.join(dst, "labels")
os.makedirs(json_dst, exist_ok=True)
for json_file in json_files:
    json_path = os.path.join(src, json_file)
    shutil.copy(json_path, json_dst)


三、训练yolov8 seg

train.py

from ultralytics import YOLO

# Load a model
model = YOLO("yolov8n-seg.pt")  # load a pretrained model (recommended for training)

# Train the model with 2 GPUs
results = model.train(data="hld-seg.yaml", epochs=100, imgsz=640, device=[0, 1, 2, 3], batch=16)

训练开启:

python -m torch.distributed.run --nproc_per_node 4 x05_train.py

训练结束:

在这里插入图片描述

四、部署

对摄像头实时画面进行分割:

在这里插入图片描述

五、代码资料

下载所有资料:

链接:https://pan.baidu.com/s/1NtLgkmRfoCCqDD5axi-HRw?pwd=78xw 
提取码:78xw 

在这里插入图片描述
在这里插入图片描述

帮助:

https://docs.qq.com/sheet/DUEdqZ2lmbmR6UVdU?tab=BB08J2

最近更新

  1. TCP协议是安全的吗?

    2024-05-25 19:34:18       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-25 19:34:18       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-25 19:34:18       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-25 19:34:18       20 阅读

热门阅读

  1. android上用QT实现绘制曲线及双指放大缩小

    2024-05-25 19:34:18       10 阅读
  2. 接口作为返回类型与类作为返回类型一样吗?

    2024-05-25 19:34:18       11 阅读
  3. 微信小程序自定义头部

    2024-05-25 19:34:18       9 阅读
  4. Git 使用手册

    2024-05-25 19:34:18       10 阅读
  5. npm 上传包

    2024-05-25 19:34:18       9 阅读
  6. node与npm版本对应表

    2024-05-25 19:34:18       11 阅读
  7. MySql

    MySql

    2024-05-25 19:34:18      11 阅读
  8. 常用神经网络-ANN/CNN/RNN/GAN/Transformer

    2024-05-25 19:34:18       9 阅读
  9. Nginx进行TLS降级

    2024-05-25 19:34:18       9 阅读
  10. ClickHouse简介+数据类型篇

    2024-05-25 19:34:18       12 阅读