----追光逐电 光赢未来----
import json
import os
def convert_coco_to_yolo(coco_file, output_dir):
with open(coco_file) as f:
data = json.load(f)
for image in data['images']:
annotations = [ann for ann in data['annotations'] if ann['image_id'] == image['id']]
label_file = os.path.join(output_dir, f"{image['file_name'].split('.')[0]}.txt")
with open(label_file, 'w') as f:
for ann in annotations:
category_id = ann['category_id'] - 1 # YOLO classes are 0-indexed
bbox = ann['bbox']
x_center = (bbox[0] + bbox[2] / 2) / image['width']
y_center = (bbox[1] + bbox[3] / 2) / image['height']
width = bbox[2] / image['width']
height = bbox[3] / image['height']
f.write(f"{category_id} {x_center} {y_center} {width} {height}\n")
import albumentations as A
from albumentations.pytorch import ToTensorV2
transform = A.Compose([
A.RandomCrop(width=640, height=640),
A.HorizontalFlip(p=0.5),
A.RandomBrightnessContrast(p=0.2),
A.HueSaturationValue(p=0.2),
ToTensorV2()
])
from sklearn.model_selection import train_test_split
import os
import shutil
def split_dataset(images_dir, labels_dir, output_dir, test_size=0.2, val_size=0.2):
images = [f for f in os.listdir(images_dir) if f.endswith('.jpg')]
train_images, test_images = train_test_split(images, test_size=test_size, random_state=42)
train_images, val_images = train_test_split(train_images, test_size=val_size, random_state=42)
for subset, subset_images in [('train', train_images), ('val', val_images), ('test', test_images)]:
os.makedirs(f"{output_dir}/images/{subset}", exist_ok=True)
os.makedirs(f"{output_dir}/labels/{subset}", exist_ok=True)
for image in subset_images:
shutil.copy(f"{images_dir}/{image}", f"{output_dir}/images/{subset}/{image}")
label_file = image.replace('.jpg', '.txt')
shutil.copy(f"{labels_dir}/{label_file}", f"{output_dir}/labels/{subset}/{label_file}")
path: ../datasets # Path to dataset root directory
train: images/train # Path to training images
val: images/val # Path to validation images
nc: 3 # Number of classes
names: ['class1', 'class2', 'class3'] # Class names
from ultralytics import YOLO
model = YOLO('yolov8n.pt') # Load YOLOv8 Nano pretrained weights
model.train(data='custom_dataset.yaml', # Path to YAML config
epochs=50, # Number of epochs
imgsz=640, # Image size
batch=16, # Batch size
device=0) # GPU device index
'custom_dataset.yaml', =
epochs=50,
imgsz=640,
lr0=0.01, # Starting learning rate
optimizer='AdamW',
augment=True)
申明:感谢原创作者的辛勤付出。本号转载的文章均会在文中注明,若遇到版权问题请联系我们处理。
----与智者为伍 为创新赋能----
联系邮箱:uestcwxd@126.com
QQ:493826566