Datasets:

Modalities:
Image
Languages:
English
Size:
< 1K
Libraries:
Datasets
License:
File size: 13,195 Bytes
abcc75c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"./figs/IOAI-Logo.png\" alt=\"IOAI Logo\" width=\"200\" height=\"auto\">\n",
    "\n",
    "[IOAI 2025 (Beijing, China), Individual Contest](https://ioai-official.org/china-2025)\n",
    "\n",
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/IOAI-official/IOAI-2025/blob/main/Individual-Contest/Restroom/Restroom.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Restroom Icon Matching\n",
    "\n",
    "## 1. Problem Description\n",
    "\n",
    "This task focuses on training a model to learn the relationship between **male and female restroom icons from the same restroom**. Based on labeled training data, you are required to train a matching model that, given a query image, finds its **cross-gender counterpart** (e.g., match a male icon in its cropped image to its female counterpart in its original image), under the constraint that both icons come from the **same restroom**.\n",
    "\n",
    "For example, for a query image (i.e., a male icon in cropped image) shown below in Fig1, its corresponding counterpart is shown in Fig2 (i.e., a female icon in original image which is from the same restroom).\n",
    "\n",
    "| <img src=\"./figs/Restroom Fig 1.png\" height=\"200\"> | <img src=\"./figs/Restroom Fig 2.png\" height=\"200\"> |\n",
    "| ------------------------------------------------------------ | ------------------------------------------------------------ |\n",
    "\n",
    "\n",
    "\n",
    "## 2. Dataset\n",
    "\n",
    "**(1) Training Set:** \n",
    "\n",
    "Used for model training. Directory structure:\n",
    "\n",
    "```bash\n",
    "train/\n",
    "├── crop/         # Cropped icons\n",
    "│   ├── female/   1.png, 2.png, ...\n",
    "│   └── male/\n",
    "└── orig/         # Original icons\n",
    "    ├── female/\n",
    "    └── male/\n",
    "```\n",
    "\n",
    "Each subfolder contains icons named from `1.png` to `82.png`, where the number indicates the restroom ID. For each restroom, there are four images (note that four images from the same restroom will share one same unique id across all four subfolders):\n",
    "\n",
    "- `crop/female/i.png` → Cropped female icon  \n",
    "- `crop/male/i.png`  → Cropped male icon  \n",
    "- `orig/female/i.png` → Original female icon  \n",
    "- `orig/male/i.png`  → Original male icon  \n",
    "\n",
    "**(2) Validation Set and Test Set:** \n",
    "\n",
    "Either the validation set (test_a) or the test set (test_b) contains two subfolders:\n",
    "\n",
    "```bash\n",
    "test_a/           (or test_b/)\n",
    "├── query/        # Cropped icons to be matched\n",
    "└── gallery/      # Candidate original icons\n",
    "```\n",
    "\n",
    "- `query/`: **cropped** icons that need to be matched.  \n",
    "- `gallery/`: pool of **original** icons to match from.  \n",
    "- Note that:\n",
    "    - Unlike the training split, the filenames in `query/` and `gallery/` are independently numbered and shuffled, which means that matching cannot rely on the ids\n",
    "    - For each cropped icon in `query/` there are exactly two originals in `gallery/` (one male, one female from the same restroom), which means $\\text{len}(\\text{gallery})=2 * \\text{len}(\\text{query})$\n",
    "- All images are in `.png` format. \n",
    "- The validation set has $10$ images in its `query/` folder, and the test set has $30$ images in its `query/` folder.\n",
    "\n",
    "## 3. Task\n",
    "\n",
    "For each image in the `query/` folder, predict the image in `gallery/` that:\n",
    "- Is of the **opposite gender**, and\n",
    "- Comes from the **same restroom**\n",
    "\n",
    "This matching should be accomplished **using your trained model**. \n",
    "\n",
    "## 4. Submission Requirements\n",
    "\n",
    "You must submit a notebook named `submission.ipynb`, which should include:\n",
    "\n",
    "- Model training process (using `train/` data)  \n",
    "- Matching process for both test sets (`test_a/` and `test_b/`)  \n",
    "- The notebook must output two `.npy` files:\n",
    "```bash\n",
    "submission_a.npy     # Matching results for validation set (test_a).\n",
    "submission_b.npy     # Matching results for test set (test_b).\n",
    "```\n",
    "\n",
    "Each npz file is a one-dimensional array with a size equal to the number of queries, and each value in the array corresponds to the image ID in the gallery.\n",
    "\n",
    "For example, one valid `submission_a.npy` may looks like this:\n",
    "<img src=\"./figs/Restroom Fig 3.png\" width=\"300\">\n",
    "\n",
    "You can also find an example output format in [baseline.ipynb](https://ioai.bohrium.com/notebooks/81153159178).\n",
    "\n",
    "## 5. Score\n",
    "\n",
    "- If the submission finishes within the time limit, the score is calculated as:  \n",
    "  $$\n",
    "  \\text{Score} = \\frac{\\text{Number of correct matches}}{\\text{Total queries}}\n",
    "  $$\n",
    "  \n",
    "  which will be a float number between $0.0$ and $1.0$ (inclusive).\n",
    "  \n",
    "- Submissions that exceed the time limit will receive a score of **0**.\n",
    "\n",
    "## 6. Baseline and Training Set\n",
    "\n",
    "- Below you can find the baseline solution.\n",
    "- The dataset is in `training_set` folder. \n",
    "- The highest score by the Scientific Committee for this task is $0.90$ in Leaderboard B,  this score is used for score unification.\n",
    "- The baseline score by the Scientific Committee for this task is $0.77$ in Leaderboard B,  this score is used for score unification.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "import numpy as np\n",
    "import torch\n",
    "\n",
    "seed = 42\n",
    "\n",
    "random.seed(seed)                  # Python built-in random\n",
    "np.random.seed(seed)               # NumPy\n",
    "torch.manual_seed(seed)            # PyTorch (CPU)\n",
    "torch.cuda.manual_seed(seed)       # PyTorch (single GPU)\n",
    "torch.cuda.manual_seed_all(seed)   # PyTorch (all GPUs)\n",
    "\n",
    "# Ensures deterministic behavior\n",
    "torch.backends.cudnn.deterministic = True\n",
    "torch.backends.cudnn.benchmark = False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "I5GTjH_JDD6-"
   },
   "outputs": [],
   "source": [
    "def sort_paths_by_number(path_list):\n",
    "    \"\"\"\n",
    "    Sort based on the numerical values of the filenames in the path,\n",
    "    assuming all filenames can be converted to integers.\n",
    "    \"\"\"\n",
    "    def get_file_number(path):\n",
    "        file_name = os.path.splitext(os.path.basename(path))[0]\n",
    "        return int(file_name)\n",
    "\n",
    "    path_list.sort(key=get_file_number)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "GaCBe4plvK-e",
    "outputId": "b3e76723-7f79-45d7-878b-5619d684e25d",
    "papermill": {
     "duration": 6.61984,
     "end_time": "2022-02-04T11:33:28.148721",
     "exception": false,
     "start_time": "2022-02-04T11:33:21.528881",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import clip-vit model\n",
    "DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
    "absolute_model_path = \"/bohr/clip-lnw6/v2/ViT-B-32.pt\" \n",
    "# The clip-model is deployed automatically in the testing machine. You cannot mounted other pretrained models.\n",
    "# You notebook can access the above model even if you do not mount it along with notebook.\n",
    "\n",
    "# TRAIN_PATH = /bohr/train-s5kb/v1/train\n",
    "# The training set is deployed automatically in the testing machine. \n",
    "# Your notebook can access the TRAIN_PATH even if you do not mount it along with notebook.\n",
    "\n",
    "\n",
    "# import the weights\n",
    "model, preprocess = clip.load(absolute_model_path, device=DEVICE)\n",
    "model.eval()  # evaluation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Eq7CnxKBvK-e",
    "papermill": {
     "duration": 0.034656,
     "end_time": "2022-02-04T11:33:28.209027",
     "exception": false,
     "start_time": "2022-02-04T11:33:28.174371",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def infer(img_paths):\n",
    "    \"\"\"\n",
    "    Compute L2‑normalized feature embeddings for a list of image file paths using the CLIP visual encoder.\n",
    "    \"\"\"\n",
    "    # print(len(img_paths))  # for debug\n",
    "    embeddings = []\n",
    "    for path in tqdm(img_paths):\n",
    "        img = Image.open(path)\n",
    "        x = preprocess(img)\n",
    "        x = x.type(torch.float16).unsqueeze(0).to(DEVICE)\n",
    "\n",
    "        with torch.no_grad():\n",
    "            emb = model.visual.forward(x)\n",
    "\n",
    "        embeddings.append(emb)\n",
    "\n",
    "    embeddings = torch.cat(embeddings)\n",
    "    embeddings = F.normalize(embeddings, p=2, dim=1)\n",
    "\n",
    "    return embeddings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "gPOB1nCkEUoJ"
   },
   "outputs": [],
   "source": [
    "def match_images(BASE_DATA_DIR, result_path):\n",
    "    \"\"\"\n",
    "    For each query image in BASE_DATA_DIR/query, find its best matching image\n",
    "    in BASE_DATA_DIR/gallery by computing cosine similarity of CLIP embeddings,\n",
    "    then save 1‑based match indices to result_path as a .npy file.\n",
    "    \"\"\"\n",
    "    QUERY_DIR = BASE_DATA_DIR / \"query\"\n",
    "    NON_QUERY_DIR = BASE_DATA_DIR / \"gallery\"\n",
    "\n",
    "    query_image_paths = list(QUERY_DIR.glob(\"*.png\"))\n",
    "    non_query_image_paths = list(NON_QUERY_DIR.glob(\"*.png\"))\n",
    "\n",
    "    query_image_paths_str = [str(p) for p in query_image_paths]\n",
    "    non_query_image_paths_str = [str(p) for p in non_query_image_paths]\n",
    "\n",
    "    sort_paths_by_number(query_image_paths_str)\n",
    "    sort_paths_by_number(non_query_image_paths_str)\n",
    "\n",
    "    # print(query_image_paths_str)  # for debug\n",
    "\n",
    "    query_embeddings = infer(query_image_paths_str)\n",
    "    non_query_embeddings = infer(non_query_image_paths_str)\n",
    "    distances = torch.mm(query_embeddings, non_query_embeddings.t())\n",
    "    distances = (distances + 1.) / 2.\n",
    "\n",
    "    topk_dists, topk_idxs = torch.topk(distances, 11, dim=1)  # distances has shape (num_queries, num_non_queries)\n",
    "\n",
    "    topk_dists, topk_idxs = topk_dists.cpu(), topk_idxs.cpu()\n",
    "\n",
    "    matches_dists, matches_idxs = topk_dists[:, 1], topk_idxs[:, 1]\n",
    "    matches_dists = matches_dists.cpu().numpy()\n",
    "    matches_idxs = matches_idxs.cpu().numpy()\n",
    "\n",
    "    for i in range(len(matches_idxs)):\n",
    "        matches_idxs[i]+=1\n",
    "\n",
    "    # print(matches_idxs)  # for debug\n",
    "    np.save(result_path, matches_idxs)  # save as .npy file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "RUtraYPDEz30",
    "outputId": "e0b44045-e6bf-47c3-e89c-e050760c8e50"
   },
   "outputs": [],
   "source": [
    "\"\"\"the generated submission should be two .npy files\"\"\"\n",
    "if os.environ.get('DATA_PATH'):\n",
    "    DATA_PATH = os.environ.get(\"DATA_PATH\") + \"/\" \n",
    "else:\n",
    "    DATA_PATH = \"\"  # Fallback for local testing\n",
    "match_images(Path(DATA_PATH + \"test_a\"),\"submission_a.npy\")\n",
    "match_images(Path(DATA_PATH + \"test_b\"),\"submission_b.npy\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import zipfile\n",
    "\n",
    "files_to_zip = ['./submission_a.npy', './submission_b.npy']\n",
    "zip_filename = 'submission.zip'\n",
    "\n",
    "with zipfile.ZipFile(zip_filename, 'w') as zipf:\n",
    "    for file in files_to_zip:\n",
    "        zipf.write(file, os.path.basename(file))\n",
    "\n",
    "print(f'{zip_filename} is created succefully!')"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "gpuType": "L4",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}