文章目录
- 一、类别定义
- 二、标注后再清洗数据
- 三、训练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