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import supervision as sv
|
| 5 |
+
from ultralytics import YOLO
|
| 6 |
+
import yaml
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
print(torch.cuda.is_available())
|
| 11 |
+
|
| 12 |
+
def setup_dataset_config(dataset_path, class_names):
|
| 13 |
+
data_yaml = {
|
| 14 |
+
'path': os.path.abspath(dataset_path),
|
| 15 |
+
'train': 'train/images',
|
| 16 |
+
'val': 'valid/images',
|
| 17 |
+
'test': 'test/images',
|
| 18 |
+
'names': {i: name for i, name in enumerate(class_names)},
|
| 19 |
+
'nc': len(class_names)
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
with open(os.path.join(dataset_path, 'dataset.yaml'), 'w') as f:
|
| 23 |
+
yaml.dump(data_yaml, f, sort_keys=False)
|
| 24 |
+
|
| 25 |
+
print(f"Dataset config saved to {os.path.join(dataset_path, 'dataset.yaml')}")
|
| 26 |
+
return os.path.join(dataset_path, 'dataset.yaml')
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def train_yolov8_model(dataset_config, epochs=100, img_size=640, batch_size=16):
|
| 30 |
+
model = YOLO('yolov8n.pt')
|
| 31 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 32 |
+
print(f"Training on device: {device}")
|
| 33 |
+
|
| 34 |
+
results = model.train(
|
| 35 |
+
data=dataset_config,
|
| 36 |
+
epochs=epochs,
|
| 37 |
+
imgsz=img_size,
|
| 38 |
+
batch=batch_size,
|
| 39 |
+
name='accessory_detection',
|
| 40 |
+
patience=20,
|
| 41 |
+
save=True,
|
| 42 |
+
device=device,
|
| 43 |
+
verbose=True
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
print("Training completed!")
|
| 47 |
+
return model
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def validate_model(model):
|
| 51 |
+
metrics = model.val()
|
| 52 |
+
print(f"Validation metrics: {metrics}")
|
| 53 |
+
return metrics
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def run_webcam_detection(model_path=None):
|
| 57 |
+
if model_path is None:
|
| 58 |
+
runs_dir = Path('runs/detect')
|
| 59 |
+
if runs_dir.exists():
|
| 60 |
+
model_dirs = [d for d in runs_dir.iterdir() if d.is_dir() and d.name.startswith('accessory_detection')]
|
| 61 |
+
if model_dirs:
|
| 62 |
+
latest_model = max(model_dirs, key=os.path.getmtime) / 'weights' / 'best.pt'
|
| 63 |
+
if latest_model.exists():
|
| 64 |
+
model_path = str(latest_model)
|
| 65 |
+
print(f"Using latest model: {model_path}")
|
| 66 |
+
|
| 67 |
+
model = YOLO(model_path) if model_path else YOLO('yolov8n.pt')
|
| 68 |
+
print(f"Model loaded from {model_path if model_path else 'Pretrained YOLOv8n'}")
|
| 69 |
+
|
| 70 |
+
cap = cv2.VideoCapture(0, cv2.CAP_V4L2)
|
| 71 |
+
if not cap.isOpened():
|
| 72 |
+
print("Error: Could not open webcam.")
|
| 73 |
+
return
|
| 74 |
+
|
| 75 |
+
box_annotator = sv.BoxAnnotator(thickness=2, text_thickness=2, text_scale=1)
|
| 76 |
+
print("Press 'q' to quit")
|
| 77 |
+
|
| 78 |
+
while True:
|
| 79 |
+
ret, frame = cap.read()
|
| 80 |
+
if not ret:
|
| 81 |
+
print("Error: Failed to capture image")
|
| 82 |
+
break
|
| 83 |
+
|
| 84 |
+
results = model(frame, conf=0.25)
|
| 85 |
+
detections = sv.Detections.from_ultralytics(results[0])
|
| 86 |
+
class_names = model.names if hasattr(model, 'names') else {0: "unknown"}
|
| 87 |
+
|
| 88 |
+
labels = [
|
| 89 |
+
f"{class_names[class_id]} {confidence:.2f}"
|
| 90 |
+
for _, confidence, class_id, _ in detections
|
| 91 |
+
]
|
| 92 |
+
|
| 93 |
+
frame = box_annotator.annotate(scene=frame, detections=detections, labels=labels)
|
| 94 |
+
cv2.putText(frame, "Press 'q' to quit", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
|
| 95 |
+
|
| 96 |
+
cv2.imshow("YOLOv8 Accessory Detection", frame)
|
| 97 |
+
|
| 98 |
+
if cv2.waitKey(1) & 0xFF == ord('q'):
|
| 99 |
+
break
|
| 100 |
+
|
| 101 |
+
cap.release()
|
| 102 |
+
cv2.destroyAllWindows()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def prepare_custom_dataset(source_dir, target_dir, split_ratios=(0.7, 0.2, 0.1)):
|
| 106 |
+
import shutil
|
| 107 |
+
from sklearn.model_selection import train_test_split
|
| 108 |
+
|
| 109 |
+
os.makedirs(os.path.join(target_dir, 'train', 'images'), exist_ok=True)
|
| 110 |
+
os.makedirs(os.path.join(target_dir, 'train', 'labels'), exist_ok=True)
|
| 111 |
+
os.makedirs(os.path.join(target_dir, 'valid', 'images'), exist_ok=True)
|
| 112 |
+
os.makedirs(os.path.join(target_dir, 'valid', 'labels'), exist_ok=True)
|
| 113 |
+
os.makedirs(os.path.join(target_dir, 'test', 'images'), exist_ok=True)
|
| 114 |
+
os.makedirs(os.path.join(target_dir, 'test', 'labels'), exist_ok=True)
|
| 115 |
+
|
| 116 |
+
print("YOLOv8 directory structure created")
|
| 117 |
+
|
| 118 |
+
files = [f for f in os.listdir(source_dir) if f.endswith('.txt') and not f.endswith('classes.txt')]
|
| 119 |
+
|
| 120 |
+
train_files, temp_files = train_test_split(files, test_size=(split_ratios[1]+split_ratios[2]), random_state=42)
|
| 121 |
+
val_ratio = split_ratios[1] / (split_ratios[1] + split_ratios[2])
|
| 122 |
+
val_files, test_files = train_test_split(temp_files, test_size=(1-val_ratio), random_state=42)
|
| 123 |
+
|
| 124 |
+
print(f"Split dataset: {len(train_files)} train, {len(val_files)} validation, {len(test_files)} test images")
|
| 125 |
+
|
| 126 |
+
setup_dataset_config(target_dir, ["hat", "scarf", "sunglasses", "spectacles", "headphones", "ears_visible"])
|
| 127 |
+
print("Dataset preparation completed!")
|
| 128 |
+
|
| 129 |
+
return os.path.join(target_dir, 'dataset.yaml')
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
if __name__ == "__main__":
|
| 133 |
+
import argparse
|
| 134 |
+
parser = argparse.ArgumentParser(description="YOLOv8 Face Accessory Detection System")
|
| 135 |
+
parser.add_argument('--train', action='store_true', help='Train model')
|
| 136 |
+
parser.add_argument('--detect', action='store_true', help='Run detection on webcam')
|
| 137 |
+
parser.add_argument('--config', type=str, help='Path to dataset config file')
|
| 138 |
+
parser.add_argument('--model', type=str, help='Path to trained model')
|
| 139 |
+
parser.add_argument('--epochs', type=int, default=100, help='Number of training epochs')
|
| 140 |
+
args = parser.parse_args()
|
| 141 |
+
|
| 142 |
+
if args.train:
|
| 143 |
+
if not args.config:
|
| 144 |
+
print("Error: Dataset config is required for training")
|
| 145 |
+
else:
|
| 146 |
+
model = train_yolov8_model(args.config, epochs=args.epochs)
|
| 147 |
+
validate_model(model)
|
| 148 |
+
|
| 149 |
+
if args.detect:
|
| 150 |
+
run_webcam_detection(args.model)
|
| 151 |
+
|
| 152 |
+
if not (args.train or args.detect):
|
| 153 |
+
parser.print_help()
|