{"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":"gpu","dataSources":[{"sourceId":30201,"databundleVersionId":2750748,"sourceType":"competition"},{"sourceId":11977273,"sourceType":"datasetVersion","datasetId":7510849},{"sourceId":11987188,"sourceType":"datasetVersion","datasetId":7510607}],"dockerImageVersionId":31041,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install --no-index --find-links /kaggle/input/cellpose-whl --no-deps cellpose fastremap fill_voids roifile","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-05-30T11:17:19.8826Z","iopub.execute_input":"2025-05-30T11:17:19.882883Z","iopub.status.idle":"2025-05-30T11:17:22.699026Z","shell.execute_reply.started":"2025-05-30T11:17:19.882862Z","shell.execute_reply":"2025-05-30T11:17:22.698119Z"}},"outputs":[{"name":"stdout","text":"Looking in links: /kaggle/input/cellpose-whl\nProcessing /kaggle/input/cellpose-whl/cellpose-4.0.3-py3-none-any.whl\nProcessing /kaggle/input/cellpose-whl/fastremap-1.16.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl\nProcessing /kaggle/input/cellpose-whl/fill_voids-2.0.8-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl\nProcessing /kaggle/input/cellpose-whl/roifile-2025.5.10-py3-none-any.whl\nInstalling collected packages: fill_voids, cellpose, roifile, fastremap\nSuccessfully installed cellpose-4.0.3 fastremap-1.16.1 fill_voids-2.0.8 roifile-2025.5.10\n","output_type":"stream"}],"execution_count":1},{"cell_type":"code","source":"from cellpose import models, io\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport cv2\n\nmodel = models.CellposeModel(gpu=True, pretrained_model='/kaggle/input/my-cellpose-models/best_model_0.30468207597732544.pth')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-30T11:17:22.700645Z","iopub.execute_input":"2025-05-30T11:17:22.700876Z","iopub.status.idle":"2025-05-30T11:17:57.041816Z","shell.execute_reply.started":"2025-05-30T11:17:22.700852Z","shell.execute_reply":"2025-05-30T11:17:57.041202Z"}},"outputs":[{"name":"stdout","text":"\n\nWelcome to CellposeSAM, cellpose v\ncellpose version: \t4.0.3 \nplatform:       \tlinux \npython version: \t3.11.11 \ntorch version:  \t2.6.0+cu124! The neural network component of\nCPSAM is much larger than in previous versions and CPU excution is slow. \nWe encourage users to use GPU/MPS if available. \n\n\n","output_type":"stream"}],"execution_count":2},{"cell_type":"code","source":"def rle_encode(img):\n    '''\n    img: numpy array, 1 - foreground, 0 - background\n    Returns run length as string\n    '''\n    pixels = img.flatten()\n    pixels = np.concatenate([[0], pixels, [0]])\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-30T11:17:57.042685Z","iopub.execute_input":"2025-05-30T11:17:57.043133Z","iopub.status.idle":"2025-05-30T11:17:57.047679Z","shell.execute_reply.started":"2025-05-30T11:17:57.043113Z","shell.execute_reply":"2025-05-30T11:17:57.047067Z"}},"outputs":[],"execution_count":3},{"cell_type":"code","source":"test_dir = Path('/kaggle/input/sartorius-cell-instance-segmentation/test')\ntest_files = sorted([f for f in test_dir.iterdir() if f.suffix == '.png']) # 假設圖片是.png格式\n\nsubmission_data = []\n\n\nfor img_path in test_files:\n    img_id = img_path.stem\n    img = io.imread(img_path)\n\n    masks = model.eval(img, tile_overlap=0.5)[0]\n\n    if masks.ndim == 2:\n        num_instances = masks.max()\n        for i in range(1, num_instances + 1):\n            mask_instance = (masks == i).astype(np.uint8)\n            rle = rle_encode(mask_instance)\n            submission_data.append({'id': img_id, 'predicted': rle})\n    else:\n        print(f\"Warning: Unexpected masks dimension for {img_id}. Skipping.\")\n\n\nsubmission_df = pd.DataFrame(submission_data)\n\n\nall_test_ids = [f.stem for f in test_files]\nmissing_ids = set(all_test_ids) - set(submission_df['id'].unique())\nfor img_id in missing_ids:\n    submission_df = pd.concat([submission_df, pd.DataFrame([{'id': img_id, 'predicted': ''}])], ignore_index=True)\n\nsubmission_df = submission_df.sort_values(by='id').reset_index(drop=True)\n\nsubmission_df.to_csv('submission.csv', index=False)\n\nprint(\"Submission file 'submission.csv' created successfully!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-30T11:17:57.048884Z","iopub.execute_input":"2025-05-30T11:17:57.049302Z","iopub.status.idle":"2025-05-30T11:18:12.391598Z","shell.execute_reply.started":"2025-05-30T11:17:57.049285Z","shell.execute_reply":"2025-05-30T11:18:12.391006Z"}},"outputs":[{"name":"stdout","text":"Submission file 'submission.csv' created successfully!\n","output_type":"stream"}],"execution_count":4},{"cell_type":"code","source":"# ✅ 終端輸出資訊\nprint(submission_df.head())\nprint(\"欄位名稱:\", submission_df.columns)\nprint(\"是否有重複 id:\", submission_df['id'].duplicated().any())\nprint(\"是否有 null:\", submission_df.isnull().sum())\nprint(\"是否有空字串以外的空值:\", (submission_df['predicted'].astype(str).str.strip() == '').sum())\nprint(\"id 總數:\", submission_df['id'].nunique(), \"submission 行數:\", len(submission_df))\nprint(\"predicted 欄型別:\", submission_df['predicted'].apply(type).value_counts())\nprint(\"✅ Submission file 'submission.csv' created successfully!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-30T11:18:12.39231Z","iopub.execute_input":"2025-05-30T11:18:12.39252Z","iopub.status.idle":"2025-05-30T11:18:12.409759Z","shell.execute_reply.started":"2025-05-30T11:18:12.392503Z","shell.execute_reply":"2025-05-30T11:18:12.408911Z"}},"outputs":[{"name":"stdout","text":"             id                                          predicted\n0  7ae19de7bc2a  62 12 753 4 761 18 1456 27 2160 26 2864 26 356...\n1  7ae19de7bc2a  216469 16 217173 17 217877 18 218581 19 219285...\n2  7ae19de7bc2a  219136 4 219839 7 220542 10 221247 11 221952 1...\n3  7ae19de7bc2a  220026 1 220727 4 221429 6 222132 8 222837 7 2...\n4  7ae19de7bc2a  220911 7 221612 10 222315 12 223019 12 223723 ...\n欄位名稱: Index(['id', 'predicted'], dtype='object')\n是否有重複 id: True\n是否有 null: id           0\npredicted    0\ndtype: int64\n是否有空字串以外的空值: 0\nid 總數: 3 submission 行數: 268\npredicted 欄型別: predicted\n<class 'str'>    268\nName: count, dtype: int64\n✅ Submission file 'submission.csv' created successfully!\n","output_type":"stream"}],"execution_count":5}]}