{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":98498,"databundleVersionId":12148564,"sourceType":"competition"}],"dockerImageVersionId":31012,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-05-05T09:25:23.990010Z","iopub.execute_input":"2025-05-05T09:25:23.990368Z","iopub.status.idle":"2025-05-05T09:25:28.408679Z","shell.execute_reply.started":"2025-05-05T09:25:23.990335Z","shell.execute_reply":"2025-05-05T09:25:28.407372Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Exploratory data analysis","metadata":{}},{"cell_type":"code","source":"import json\nimport os\nimport matplotlib.pyplot as plt\nimport cv2\nfrom matplotlib.patches import Polygon\nfrom matplotlib.collections import PatchCollection\nimport numpy as np\n\n# Load annotation JSON\njson_path = \"/kaggle/input/garbage-segmentation/garbage_segmentation_dataset/train_json.json\"\nimage_root = \"/kaggle/input/garbage-segmentation/garbage_segmentation_dataset/train\"\n\nwith open(json_path, 'r') as f:\n    coco = json.load(f)\n\n# Create image dict for quick lookup\nimage_dict = {img['id']: img for img in coco['images']}\n\n# Group annotations by image\nfrom collections import defaultdict\nann_by_img = defaultdict(list)\nfor ann in coco['annotations']:\n    ann_by_img[ann['image_id']].append(ann)\n\n# Visualize 10 images\nfig, axs = plt.subplots(5, 2, figsize=(20, 25))\naxs = axs.flatten()\ncount = 0\n\nfor img_id, anns in ann_by_img.items():\n    if count >= 10:\n        break\n    img_info = image_dict[img_id]\n    img_path = os.path.join(image_root, img_info['file_name']).replace('\\\\', '/')\n\n    if not os.path.exists(img_path):\n        continue\n\n    image = cv2.imread(img_path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n    axs[count].imshow(image)\n    axs[count].set_title(img_info.get('file_name', ''))\n\n    patches = []\n    for ann in anns:\n        if 'segmentation' in ann:\n            for seg in ann['segmentation']:\n                poly = Polygon(np.array(seg).reshape(-1, 2), closed=True, edgecolor='red', fill=False, linewidth=2)\n                axs[count].add_patch(poly)\n\n    axs[count].axis('off')\n    count += 1\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-05T09:25:28.409797Z","iopub.execute_input":"2025-05-05T09:25:28.410272Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Submission","metadata":{}},{"cell_type":"code","source":"# Create DataFrame for the submission (image_id, pred_str)\nsubmission_df = pd.DataFrame({\n    \"id\": test_image_ids,  # Add an ID column here\n    \"image_id\": test_image_ids,  # Repeat for consistency\n    \"pred_str\": predictions\n})\n\n# Save the final submission to CSV\nsubmission_df.to_csv(\"submission.csv\", index=False)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**To be noted**\n\nMask Structure:\nEach mask is a 512x512 binary numpy array (0s and 1s). 1 indicates a pixel belonging to the segmented region, and 0 represents the background.\n\nEncoding:\nFlattening the 512x512 mask into a 1D array of 0s and 1s is a standard approach. Then, the flattened list is compressed using zlib (for compression) and base64 (for encoding)\n\nDecoding:\nThe string representation is decoded back into the original 512x512 mask using base64 and zlib decompression.","metadata":{}},{"cell_type":"markdown","source":"Example format:\n\ncsv\n\nid,image_id,pred_str\n\n0,image_1,\"1 abcdefg;2 hijklmn\"\n\n1,image_2,\"\"\n","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}}]}