File size: 6,274 Bytes
e379953
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"""
Dataset Tools for YOLO Object Detection
=====================================

This script provides tools to work with your YOLO dataset locally
and from Hugging Face Hub.
"""

from datasets import load_dataset
import yaml
from pathlib import Path
import matplotlib.pyplot as plt
import cv2
import numpy as np

class YOLODatasetTools:
    def __init__(self, dataset_path=".", hf_repo_id="Sean676/cv_proj"):
        self.dataset_path = Path(dataset_path)
        self.hf_repo_id = hf_repo_id
        self.class_names = []
        self.dataset_info = {}
        
    def load_config(self):
        """Load dataset configuration from dataset.yaml"""
        config_path = self.dataset_path / "dataset.yaml"
        if config_path.exists():
            with open(config_path, 'r') as f:
                config = yaml.safe_load(f)
                self.class_names = list(config.get('names', {}).values())
                self.dataset_info = config
                return config
        return None
    
    def inspect_local_dataset(self):
        """Inspect local dataset structure"""
        print("=== Local Dataset Inspection ===")
        
        # Load config
        config = self.load_config()
        if config:
            print(f"Classes: {self.class_names}")
            print(f"Total classes: {len(self.class_names)}")
        
        # Check images and labels
        images_dir = self.dataset_path / "images"
        labels_dir = self.dataset_path / "labels"
        
        if images_dir.exists():
            print(f"\nImages directory: {images_dir}")
            for split in ["train", "val", "test"]:
                split_dir = images_dir / split
                if split_dir.exists():
                    images = list(split_dir.glob("*.jpg")) + list(split_dir.glob("*.png"))
                    print(f"  {split}: {len(images)} images")
        
        if labels_dir.exists():
            print(f"\nLabels directory: {labels_dir}")
            for split in ["train", "val", "test"]:
                split_dir = labels_dir / split
                if split_dir.exists():
                    labels = list(split_dir.glob("*.txt"))
                    print(f"  {split}: {len(labels)} label files")
    
    def load_from_hf(self):
        """Load dataset from Hugging Face Hub"""
        try:
            print("Loading dataset from Hugging Face Hub...")
            dataset = load_dataset(self.hf_repo_id)
            print(f"Dataset loaded successfully!")
            print(dataset)
            return dataset
        except Exception as e:
            print(f"Failed to load from Hub: {e}")
            return None
    
    def visualize_sample(self, split="train", max_samples=4):
        """Visualize sample images with bounding boxes"""
        images_dir = self.dataset_path / "images" / split
        labels_dir = self.dataset_path / "labels" / split
        
        if not images_dir.exists() or not labels_dir.exists():
            print(f"Split '{split}' not found locally")
            return
        
        # Get sample images
        image_files = list(images_dir.glob("*.jpg"))[:max_samples]
        
        fig, axes = plt.subplots(2, 2, figsize=(12, 10))
        axes = axes.flatten()
        
        for i, img_path in enumerate(image_files):
            if i >= max_samples:
                break
                
            # Load image
            img = cv2.imread(str(img_path))
            img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            
            # Load and draw bounding boxes
            label_path = labels_dir / (img_path.stem + ".txt")
            if label_path.exists():
                with open(label_path, 'r') as f:
                    for line in f:
                        parts = line.strip().split()
                        if len(parts) >= 5:
                            class_id = int(parts[0])
                            x_center, y_center, width, height = map(float, parts[1:5])
                            
                            # Convert to pixel coordinates
                            h, w = img.shape[:2]
                            x1 = int((x_center - width/2) * w)
                            y1 = int((y_center - height/2) * h)
                            x2 = int((x_center + width/2) * w)
                            y2 = int((y_center + height/2) * h)
                            
                            # Draw rectangle
                            cv2.rectangle(img_rgb, (x1, y1), (x2, y2), (255, 0, 0), 2)
                            
                            # Add class label
                            if class_id < len(self.class_names):
                                label = self.class_names[class_id]
                                cv2.putText(img_rgb, label, (x1, y1-10), 
                                          cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
            
            axes[i].imshow(img_rgb)
            axes[i].set_title(f"Sample {i+1}: {img_path.name}")
            axes[i].axis('off')
        
        plt.tight_layout()
        plt.savefig(f"{split}_samples.png")
        print(f"Visualization saved as {split}_samples.png")
        plt.show()
    
    def download_from_hf(self, local_path="./downloaded_dataset"):
        """Download dataset from Hugging Face to local folder"""
        try:
            dataset = load_dataset(self.hf_repo_id)
            save_path = Path(local_path)
            save_path.mkdir(exist_ok=True)
            
            dataset.save_to_disk(str(save_path))
            print(f"Dataset downloaded to: {save_path}")
            return save_path
        except Exception as e:
            print(f"Download failed: {e}")
            return None

def main():
    tools = YOLODatasetTools()
    
    print("=== YOLO Dataset Tools ===")
    print("\n1. Inspect local dataset:")
    tools.inspect_local_dataset()
    
    print("\n2. Load from Hugging Face:")
    hf_dataset = tools.load_from_hf()
    
    print("\n3. Visualize samples (if matplotlib available):")
    try:
        tools.visualize_sample("train", max_samples=2)
    except Exception as e:
        print(f"Visualization failed: {e}")
        print("Install matplotlib: pip install matplotlib")

if __name__ == "__main__":
    main()