thenukegun10x commited on
Commit
37960d3
·
verified ·
1 Parent(s): 86623ef

Update src\data\plant.py

Browse files
Files changed (1) hide show
  1. src/data/plant.py +75 -0
src/data/plant.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plant CSV dataset for data/wa_plants/manifest.csv (observation-separated).
2
+ Reuses RSNA train_mor pattern: manifest + ImageNet norm, 336px, Aug.
3
+ """
4
+ from __future__ import annotations
5
+ import csv
6
+ from pathlib import Path
7
+ import random
8
+ from PIL import Image
9
+ import warnings
10
+ # faster decode: raise limit (100Mpx originals) + draft shrink for large JPEGs
11
+ Image.MAX_IMAGE_PIXELS = 300_000_000
12
+ warnings.filterwarnings("ignore", category=Image.DecompressionBombWarning)
13
+ import torch
14
+ from torch.utils.data import Dataset
15
+ import torchvision.transforms as T
16
+
17
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
18
+ IMAGENET_STD = (0.229, 0.224, 0.225)
19
+
20
+ class PlantDataset(Dataset):
21
+ def __init__(self, manifest: Path, split: str, img_size: int = 336, augment: bool = False):
22
+ self.split = split
23
+ self.img_size = img_size
24
+ rows = []
25
+ # species -> idx map built from manifest train split (500 classes)
26
+ with open(manifest, newline="", encoding="utf-8") as f:
27
+ for r in csv.DictReader(f):
28
+ if r["split"] == split and r["status"] in ("downloaded","skip_exists"):
29
+ rows.append(r)
30
+ # stable class order sorted
31
+ species = sorted({r["species"] for r in rows})
32
+ self.species_to_idx = {s:i for i,s in enumerate(species)}
33
+ self.rows = rows
34
+ # class counts for balanced sampling
35
+ self.augment = augment
36
+ tfms = []
37
+ if augment:
38
+ tfms = [
39
+ T.RandomResizedCrop(img_size, scale=(0.7,1.0)),
40
+ T.RandomHorizontalFlip(),
41
+ T.ColorJitter(0.2,0.2,0.2,0.05),
42
+ T.ToTensor(), T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
43
+ ]
44
+ else:
45
+ tfms = [T.Resize(int(img_size*1.14)), T.CenterCrop(img_size), T.ToTensor(), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)]
46
+ self.tf = T.Compose(tfms)
47
+
48
+ def __len__(self): return len(self.rows)
49
+ def __getitem__(self, i):
50
+ r = self.rows[i]
51
+ p = Path(r["path"])
52
+ # manifest stores absolute win path; if not found try relative to data/wa_plants
53
+ if not p.exists():
54
+ # try finding under train/val subfolders by gbifID
55
+ base = Path(__file__).resolve().parents[2] / "data" / "wa_plants"
56
+ for split in ("train","val"):
57
+ cand = base / split / r["species"].replace(" ","_").replace("/","_")[:120] / f"{r['gbifID']}.jpg"
58
+ if cand.exists():
59
+ p = cand; break
60
+ try:
61
+ im = Image.open(p)
62
+ # fast draft for huge JPEGs (8× shrink before full decode) - no effect on small images
63
+ try:
64
+ if max(im.size) > 1024:
65
+ # draft uses libjpeg shrink 1/2/4/8
66
+ im.draft("RGB", (768, 768))
67
+ except:
68
+ pass
69
+ im = im.convert("RGB")
70
+ except Exception:
71
+ im = Image.new("RGB", (self.img_size, self.img_size))
72
+ # species_to_idx may have been remapped after init (train vs val) - lookup safely
73
+ y = self.species_to_idx.get(r["species"], 0)
74
+ x = self.tf(im)
75
+ return x, y, r["gbifID"]