File size: 10,373 Bytes
bb14d6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ebe0faa7",
   "metadata": {},
   "source": [
    "This notebook prepares the datasets for training of the turtle detection model. First, it goes through the SeaTurtleID2022 dataset and converts the existing masks into the YOLO format needed by Ultralytics. Then it goes through the TurtlesOfSMSRC dataset, loads the masks created in the smsrc_prepare notebook and again, converts the masks to the YOLO format. Finally, the metadata are merged together and are ready to use the segmentation_train script, which first trains on SeaTurtleID2022 (photos below water) and then finetunes on the combined dataset (photos above water were added)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2e66c17",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import json\n",
    "import shutil\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from tqdm import tqdm\n",
    "from wildlife_datasets.datasets import SeaTurtleID2022, TurtlesOfSMSRC\n",
    "from wildlife_datasets.datasets.utils import find_images, parse_bbox_mask\n",
    "from wildlife_datasets.splits import ClosedSetSplit\n",
    "from turtle_detector import get_index, rle_to_yolo, uncompressed_rle_to_yolo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93be7212",
   "metadata": {},
   "outputs": [],
   "source": [
    "root_out = f'/data/wildlife_datasets/turtle-detector'\n",
    "\n",
    "for addition in ['images/train', 'images/val', 'labels/train', 'labels/val']:\n",
    "    for dataset_name in ['SeaTurtleID2022', 'TurtlesOfSMSRC']:\n",
    "        os.makedirs(os.path.join(root_out, addition, dataset_name), exist_ok=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14b3e193",
   "metadata": {},
   "source": [
    "# SeaTurtleID2022"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4c664fa1",
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset_name = 'SeaTurtleID2022'\n",
    "root = '/data/wildlife_datasets/data/SeaTurtleID2022'\n",
    "\n",
    "dataset = SeaTurtleID2022(root)\n",
    "if dataset.df['path'].nunique() != len(dataset):\n",
    "    raise ValueError('path is not unique')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64391cd5",
   "metadata": {},
   "outputs": [],
   "source": [
    "splitter = ClosedSetSplit(0.8)\n",
    "idx_train, idx_test = splitter.split(dataset.df)[0]\n",
    "idx_train += 1\n",
    "idx_test += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "057b036e",
   "metadata": {},
   "outputs": [],
   "source": [
    "flipper_categories = {\n",
    "    '': 0,\n",
    "    'front_left': 2,\n",
    "    'front_right': 3,\n",
    "    'rear_left': 4,\n",
    "    'rear_right': 5,\n",
    "}\n",
    "\n",
    "root_ann = f'{root}/turtles-data/data'\n",
    "with open(os.path.join(root_ann, 'annotations.json')) as file:\n",
    "    annotations = json.load(file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7ff91b8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "for ann_img in tqdm(annotations['images']):\n",
    "    file_name = os.path.join(root_ann, ann_img['file_name'])\n",
    "    if ann_img['id'] in idx_train:\n",
    "        shutil.copy(file_name, f'{root_out}/images/train/{dataset_name}')\n",
    "    elif ann_img['id'] in idx_test:\n",
    "        shutil.copy(file_name, f'{root_out}/images/val/{dataset_name}')\n",
    "    else:\n",
    "        raise ValueError('Split wrong')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a5a19846",
   "metadata": {},
   "outputs": [],
   "source": [
    "for ann_ann in tqdm(annotations['annotations']):\n",
    "    if ann_ann['category_id'] == 1:\n",
    "        category_id = 0\n",
    "    elif ann_ann['category_id'] == 3:\n",
    "        category_id = 1\n",
    "    else:\n",
    "        location = ann_ann['attributes'].get('location', '')\n",
    "        category_id = flipper_categories[location]\n",
    "\n",
    "    image_id = ann_ann['image_id']\n",
    "    rle = ann_ann['segmentation']    \n",
    "    yolo_segments = uncompressed_rle_to_yolo(rle, class_id=category_id)\n",
    "    ann_img = annotations['images'][image_id - 1]\n",
    "    base_name = os.path.basename(ann_img['file_name'])\n",
    "    base_name = os.path.splitext(base_name)[0] + '.txt'\n",
    "\n",
    "    if image_id != ann_img['id']:\n",
    "        raise ValueError('Image ids are not ordered')\n",
    "    if ann_img['id'] in idx_train:\n",
    "        file_name = f'{root_out}/labels/train/{dataset_name}/{base_name}'\n",
    "    elif ann_img['id'] in idx_test:\n",
    "        file_name = f'{root_out}/labels/val/{dataset_name}/{base_name}'\n",
    "    else:\n",
    "        raise ValueError('Split wrong')\n",
    "\n",
    "    with open(file_name, 'a') as myfile:\n",
    "        for yolo_segment in yolo_segments:\n",
    "            myfile.write(yolo_segment + '\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65a8b7ce",
   "metadata": {},
   "source": [
    "# TurtlesOfSMSRC"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33d88ac1",
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset_name = 'TurtlesOfSMSRC'\n",
    "root = '/data/wildlife_datasets/TurtlesOfSMSRC'\n",
    "\n",
    "dataset = TurtlesOfSMSRC(root)\n",
    "masks = pd.read_csv(f'{root}/masks.csv')\n",
    "masks['mask'] = masks['mask'].apply(parse_bbox_mask)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e632972b",
   "metadata": {},
   "outputs": [],
   "source": [
    "splitter = ClosedSetSplit(0.8)\n",
    "idx_train, idx_test = splitter.split(dataset.df)[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6acc2bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "annotation_categories = {\n",
    "    'turtle': 0,\n",
    "    'head': 1,\n",
    "    'flipper_fl': 2,\n",
    "    'flipper_fr': 3,\n",
    "    'flipper_rl': 4,\n",
    "    'flipper_rr': 5,\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3377df4",
   "metadata": {},
   "outputs": [],
   "source": [
    "for image_id in tqdm(masks['image_id'].unique()):\n",
    "    i = get_index(dataset, image_id)\n",
    "    file_name = os.path.join(root, dataset.metadata.loc[i, 'path'])\n",
    "    if i in idx_train:\n",
    "        shutil.copy(file_name, f'{root_out}/images/train/{dataset_name}')\n",
    "    elif i in idx_test:\n",
    "        shutil.copy(file_name, f'{root_out}/images/val/{dataset_name}')\n",
    "    else:\n",
    "        raise ValueError('Split wrong')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1eba0f2",
   "metadata": {},
   "outputs": [],
   "source": [
    "for _, mask in tqdm(masks.iterrows(), total=len(masks)):\n",
    "    category_id = annotation_categories[mask['label_side']]\n",
    "    image_id = mask['image_id']\n",
    "    rle = mask['mask']    \n",
    "    yolo_segments = rle_to_yolo(rle, class_id=category_id)\n",
    "    i = get_index(dataset, image_id)\n",
    "\n",
    "    base_name = os.path.basename(dataset.metadata.loc[i, 'path'])\n",
    "    base_name = os.path.splitext(base_name)[0] + '.txt'\n",
    "\n",
    "    if i in idx_train:\n",
    "        file_name = f'{root_out}/labels/train/{dataset_name}/{base_name}'\n",
    "    elif i in idx_test:\n",
    "        file_name = f'{root_out}/labels/val/{dataset_name}/{base_name}'\n",
    "    else:\n",
    "        raise ValueError('Split wrong')\n",
    "\n",
    "    with open(file_name, 'a') as myfile:\n",
    "        for yolo_segment in yolo_segments:\n",
    "            myfile.write(yolo_segment + '\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0b6f6683",
   "metadata": {},
   "source": [
    "# Create metadata"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5908b52",
   "metadata": {},
   "outputs": [],
   "source": [
    "n_repeat = {\n",
    "    'SeaTurtleID2022': 1,\n",
    "    'TurtlesOfSMSRC': 30,\n",
    "}\n",
    "\n",
    "# First split and only then oversample to prevent train-test leak\n",
    "images = find_images(root_out)\n",
    "images = root_out + '/' + images['path'] + '/' + images['file']\n",
    "images_train = images[images.str.contains('/train/')]\n",
    "images_test = images[images.str.contains('/val/')]\n",
    "if len(images_train) + len(images_test) != len(images):\n",
    "    raise ValueError('The split into train and test images failed.')\n",
    "\n",
    "# Oversample (even the test set)\n",
    "idx_train = []\n",
    "idx_test = []\n",
    "for dataset_name in ['SeaTurtleID2022', 'TurtlesOfSMSRC']:\n",
    "    idx_part = list(images_train[images_train.str.contains(dataset_name)].index)\n",
    "    idx_train += n_repeat[dataset_name] * idx_part\n",
    "    idx_part = list(images_test[images_test.str.contains(dataset_name)].index)\n",
    "    idx_test += n_repeat[dataset_name] * idx_part\n",
    "images_train = images_train.loc[idx_train]\n",
    "images_test = images_test.loc[idx_test]\n",
    "\n",
    "# Save the oversampled splits\n",
    "images_train.to_csv(f'{root_out}/train.txt', header=False, index=False)\n",
    "images_test.to_csv(f'{root_out}/val.txt', header=False, index=False)\n",
    "for dataset_name in ['SeaTurtleID2022', 'TurtlesOfSMSRC']:\n",
    "    subset_train = images_train[images_train.str.contains(dataset_name)]\n",
    "    subset_train.to_csv(f'{root_out}/train_{dataset_name}.txt', header=False, index=False)\n",
    "    subset_test = images_test[images_test.str.contains(dataset_name)]\n",
    "    subset_test.to_csv(f'{root_out}/val_{dataset_name}.txt', header=False, index=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "sam3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}