{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":84969,"databundleVersionId":10033515,"sourceType":"competition"},{"sourceId":10126976,"sourceType":"datasetVersion","datasetId":6240276},{"sourceId":10127593,"sourceType":"datasetVersion","datasetId":6240616},{"sourceId":211097053,"sourceType":"kernelVersion"}],"dockerImageVersionId":30805,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!tar xfvz /kaggle/input/ultralytics-for-offline-install/archive.tar.gz\n!pip install --no-index --find-links=./packages ultralytics\n!rm -rf ./packages\n!pip install zarr","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-12-20T10:43:03.834977Z","iopub.execute_input":"2024-12-20T10:43:03.835675Z","iopub.status.idle":"2024-12-20T10:44:14.795185Z","shell.execute_reply.started":"2024-12-20T10:43:03.835611Z","shell.execute_reply":"2024-12-20T10:44:14.794125Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport zarr\nimport os\nfrom ultralytics import YOLO\nimport cv2\nimport pandas as pd\nimport warnings\n\nwarnings.simplefilter('ignore')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T10:44:25.781691Z","iopub.execute_input":"2024-12-20T10:44:25.782075Z","iopub.status.idle":"2024-12-20T10:44:30.342265Z","shell.execute_reply.started":"2024-12-20T10:44:25.782045Z","shell.execute_reply":"2024-12-20T10:44:30.341514Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# choose your model!\nmodel = YOLO(\"/kaggle/input/czii-yolo11-training-baseline-weight-and-others/runs/detect/train/weights/best.pt\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T10:44:33.366917Z","iopub.execute_input":"2024-12-20T10:44:33.367488Z","iopub.status.idle":"2024-12-20T10:44:34.184695Z","shell.execute_reply.started":"2024-12-20T10:44:33.367460Z","shell.execute_reply":"2024-12-20T10:44:34.183723Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"p2i_dict = {\n        'apo-ferritin': 0,\n        'beta-amylase': 1,\n        'beta-galactosidase': 2,\n        'ribosome': 3,\n        'thyroglobulin': 4,\n        'virus-like-particle': 5\n    }\n\ni2p_dict = {\n        0:'apo-ferritin',\n        1:'beta-amylase',\n        2:'beta-galactosidase',\n        3:'ribosome',\n        4:'thyroglobulin',\n        5:'virus-like-particle'\n    }\n\ni2c_dict = {\n        0:'red',\n        1:'green',\n        2:'yellow',\n        3:'black',\n        4:'blue',\n        5:'white'\n    }\n\nparticle_radius = {\n        'apo-ferritin': 60,\n        'beta-amylase': 65,\n        'beta-galactosidase': 90,\n        'ribosome': 150,\n        'thyroglobulin': 130,\n        'virus-like-particle': 135,\n    }","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T10:44:36.884632Z","iopub.execute_input":"2024-12-20T10:44:36.885279Z","iopub.status.idle":"2024-12-20T10:44:36.890381Z","shell.execute_reply.started":"2024-12-20T10:44:36.885248Z","shell.execute_reply":"2024-12-20T10:44:36.889555Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def convert_to_8bit(x):\n    lower, upper = np.percentile(x, (0.5, 99.5))\n    x = np.clip(x, lower, upper)\n    x = (x - x.min()) / (x.max() - x.min() + 1e-12) * 255\n    return x.round().astype(\"uint8\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T10:44:38.921098Z","iopub.execute_input":"2024-12-20T10:44:38.921706Z","iopub.status.idle":"2024-12-20T10:44:38.926222Z","shell.execute_reply.started":"2024-12-20T10:44:38.921672Z","shell.execute_reply":"2024-12-20T10:44:38.925375Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.makedirs(\"/kaggle/working/output_image\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T10:44:40.544083Z","iopub.execute_input":"2024-12-20T10:44:40.544809Z","iopub.status.idle":"2024-12-20T10:44:40.548922Z","shell.execute_reply.started":"2024-12-20T10:44:40.544775Z","shell.execute_reply":"2024-12-20T10:44:40.548031Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.patches as patches\n\ndef plot_bbox_2(EXP_NAME, img_slice, model):\n    if EXP_NAME == 'TS_5_4':\n        mode = 'val'\n    else:\n        mode = 'train'\n        \n    try:\n        df = pd.read_csv(f\"/kaggle/input/czii-yolo-datasets/datasets/czii_det2d/labels/{mode}/{EXP_NAME}_{int(img_slice*10)}.txt\",\n                         delim_whitespace=True, header=None)\n    except:\n        return\n\n    tomogram_path = f\"/kaggle/input/czii-cryo-et-object-identification/train/static/ExperimentRuns/{EXP_NAME}/VoxelSpacing10.000/denoised.zarr\"\n    tomogram = zarr.open(tomogram_path)['0'][:]\n    tomogram = convert_to_8bit(tomogram)\n    a_zero = np.zeros((630, 630))\n    a_zero[:] = tomogram[img_slice]\n    a_inp = np.stack([a_zero]*3, axis=-1)\n    a_inp = cv2.resize(a_inp, (640, 640))\n\n    res = model.predict(a_inp, save=False, imgsz=640, \n                        conf=0.15, device=\"0\", batch=1, verbose=False)\n\n    label_files = os.listdir(f\"/kaggle/input/czii-yolo-datasets/datasets/czii_det2d/labels/{mode}\")\n    label_files = [file for file in label_files if \"_\".join(file.split('_')[:3])==EXP_NAME]\n    \n\n    df.iloc[:, 1] = df.iloc[:, 1]*640\n    df.iloc[:, 2] = df.iloc[:, 2]*640\n    df.iloc[:, 3] = df.iloc[:, 3]*640\n\n    b = df.iloc[:, [1,2]].values.tolist()\n    b = np.array(b)\n\n    \n    image = res[0].orig_img[:, :, 0]\n    fig, ax = plt.subplots(1, 2, tight_layout=True, figsize=(12, 8))\n\n    ax[0].imshow(image)\n    ax[0].axis('off')\n    ax[0].set_title('Predicted')\n\n    for j in range(len(res[0].boxes.cls)):\n        cls = res[0].boxes.cls[j].cpu().numpy()\n        conf = res[0].boxes.conf[j].cpu().numpy()\n\n        xyxy = res[0].boxes.xyxy[j].cpu().numpy()\n        x_min = xyxy[0]\n        y_min = xyxy[1]\n        w = xyxy[2]-xyxy[0]\n        h = xyxy[3]-xyxy[1]\n\n        \n        rect = patches.Rectangle((x_min, y_min), w, h, linewidth=1, edgecolor=i2c_dict[int(cls)], facecolor='none')\n        ax[0].add_patch(rect)\n        ax[0].text(\n            x_min, y_min - 10, f\"{j}\", color=\"white\", fontsize=10,\n            bbox=dict(facecolor=i2c_dict[int(cls)], alpha=0.5)\n        )\n\n        xywh = res[0].boxes.xywh[j].cpu().numpy()\n        x_c = xywh[0]\n        y_c = xywh[1]\n        #lopped_image = image[int(y_min):int(y_min+h), int(x_min):int(x_min+w)]\n        #cv2.imwrite(f\"/kaggle/working/output_image/{EXP_NAME}_{img_slice}_{j}.png\", clopped_image)\n        a = np.array([x_c, y_c])\n        dis = np.linalg.norm(b-a, axis=1)\n        if dis.min() > 5:\n            clopped_image = image[int(y_min):int(y_min+h), int(x_min):int(x_min+w)]\n            cv2.imwrite(f\"/kaggle/working/output_image/{EXP_NAME}_{img_slice}_{j}.png\", clopped_image)\n        \n\n    \n    ax[1].imshow(image)\n    ax[1].axis('off')\n    ax[1].set_title('Target')\n\n    for id, x_c, y_c, w in zip(df.iloc[:, 0].to_numpy(), df.iloc[:, 1].to_numpy(), df.iloc[:, 2].to_numpy(), df.iloc[:, 3].to_numpy()):\n        x_min = x_c - (w/2)\n        y_min = y_c - (w/2)\n\n        rect = patches.Rectangle((x_min*64/63, y_min*64/63), w*64/63, w*64/63, linewidth=1, edgecolor=i2c_dict[int(id)], facecolor='none')\n        ax[1].add_patch(rect)\n        ax[1].text(\n            x_min*64/63, y_min*64/63 - 10, f\"{i2p_dict[int(id)]}\", color=\"white\", fontsize=3,\n            bbox=dict(facecolor=i2c_dict[int(id)], alpha=0.5)\n        )\n    plt.suptitle(f\"{EXP_NAME}: {img_slice}\")\n    plt.axis(\"off\")\n    # plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T10:44:51.896335Z","iopub.execute_input":"2024-12-20T10:44:51.897036Z","iopub.status.idle":"2024-12-20T10:44:51.912581Z","shell.execute_reply.started":"2024-12-20T10:44:51.897004Z","shell.execute_reply":"2024-12-20T10:44:51.911834Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for exp in [\"TS_5_4\", \"TS_69_2\", \"TS_6_4\", \"TS_6_6\", \"TS_73_6\", \"TS_86_3\", \"TS_99_9\"]:\n    for i in range(184):\n        plot_bbox_2(exp, i, model)\n    break","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T10:45:36.426977Z","iopub.execute_input":"2024-12-20T10:45:36.427338Z","execution_failed":"2024-12-20T10:46:15.817Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import shutil\n\n# 圧縮したいフォルダのパス\nfolder_path = \"/kaggle/working/output_image\"\n\n# 出力するZIPファイルのパス（拡張子を含む）\noutput_zip_path = \"/kaggle/working/output_image.zip\"\n\n# フォルダをZIPファイルに圧縮\nshutil.make_archive(output_zip_path.replace(\".zip\", \"\"), 'zip', folder_path)\n\nprint(f\"{folder_path} を {output_zip_path} に圧縮しました。\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}