Yoyo-9877 commited on
Commit
d6c09c0
Β·
verified Β·
1 Parent(s): 5a266b9

Update yolo_training_script

Browse files
Files changed (1) hide show
  1. yolo_training_script +1 -107
yolo_training_script CHANGED
@@ -1,107 +1 @@
1
- #!/usr/bin/env python3
2
- # This script is for YOLOv8 training using data from PlantNet and local files.
3
-
4
- import os
5
- import requests
6
- import json
7
- import random
8
- import shutil
9
- from ultralytics import YOLO
10
-
11
- # ==================== CONFIGURATION & SECRETS ====================
12
- # Use your API key from the main script
13
- PLANTNET_API_KEY = "2b10HlR0yP4wZbvHjP8jCo3Aae"
14
- PLANTNET_SEARCH_URL = "https://my-api.plantnet.org/v2/identify/all"
15
-
16
- # Define the training directory structure
17
- TRAIN_DIR = 'yolo_train'
18
- DATASET_YAML_PATH = os.path.join(TRAIN_DIR, 'dataset.yaml')
19
-
20
- # Define your 52 morphological features here.
21
- # This list is crucial and must match the labels you will create in your annotation tool.
22
- MORPHOLOGICAL_FEATURES = [
23
- 'leaf', 'stem', 'flower', 'fruit', 'root', 'branch', 'petal', 'sepal',
24
- 'bud', 'thorn', 'node', 'vein', 'blade', 'petiole', 'stamen', 'pistil',
25
- 'seed', 'bark', 'trunk', 'tuber', 'rhizome', 'bulb', 'spore', 'cone',
26
- 'tendril', 'pollen', 'nectar', 'bract', 'gemma', 'stomata', 'cuticle',
27
- 'xylem', 'phloem', 'vascular_bundle', 'cambium', 'lenticel', 'stolon',
28
- 'runner', 'corm', 'sheath', 'ligule', 'auricle', 'rachis', 'rachilla',
29
- 'glume', 'lemma', 'palea', 'floret', 'awns', 'caryopsis', 'pericarp', 'endosperm'
30
- ]
31
- # You can update this list based on what you want to annotate.
32
-
33
- # ==================== DATA COLLECTION & PREPARATION ====================
34
- def download_and_prepare_dataset(plant_list: list, num_images_per_plant: int = 50):
35
- """
36
- Downloads and organizes images for a list of plants.
37
- Note: PlantNet's API is for identification. We'll simulate fetching images
38
- from a hypothetical image search to demonstrate the concept.
39
- In a real-world scenario, you would use a web scraper or a curated dataset.
40
-
41
- This function creates a basic directory structure for YOLO.
42
- """
43
- print("Preparing dataset directory...")
44
- # Clean up and create new directories
45
- if os.path.exists(TRAIN_DIR):
46
- shutil.rmtree(TRAIN_DIR)
47
- os.makedirs(os.path.join(TRAIN_DIR, 'images'))
48
- os.makedirs(os.path.join(TRAIN_DIR, 'images', 'train'))
49
- os.makedirs(os.path.join(TRAIN_DIR, 'images', 'val'))
50
- os.makedirs(os.path.join(TRAIN_DIR, 'labels'))
51
- os.makedirs(os.path.join(TRAIN_DIR, 'labels', 'train'))
52
- os.makedirs(os.path.join(TRAIN_DIR, 'labels', 'val'))
53
-
54
- # Simulate downloading and creating placeholder images and labels
55
- print("Simulating dataset creation. Please replace with your actual data and annotations.")
56
-
57
- # Create dataset.yaml
58
- with open(DATASET_YAML_PATH, 'w') as f:
59
- yaml_content = f"""
60
- path: {os.path.abspath(TRAIN_DIR)}
61
- train: images/train
62
- val: images/val
63
-
64
- names:
65
- {os.linesep.join([f" {i}: {name}" for i, name in enumerate(MORPHOLOGICAL_FEATURES)])}
66
- """
67
- f.write(yaml_content)
68
-
69
- print(f"βœ… Created {DATASET_YAML_PATH}")
70
- print(f"Next, populate {os.path.join(TRAIN_DIR, 'images', 'train')}, {os.path.join(TRAIN_DIR, 'images', 'val')}, and their corresponding 'labels' directories with your annotated data.")
71
-
72
- # ==================== YOLO TRAINING ====================
73
- def start_yolo_training():
74
- """
75
- Starts the YOLOv8 training process using the prepared dataset.
76
- """
77
- if not os.path.exists(DATASET_YAML_PATH):
78
- print("❌ Dataset not found. Please run the data preparation step first.")
79
- return
80
-
81
- print("Loading YOLOv8 model for training...")
82
- try:
83
- model = YOLO('yolov8n.pt')
84
- print("Starting training...")
85
-
86
- # Train the model
87
- # You can adjust epochs, image size (imgsz), and other parameters
88
- results = model.train(data=DATASET_YAML_PATH, epochs=100, imgsz=640)
89
-
90
- print("βœ… Training complete. Results are saved in the 'runs' directory.")
91
- print("The best model is located at 'runs/detect/train/weights/best.pt'.")
92
-
93
- except Exception as e:
94
- print(f"An error occurred during training: {e}")
95
-
96
- # ==================== MAIN EXECUTION ====================
97
- if __name__ == "__main__":
98
- # Example list of plants to train on
99
- plants_to_train = ["rosemary", "basil", "mint"]
100
-
101
- # Step 1: Prepare the directory structure and dataset.yaml
102
- # This function is a placeholder. You need to manually add your images and labels.
103
- download_and_prepare_dataset(plants_to_train)
104
-
105
- # Step 2: Start the training process
106
- # Make sure you have your annotated images and labels in place before running this.
107
- # start_yolo_training() # Uncomment this line to run the training
 
1
+ pip install --upgrade gradio