Datasets:

Modalities:
Image
Formats:
parquet
Languages:
English
ArXiv:
Libraries:
Datasets
pandas
License:
File size: 3,773 Bytes
b9a02ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
from collections.abc import Generator
from pathlib import Path
from typing import Any

import datasets
import numpy as np
from datasets import Dataset
from datasets.splits import NamedSplit
from numpy.typing import NDArray
from PIL import Image
from tqdm import tqdm


tissue_map = {
    "Bile-duct": "Bile Duct",
    "HeadNeck": "Head & Neck",
    "Adrenal_gland": "Adrenal Gland",
}

features = datasets.Features(
    {
        "image": datasets.Image(mode="RGB"),
        "instances": datasets.Sequence(datasets.Image(mode="1")),
        "categories": datasets.Sequence(
            datasets.ClassLabel(
                num_classes=5,
                names=[
                    "Neoplastic",
                    "Inflammatory",
                    "Connective",
                    "Dead",
                    "Epithelial",
                ],
            )
        ),
        "tissue": datasets.ClassLabel(
            num_classes=19,
            names=[
                "Adrenal Gland",
                "Bile Duct",
                "Bladder",
                "Breast",
                "Cervix",
                "Colon",
                "Esophagus",
                "Head & Neck",
                "Kidney",
                "Liver",
                "Lung",
                "Ovarian",
                "Pancreatic",
                "Prostate",
                "Skin",
                "Stomach",
                "Testis",
                "Thyroid",
                "Uterus",
            ],
        ),
    }
)


def one_hot_mask(
    mask: NDArray[np.float64],
) -> tuple[NDArray[np.bool], NDArray[np.uint8]]:
    """Converts a mask to one-hot encoding.

    Returns:
        A dictionary with the following keys:
            - masks: A 3D array with shape (num_masks, height, width) containing the
                one-hot encoded masks.
            - labels: A 1D array with shape (num_masks,) containing the class labels.
    """
    masks: list[NDArray[np.bool]] = []
    labels: list[NDArray[np.uint8]] = []

    for c in range(mask.shape[-1] - 1):
        masks.append(mask[..., c] == np.unique(mask[..., c])[1:, None, None])
        labels.append(np.full(masks[-1].shape[0], c, dtype=np.uint8))

    return np.concatenate(masks), np.concatenate(labels)


def process(path: str, subfolder: str) -> Generator[dict[str, Any], None, None]:
    images = np.load(Path(path, "images", subfolder, "images.npy"), mmap_mode="r")
    masks = np.load(Path(path, "masks", subfolder, "masks.npy"), mmap_mode="r")
    types = np.load(Path(path, "images", subfolder, "types.npy"))

    for image, mask, tissue in tqdm(
        zip(images, masks, types, strict=True), total=len(images)
    ):
        mask, labels = one_hot_mask(mask)

        yield {
            "image": Image.fromarray(image.astype(np.uint8)),
            "instances": [Image.fromarray(m) for m in mask],
            "categories": labels,
            "tissue": tissue_map.get(tissue, tissue),
        }


if __name__ == "__main__":
    fold1 = Dataset.from_generator(
        process,
        gen_kwargs={"path": "PanNuke/Fold 1", "subfolder": "fold1"},
        features=features,
        split=NamedSplit("fold1"),
        keep_in_memory=True,
    )
    fold1.push_to_hub("RationAI/PanNuke")
    fold2 = Dataset.from_generator(
        process,
        gen_kwargs={"path": "PanNuke/Fold 2", "subfolder": "fold2"},
        features=features,
        split=NamedSplit("fold2"),
        keep_in_memory=True,
    )
    fold2.push_to_hub("RationAI/PanNuke")
    fold3 = Dataset.from_generator(
        process,
        gen_kwargs={"path": "PanNuke/Fold 3", "subfolder": "fold3"},
        features=features,
        split=NamedSplit("fold3"),
        keep_in_memory=True,
    )
    fold3.push_to_hub("RationAI/PanNuke")