Spaces:
Sleeping
Sleeping
File size: 2,732 Bytes
871ff08 | 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 | """
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)
|