File size: 3,926 Bytes
02a1d81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reading the GrainDet crops and the split lists.

What is in this file, in simple words:
  * CLASS_ORDER      - the eight classes, always in this order (the label number is the position).
  * tray_id          - every crop's file name contains the time the tray was photographed.
                       All crops with the same time stamp are one "tray". We need this to
                       resample whole trays when we compute confidence intervals.
  * load_split       - reads the three CSV lists (fine-tune train / fine-tune validation / held-out).
  * CropDataset      - gives a model one crop at a time (image, label).
  * make_transforms  - how a crop is resized, flipped, rotated and normalised.
"""
import re
from pathlib import Path

import pandas as pd
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms

# The label number of a class is its position in this list (NOR = 0, ..., IM = 7).
CLASS_ORDER = ["NOR", "F&S", "SD", "MY", "AP", "BN", "HD", "IM"]

# GrainSet's own colour statistics. We use them for every model, also on GrainDet,
# because computing new ones on GrainDet made the zero-shot scores worse (paper, Section 3).
GRAINSET_MEAN = (0.308562, 0.251994, 0.187898)
GRAINSET_STD = (0.240441, 0.197289, 0.149387)
IMAGE_SIZE = 224

_TRAY_PATTERN = re.compile(r"(\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2})")


def tray_id(path: str) -> str:
    """Return the time stamp in the file name, e.g. '2022-12-16-10-24-45'. One time stamp = one tray."""
    found = _TRAY_PATTERN.search(str(path))
    if found is None:
        raise ValueError(f"no tray time stamp in file name: {path}")
    return found.group(1)


def capture_date(path: str) -> str:
    """The calendar date of the tray, e.g. '2022-12-16' (used for the session check)."""
    return tray_id(path)[:10]


def load_split(split_dir: str):
    """Read the three lists that define our split of the 8,640 GrainDet crops.

    Each CSV has the columns: path, class, label. We add a 'tray' column.
    Returns (train, validation, heldout) as pandas tables.
    """
    split_dir = Path(split_dir)
    parts = []
    for name in ("graindet_finetune_train.csv", "graindet_finetune_val.csv", "graindet_heldout_eval.csv"):
        table = pd.read_csv(split_dir / name)
        table["tray"] = table["path"].map(tray_id)
        parts.append(table)
    return tuple(parts)


def make_transforms(train: bool):
    """Crops are resized to 224 x 224. For training we also flip, rotate (up to 30 degrees)
    and jitter the colour a little, so the model sees slightly different crops each epoch."""
    steps = [transforms.Resize((IMAGE_SIZE, IMAGE_SIZE))]
    if train:
        steps += [transforms.RandomHorizontalFlip(0.5), transforms.RandomVerticalFlip(0.5),
                  transforms.RandomRotation(30), transforms.ColorJitter(0.2, 0.2, 0.2, 0.1)]
    steps += [transforms.ToTensor(), transforms.Normalize(GRAINSET_MEAN, GRAINSET_STD)]
    return transforms.Compose(steps)


class CropDataset(Dataset):
    """One item = (image tensor, label number, file path)."""

    def __init__(self, table: pd.DataFrame, images_dir: str, train: bool):
        # The split lists store the original file locations; we only keep the file name
        # and look it up inside images_dir/<class>/ so the code works on any computer.
        self.table = table.reset_index(drop=True)
        self.images_dir = Path(images_dir)
        self.transform = make_transforms(train)

    def __len__(self):
        return len(self.table)

    def __getitem__(self, i):
        row = self.table.iloc[i]
        # Careful: the class is called "F&S" in the lists, but its folder on disk is "FS" (no "&").
        file = self.images_dir / str(row["class"]).replace("&", "") / Path(str(row["path"]).replace("\\", "/")).name
        image = Image.open(file).convert("RGB")
        return self.transform(image), int(row["label"]), str(row["path"])