sunglasses / yolov8.py
sushku's picture
Update yolov8.py
fc2a0c4 verified
import os
import cv2
import numpy as np
import supervision as sv
from ultralytics import YOLO
import yaml
from pathlib import Path
import torch
print(torch.cuda.is_available())
def setup_dataset_config(dataset_path, class_names):
data_yaml = {
'path': os.path.abspath(dataset_path),
'train': 'train/images',
'val': 'valid/images',
'test': 'test/images',
'names': {i: name for i, name in enumerate(class_names)},
'nc': len(class_names)
}
with open(os.path.join(dataset_path, 'dataset.yaml'), 'w') as f:
yaml.dump(data_yaml, f, sort_keys=False)
print(f"Dataset config saved to {os.path.join(dataset_path, 'dataset.yaml')}")
return os.path.join(dataset_path, 'dataset.yaml')
def train_yolov8_model(dataset_config, epochs=100, img_size=640, batch_size=16):
model = YOLO('yolov8n.pt')
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"Training on device: {device}")
results = model.train(
data=dataset_config,
epochs=epochs,
imgsz=img_size,
batch=batch_size,
name='accessory_detection',
patience=20,
save=True,
device=device,
verbose=True
)
print("Training completed!")
return model
def validate_model(model):
metrics = model.val()
print(f"Validation metrics: {metrics}")
return metrics
def run_webcam_detection(model_path=None):
if model_path is None:
runs_dir = Path('runs/detect')
if runs_dir.exists():
model_dirs = [d for d in runs_dir.iterdir() if d.is_dir() and d.name.startswith('accessory_detection')]
if model_dirs:
latest_model = max(model_dirs, key=os.path.getmtime) / 'weights' / 'best.pt'
if latest_model.exists():
model_path = str(latest_model)
print(f"Using latest model: {model_path}")
model = YOLO(model_path) if model_path else YOLO('yolov8n.pt')
print(f"Model loaded from {model_path if model_path else 'Pretrained YOLOv8n'}")
cap = cv2.VideoCapture(0, cv2.CAP_V4L2)
if not cap.isOpened():
print("Error: Could not open webcam.")
return
box_annotator = sv.BoxAnnotator(thickness=2, text_thickness=2, text_scale=1)
print("Press 'q' to quit")
while True:
ret, frame = cap.read()
if not ret:
print("Error: Failed to capture image")
break
results = model(frame, conf=0.25)
detections = sv.Detections.from_ultralytics(results[0])
class_names = model.names if hasattr(model, 'names') else {0: "unknown"}
labels = [
f"{class_names[class_id]} {confidence:.2f}"
for _, confidence, class_id, _ in detections
]
frame = box_annotator.annotate(scene=frame, detections=detections, labels=labels)
cv2.putText(frame, "Press 'q' to quit", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow("YOLOv8 Accessory Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
def prepare_custom_dataset(source_dir, target_dir, split_ratios=(0.7, 0.2, 0.1)):
import shutil
from sklearn.model_selection import train_test_split
os.makedirs(os.path.join(target_dir, 'train', 'images'), exist_ok=True)
os.makedirs(os.path.join(target_dir, 'train', 'labels'), exist_ok=True)
os.makedirs(os.path.join(target_dir, 'valid', 'images'), exist_ok=True)
os.makedirs(os.path.join(target_dir, 'valid', 'labels'), exist_ok=True)
os.makedirs(os.path.join(target_dir, 'test', 'images'), exist_ok=True)
os.makedirs(os.path.join(target_dir, 'test', 'labels'), exist_ok=True)
print("YOLOv8 directory structure created")
files = [f for f in os.listdir(source_dir) if f.endswith('.txt') and not f.endswith('classes.txt')]
train_files, temp_files = train_test_split(files, test_size=(split_ratios[1]+split_ratios[2]), random_state=42)
val_ratio = split_ratios[1] / (split_ratios[1] + split_ratios[2])
val_files, test_files = train_test_split(temp_files, test_size=(1-val_ratio), random_state=42)
print(f"Split dataset: {len(train_files)} train, {len(val_files)} validation, {len(test_files)} test images")
setup_dataset_config(target_dir, ["hat", "scarf", "sunglasses", "spectacles", "headphones", "ears_visible"])
print("Dataset preparation completed!")
return os.path.join(target_dir, 'dataset.yaml')
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="YOLOv8 Face Accessory Detection System")
parser.add_argument('--train', action='store_true', help='Train model')
parser.add_argument('--detect', action='store_true', help='Run detection on webcam')
parser.add_argument('--config', type=str, help='Path to dataset config file')
parser.add_argument('--model', type=str, help='Path to trained model')
parser.add_argument('--epochs', type=int, default=100, help='Number of training epochs')
args = parser.parse_args()
if args.train:
if not args.config:
print("Error: Dataset config is required for training")
else:
model = train_yolov8_model(args.config, epochs=args.epochs)
validate_model(model)
if args.detect:
run_webcam_detection(args.model)
if not (args.train or args.detect):
parser.print_help()