Datasets:
Download dataset_tools.py from Sean676/cv_proj: direct link, hf CLI and curl.
- Browser
- Download file 6.27 kB
-
https://huggingface.co/datasets/Sean676/cv_proj/resolve/main/dataset_tools.py
- Command line
-
hf download hf://datasets/Sean676/cv_proj/dataset_tools.py
-
curl -L -o dataset_tools.py https://huggingface.co/datasets/Sean676/cv_proj/resolve/main/dataset_tools.py
6.27 kB
| """ | |
| 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() | |