""" Dataset loader for garbage classification. Supports both COCO JSON format and pre-split JSON format (from split_dataset.py). """ import json import os from collections import defaultdict from pathlib import Path import torch from PIL import Image from torch.utils.data import Dataset, WeightedRandomSampler CLASSES = ["biodegradable", "cardboard", "glass", "metal", "paper", "plastic"] CLASS_TO_IDX = {c: i for i, c in enumerate(CLASSES)} class GarbageDataset(Dataset): def __init__(self, json_path: str, img_dir: str = None, transform=None): """ Accepts two formats: 1. COCO JSON + img_dir (original format) 2. Pre-split JSON from split_dataset.py (list of {path, label}) """ with open(json_path) as f: data = json.load(f) if isinstance(data, list): # Pre-split format: [{path, label}, ...] self.samples = [(d["path"], d["label"]) for d in data if os.path.exists(d["path"])] else: # COCO format self.samples = self._load_coco(data, img_dir) self.transform = transform def _load_coco(self, coco, img_dir): cat_map = {c["id"]: c["name"] for c in coco["categories"]} img_file = {img["id"]: img["file_name"] for img in coco["images"]} img_cat_area = defaultdict(lambda: defaultdict(float)) for ann in coco["annotations"]: img_cat_area[ann["image_id"]][ann["category_id"]] += ann["area"] samples = [] for img_id, cat_areas in img_cat_area.items(): dominant = max(cat_areas, key=cat_areas.get) name = cat_map[dominant] if name not in CLASS_TO_IDX: continue fpath = os.path.join(img_dir, img_file[img_id]) if os.path.exists(fpath): samples.append((fpath, CLASS_TO_IDX[name])) return samples def __len__(self): return len(self.samples) def __getitem__(self, idx): fpath, label = self.samples[idx] img = Image.open(fpath).convert("RGB") if self.transform: img = self.transform(img) return img, label def class_counts(self): counts = [0] * len(CLASSES) for _, label in self.samples: counts[label] += 1 return counts def make_weighted_sampler(dataset: GarbageDataset) -> WeightedRandomSampler: counts = dataset.class_counts() total = sum(counts) weights_per_class = [total / (c + 1e-6) for c in counts] sample_weights = [weights_per_class[label] for _, label in dataset.samples] return WeightedRandomSampler(sample_weights, num_samples=len(sample_weights), replacement=True)