Delete ccagt.py
Browse files
ccagt.py
DELETED
@@ -1,355 +0,0 @@
|
|
1 |
-
import json
|
2 |
-
import os
|
3 |
-
from collections import OrderedDict, defaultdict
|
4 |
-
from math import ceil
|
5 |
-
|
6 |
-
import numpy as np
|
7 |
-
import pandas as pd
|
8 |
-
|
9 |
-
import datasets
|
10 |
-
|
11 |
-
|
12 |
-
logger = datasets.logging.get_logger(__name__)
|
13 |
-
|
14 |
-
CCAGT_CLASSES = OrderedDict(
|
15 |
-
{
|
16 |
-
1: "NUCLEUS",
|
17 |
-
2: "CLUSTER",
|
18 |
-
3: "SATELLITE",
|
19 |
-
4: "NUCLEUS_OUT_OF_FOCUS",
|
20 |
-
5: "OVERLAPPED_NUCLEI",
|
21 |
-
6: "NON_VIABLE_NUCLEUS",
|
22 |
-
7: "LEUKOCYTE_NUCLEUS",
|
23 |
-
}
|
24 |
-
)
|
25 |
-
|
26 |
-
_LICENSE = "CC BY NC 3.0 License"
|
27 |
-
|
28 |
-
_CITATION = """\
|
29 |
-
@misc{CCAgTDataset,
|
30 |
-
doi = {10.17632/WG4BPM33HJ.2},
|
31 |
-
url = {https://data.mendeley.com/datasets/wg4bpm33hj/2},
|
32 |
-
author = {Jo{\\~{a}}o Gustavo Atkinson Amorim and Andr{\'{e}} Vict{\'{o}}ria Matias and Tainee Bottamedi and Vinícius Sanches and Ane Francyne Costa and Fabiana Botelho De Miranda Onofre and Alexandre Sherlley Casimiro Onofre and Aldo von Wangenheim},
|
33 |
-
title = {CCAgT: Images of Cervical Cells with AgNOR Stain Technique},
|
34 |
-
publisher = {Mendeley},
|
35 |
-
year = {2022},
|
36 |
-
copyright = {Attribution-NonCommercial 3.0 Unported}
|
37 |
-
}
|
38 |
-
"""
|
39 |
-
|
40 |
-
_HOMEPAGE = "https://data.mendeley.com/datasets/wg4bpm33hj"
|
41 |
-
|
42 |
-
_DESCRIPTION = """\
|
43 |
-
The CCAgT (Images of Cervical Cells with AgNOR Stain Technique) dataset contains 9339 images (1600x1200 resolution where each pixel is 0.111µmX0.111µm) from 15 different slides stained using the AgNOR technique.
|
44 |
-
Each image has at least one label. In total, this dataset has more than 63K instances of annotated object.
|
45 |
-
The images are from the patients of the Gynecology and Colonoscopy Outpatient Clinic of the Polydoro Ernani de São Thiago University Hospital of the Universidade Federal de Santa Catarina (HU-UFSC).
|
46 |
-
"""
|
47 |
-
|
48 |
-
_DATA_URL = "https://md-datasets-cache-zipfiles-prod.s3.eu-west-1.amazonaws.com/wg4bpm33hj-2.zip"
|
49 |
-
|
50 |
-
|
51 |
-
def tvt(ids, tvt_size, seed=1609):
|
52 |
-
"""From a list of indexes/ids (int) will generate the train-validation-test data.
|
53 |
-
|
54 |
-
Based on `github.com/scikit-learn/scikit-learn/blob/37ac6788c9504ee409b75e5e24ff7d86c90c2ffb/sklearn/model_selection/_split.py#L2321`
|
55 |
-
"""
|
56 |
-
n_samples = len(ids)
|
57 |
-
|
58 |
-
qtd = {
|
59 |
-
"valid": ceil(n_samples * tvt_size[1]),
|
60 |
-
"test": ceil(n_samples * tvt_size[2]),
|
61 |
-
}
|
62 |
-
qtd["train"] = int(n_samples - qtd["valid"] - qtd["test"])
|
63 |
-
|
64 |
-
rng = np.random.RandomState(seed)
|
65 |
-
permutatation = rng.permutation(ids)
|
66 |
-
|
67 |
-
out = {
|
68 |
-
"train": set(permutatation[: qtd["train"]]),
|
69 |
-
"valid": set(permutatation[qtd["train"] : qtd["train"] + qtd["valid"]]),
|
70 |
-
"test": set(permutatation[qtd["train"] + qtd["valid"] :]),
|
71 |
-
}
|
72 |
-
|
73 |
-
return out["train"], out["valid"], out["test"]
|
74 |
-
|
75 |
-
|
76 |
-
def annotations_per_image(df):
|
77 |
-
"""
|
78 |
-
based on: https://github.com/johnnv1/CCAgT-utils/blob/54ade78e4ddb2e2ed9507b8a1633940897767cac/CCAgT_utils/describe.py#L152
|
79 |
-
"""
|
80 |
-
df_describe_images = df.groupby(["image_id", "category_id"]).size().reset_index().rename(columns={0: "count"})
|
81 |
-
df_describe_images = df_describe_images.pivot(columns=["category_id"], index="image_id")
|
82 |
-
df_describe_images = df_describe_images.rename(CCAGT_CLASSES, axis=1)
|
83 |
-
df_describe_images["qtd_annotations"] = df_describe_images.sum(axis=1)
|
84 |
-
df_describe_images = df_describe_images.fillna(0)
|
85 |
-
df_describe_images["NORs"] = (
|
86 |
-
df_describe_images[
|
87 |
-
"count",
|
88 |
-
CCAGT_CLASSES[2],
|
89 |
-
]
|
90 |
-
+ df_describe_images[
|
91 |
-
"count",
|
92 |
-
CCAGT_CLASSES[3],
|
93 |
-
]
|
94 |
-
)
|
95 |
-
|
96 |
-
return df_describe_images
|
97 |
-
|
98 |
-
|
99 |
-
def tvt_by_nors(df, tvt_size=(0.7, 0.15, 0.15), **kwargs):
|
100 |
-
"""This will split the CCAgT annotations based on the number of NORs
|
101 |
-
into each image. With a silly separation, first will split
|
102 |
-
between each fold images with one or less NORs, after will split
|
103 |
-
images with the amount of NORs is between 2 and 7, and at least will
|
104 |
-
split images that have more than 7 NORs.
|
105 |
-
|
106 |
-
based on `https://github.com/johnnv1/CCAgT-utils/blob/54ade78e4ddb2e2ed9507b8a1633940897767cac/CCAgT_utils/split.py#L64`
|
107 |
-
"""
|
108 |
-
if sum(tvt_size) != 1:
|
109 |
-
raise ValueError("The sum of `tvt_size` need to be equal to 1!")
|
110 |
-
|
111 |
-
df_describe_imgs = annotations_per_image(df)
|
112 |
-
|
113 |
-
img_ids = {}
|
114 |
-
img_ids["low_nors"] = df_describe_imgs.loc[(df_describe_imgs["NORs"] < 2)].index
|
115 |
-
img_ids["medium_nors"] = df_describe_imgs[(df_describe_imgs["NORs"] >= 2) * (df_describe_imgs["NORs"] <= 7)].index
|
116 |
-
img_ids["high_nors"] = df_describe_imgs[(df_describe_imgs["NORs"] > 7)].index
|
117 |
-
|
118 |
-
train_ids = set({})
|
119 |
-
valid_ids = set({})
|
120 |
-
test_ids = set({})
|
121 |
-
|
122 |
-
for k, ids in img_ids.items():
|
123 |
-
logger.info(f"Splitting {len(ids)} images with {k} quantity...")
|
124 |
-
if len(ids) == 0:
|
125 |
-
continue
|
126 |
-
_train, _valid, _test = tvt(ids, tvt_size, **kwargs)
|
127 |
-
logger.info(f">T: {len(_train)} V: {len(_valid)} T: {len(_test)}")
|
128 |
-
train_ids = train_ids.union(_train)
|
129 |
-
valid_ids = valid_ids.union(_valid)
|
130 |
-
test_ids = test_ids.union(_test)
|
131 |
-
|
132 |
-
return train_ids, valid_ids, test_ids
|
133 |
-
|
134 |
-
|
135 |
-
def get_basename(path):
|
136 |
-
return os.path.splitext(os.path.basename(path))[0]
|
137 |
-
|
138 |
-
|
139 |
-
def get_slide_id(path):
|
140 |
-
bn = get_basename(path)
|
141 |
-
slide_id = bn.split("_")[0]
|
142 |
-
return slide_id
|
143 |
-
|
144 |
-
|
145 |
-
class CCAgTConfig(datasets.BuilderConfig):
|
146 |
-
"""BuilderConfig for CCAgT."""
|
147 |
-
|
148 |
-
seed = 1609
|
149 |
-
tvt_size = (0.7, 0.15, 0.15)
|
150 |
-
|
151 |
-
|
152 |
-
class CCAgT(datasets.GeneratorBasedBuilder):
|
153 |
-
"""Images of Cervical Cells with AgNOR Stain Technique (CCAgT) dataset"""
|
154 |
-
|
155 |
-
test_dummy_data = False
|
156 |
-
|
157 |
-
VERSION = datasets.Version("2.0.0")
|
158 |
-
|
159 |
-
BUILDER_CONFIG_CLASS = CCAgTConfig
|
160 |
-
BUILDER_CONFIGS = [
|
161 |
-
CCAgTConfig(name="semantic_segmentation", version=VERSION, description="The semantic segmentation variant."),
|
162 |
-
CCAgTConfig(name="object_detection", version=VERSION, description="The object detection variant."),
|
163 |
-
CCAgTConfig(name="instance_segmentation", version=VERSION, description="The instance segmentation variant."),
|
164 |
-
]
|
165 |
-
|
166 |
-
DEFAULT_CONFIG_NAME = "semantic_segmentation"
|
167 |
-
|
168 |
-
def _info(self):
|
169 |
-
assert len(CCAGT_CLASSES) == 7
|
170 |
-
|
171 |
-
if self.config.name == "semantic_segmentation":
|
172 |
-
features = datasets.Features(
|
173 |
-
{
|
174 |
-
"image": datasets.Image(),
|
175 |
-
"annotation": datasets.Image(),
|
176 |
-
}
|
177 |
-
)
|
178 |
-
elif self.config.name == "object_detection":
|
179 |
-
features = datasets.Features(
|
180 |
-
{
|
181 |
-
"image": datasets.Image(),
|
182 |
-
"objects": datasets.Sequence(
|
183 |
-
{
|
184 |
-
"bbox": datasets.Sequence(datasets.Value("float32"), length=4),
|
185 |
-
"label": datasets.ClassLabel(names=list(CCAGT_CLASSES.values())),
|
186 |
-
}
|
187 |
-
),
|
188 |
-
}
|
189 |
-
)
|
190 |
-
elif self.config.name == "instance_segmentation":
|
191 |
-
features = datasets.Features(
|
192 |
-
{
|
193 |
-
"image": datasets.Image(),
|
194 |
-
"objects": datasets.Sequence(
|
195 |
-
{
|
196 |
-
"bbox": datasets.Sequence(datasets.Value("float32"), length=4),
|
197 |
-
"segment": datasets.Sequence(datasets.Sequence(datasets.Value("float32"))),
|
198 |
-
"label": datasets.ClassLabel(names=list(CCAGT_CLASSES.values())),
|
199 |
-
}
|
200 |
-
),
|
201 |
-
}
|
202 |
-
)
|
203 |
-
else:
|
204 |
-
raise NotImplementedError
|
205 |
-
|
206 |
-
return datasets.DatasetInfo(
|
207 |
-
description=_DESCRIPTION,
|
208 |
-
features=features,
|
209 |
-
homepage=_HOMEPAGE,
|
210 |
-
license=_LICENSE,
|
211 |
-
citation=_CITATION,
|
212 |
-
)
|
213 |
-
|
214 |
-
def _download_and_extract_all(self, dl_manager):
|
215 |
-
def extracted_by_slide(paths):
|
216 |
-
return {get_slide_id(path): dl_manager.extract(path) for path in paths}
|
217 |
-
|
218 |
-
data_dir = dl_manager.download_and_extract(_DATA_URL)
|
219 |
-
base_path = os.path.join(data_dir, "wg4bpm33hj-2")
|
220 |
-
|
221 |
-
logger.info("Extracting images...")
|
222 |
-
self.images_base_dir = os.path.join(base_path, "images")
|
223 |
-
images_to_extract = [
|
224 |
-
os.path.join(self.images_base_dir, fn) for fn in os.listdir(self.images_base_dir) if fn.endswith(".zip")
|
225 |
-
]
|
226 |
-
self.images_extracted = extracted_by_slide(images_to_extract)
|
227 |
-
|
228 |
-
if self.config.name == "semantic_segmentation":
|
229 |
-
logger.info("Extracting masks...")
|
230 |
-
self.masks_base_dir = os.path.join(base_path, "masks")
|
231 |
-
masks_to_extract = [
|
232 |
-
os.path.join(self.masks_base_dir, fn) for fn in os.listdir(self.masks_base_dir) if fn.endswith(".zip")
|
233 |
-
]
|
234 |
-
self.masks_extracted = extracted_by_slide(masks_to_extract)
|
235 |
-
elif self.config.name in {"object_detection", "instance_segmentation"}:
|
236 |
-
logger.info("Reading COCO OD file...")
|
237 |
-
ccagt_OD_COCO_path = os.path.join(base_path, "CCAgT_COCO_OD.json")
|
238 |
-
with open(ccagt_OD_COCO_path, "r", encoding="utf-8") as json_file:
|
239 |
-
coco_OD = json.load(json_file)
|
240 |
-
|
241 |
-
self._imageid_to_coco_OD_annotations = defaultdict(list)
|
242 |
-
for labels in coco_OD["annotations"]:
|
243 |
-
self._imageid_to_coco_OD_annotations[labels["image_id"]].append(labels)
|
244 |
-
|
245 |
-
logger.info("Loading dataset info...")
|
246 |
-
ccagt_raw_path = os.path.join(base_path, "CCAgT.parquet.gzip")
|
247 |
-
with open(ccagt_raw_path, "rb") as f:
|
248 |
-
self._ccagt_info = pd.read_parquet(f, columns=["image_name", "category_id", "image_id", "slide_id"])
|
249 |
-
self._bn_to_imageid = pd.Series(
|
250 |
-
self._ccagt_info["image_id"].values, index=self._ccagt_info["image_name"]
|
251 |
-
).to_dict()
|
252 |
-
|
253 |
-
def _split_generators(self, dl_manager):
|
254 |
-
"""Returns SplitGenerators."""
|
255 |
-
|
256 |
-
def build_path(basename, tp="images"):
|
257 |
-
slide = basename.split("_")[0]
|
258 |
-
if tp == "images":
|
259 |
-
dir_path = self.images_extracted[slide]
|
260 |
-
ext = ".jpg"
|
261 |
-
else:
|
262 |
-
dir_path = self.masks_extracted[slide]
|
263 |
-
ext = ".png"
|
264 |
-
|
265 |
-
return os.path.join(dir_path, slide, basename + ext)
|
266 |
-
|
267 |
-
def images_and_masks(basenames):
|
268 |
-
for bn in basenames:
|
269 |
-
yield build_path(bn), build_path(bn, "masks")
|
270 |
-
|
271 |
-
def images_and_boxes(basenames):
|
272 |
-
for bn in basenames:
|
273 |
-
image_id = self._bn_to_imageid[bn]
|
274 |
-
labels = [
|
275 |
-
{"bbox": annotation["bbox"], "label": annotation["category_id"] - 1}
|
276 |
-
for annotation in self._imageid_to_coco_OD_annotations[image_id]
|
277 |
-
]
|
278 |
-
|
279 |
-
yield build_path(bn), labels
|
280 |
-
|
281 |
-
def images_and_instances(basenames):
|
282 |
-
for bn in basenames:
|
283 |
-
image_id = self._bn_to_imageid[bn]
|
284 |
-
instances = [
|
285 |
-
{
|
286 |
-
"bbox": annotation["bbox"],
|
287 |
-
"label": annotation["category_id"] - 1,
|
288 |
-
"segment": annotation["segmentation"],
|
289 |
-
}
|
290 |
-
for annotation in self._imageid_to_coco_OD_annotations[image_id]
|
291 |
-
]
|
292 |
-
|
293 |
-
yield build_path(bn), instances
|
294 |
-
|
295 |
-
self._download_and_extract_all(dl_manager)
|
296 |
-
|
297 |
-
logger.info("Splitting dataset based on the NORs quantity by image...")
|
298 |
-
train_ids, valid_ids, test_ids = tvt_by_nors(
|
299 |
-
self._ccagt_info, tvt_size=self.config.tvt_size, seed=self.config.seed
|
300 |
-
)
|
301 |
-
train_bn_images = self._ccagt_info.loc[self._ccagt_info["image_id"].isin(train_ids), "image_name"].unique()
|
302 |
-
valid_bn_images = self._ccagt_info.loc[self._ccagt_info["image_id"].isin(valid_ids), "image_name"].unique()
|
303 |
-
test_bn_images = self._ccagt_info.loc[self._ccagt_info["image_id"].isin(test_ids), "image_name"].unique()
|
304 |
-
|
305 |
-
if self.config.name == "semantic_segmentation":
|
306 |
-
train_data = images_and_masks(train_bn_images)
|
307 |
-
valid_data = images_and_masks(valid_bn_images)
|
308 |
-
test_data = images_and_masks(test_bn_images)
|
309 |
-
elif self.config.name == "object_detection":
|
310 |
-
train_data = images_and_boxes(train_bn_images)
|
311 |
-
valid_data = images_and_boxes(valid_bn_images)
|
312 |
-
test_data = images_and_boxes(test_bn_images)
|
313 |
-
elif self.config.name == "instance_segmentation":
|
314 |
-
train_data = images_and_instances(train_bn_images)
|
315 |
-
valid_data = images_and_instances(valid_bn_images)
|
316 |
-
test_data = images_and_instances(test_bn_images)
|
317 |
-
else:
|
318 |
-
raise NotImplementedError
|
319 |
-
|
320 |
-
return [
|
321 |
-
datasets.SplitGenerator(
|
322 |
-
name=datasets.Split.TRAIN,
|
323 |
-
gen_kwargs={"data": train_data},
|
324 |
-
),
|
325 |
-
datasets.SplitGenerator(
|
326 |
-
name=datasets.Split.TEST,
|
327 |
-
gen_kwargs={"data": test_data},
|
328 |
-
),
|
329 |
-
datasets.SplitGenerator(
|
330 |
-
name=datasets.Split.VALIDATION,
|
331 |
-
gen_kwargs={"data": valid_data},
|
332 |
-
),
|
333 |
-
]
|
334 |
-
|
335 |
-
def _generate_examples(self, data):
|
336 |
-
if self.config.name == "semantic_segmentation":
|
337 |
-
for img_path, msk_path in data:
|
338 |
-
img_basename = get_basename(img_path)
|
339 |
-
image_id = self._bn_to_imageid[img_basename]
|
340 |
-
yield image_id, {
|
341 |
-
"image": img_path,
|
342 |
-
"annotation": msk_path,
|
343 |
-
}
|
344 |
-
elif self.config.name == "object_detection":
|
345 |
-
for img_path, labels in data:
|
346 |
-
img_basename = get_basename(img_path)
|
347 |
-
image_id = self._bn_to_imageid[img_basename]
|
348 |
-
yield image_id, {"image": img_path, "objects": labels}
|
349 |
-
elif self.config.name == "instance_segmentation":
|
350 |
-
for img_path, instances in data:
|
351 |
-
img_basename = get_basename(img_path)
|
352 |
-
image_id = self._bn_to_imageid[img_basename]
|
353 |
-
yield image_id, {"image": img_path, "objects": instances}
|
354 |
-
else:
|
355 |
-
raise NotImplementedError
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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