{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":107469,"databundleVersionId":13024000,"sourceType":"competition"},{"sourceId":470538,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":379586,"modelId":399493}],"dockerImageVersionId":31090,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<div style=\"text-align:center\">\n\n<h1>🔥 PLS UPVOTE if you liked this notebook!</h1>\n<h2>⭐️ Check out our <a href=\"https://www.kaggle.com/models/antonoof/2-top-models/\">TOP MODELS</a> — trained for maximum MAP@50! 💪</h2>\n\n<p>Your support helps improve models & share better content for everyone! 🙏<br>\nLet’s keep pushing the limits of what models can see 🧠📸</p>\n\n<img src=\"https://media.giphy.com/media/XIqCQx02E1U9W/giphy.gif\" style=\"display:block; margin:auto\" />\n\n<p>🧩 Model 1: habijabii.pt<br>\n🎯 Model 2: nadiatriki.pt<br>\n📦 Ensembling predictions, visualizing results, and going for the gold 🥇</p>\n\n<hr>\n\n</div>","metadata":{}},{"cell_type":"code","source":"!pip install ultralytics > /dev/null","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-14T08:59:18.166072Z","iopub.execute_input":"2025-07-14T08:59:18.166542Z","iopub.status.idle":"2025-07-14T09:00:43.422332Z","shell.execute_reply.started":"2025-07-14T08:59:18.166515Z","shell.execute_reply":"2025-07-14T09:00:43.421367Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport cv2\nimport csv\nimport random\nimport matplotlib.pyplot as plt\n\nfrom pathlib import Path\nfrom ultralytics import YOLO","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-14T09:00:43.423691Z","iopub.execute_input":"2025-07-14T09:00:43.424002Z","iopub.status.idle":"2025-07-14T09:00:48.212834Z","shell.execute_reply.started":"2025-07-14T09:00:43.423978Z","shell.execute_reply":"2025-07-14T09:00:48.212316Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load pre-trained YOLO models\nmodel1_path = '/kaggle/input/2-top-models/pytorch/default/1/habijabii.pt'\nmodel2_path = '/kaggle/input/2-top-models/pytorch/default/1/nadiatriki.pt'\n\nmodel1 = YOLO(model1_path, verbose=False)\nmodel2 = YOLO(model2_path, verbose=False)\n\n# Load test images\ntest_images_dir = '/kaggle/input/multi-class-object-detection-challenge/testImages/images'\nimage_files = [f for f in os.listdir(test_images_dir) if f.endswith(('.jpg', '.png'))]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-14T09:00:48.213477Z","iopub.execute_input":"2025-07-14T09:00:48.213730Z","iopub.status.idle":"2025-07-14T09:00:51.827604Z","shell.execute_reply.started":"2025-07-14T09:00:48.213714Z","shell.execute_reply":"2025-07-14T09:00:51.826990Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Helper function to convert prediction results into a submission string\ndef format_boxes(results, class_offset=0):\n    boxes = results.boxes\n    width, height = results.orig_shape[1], results.orig_shape[0]\n\n    if boxes is None or len(boxes) == 0:\n        return \"\"\n\n    parts = []\n    for box in boxes:\n        cls = int(box.cls.cpu().numpy()) + class_offset\n        conf = float(box.conf.cpu().numpy())\n        x_center_abs, y_center_abs, w_abs, h_abs = box.xywh[0].cpu().numpy()\n\n        x_center = x_center_abs / width\n        y_center = y_center_abs / height\n        w = w_abs / width\n        h = h_abs / height\n\n        parts.append(f\"{cls} {conf:.6f} {x_center:.6f} {y_center:.6f} {w:.6f} {h:.6f}\")\n\n    return \" \".join(parts)\n\noutput_rows = []\n\n# Inference on 2 models\nfor img_name in image_files:\n    img_path = os.path.join(test_images_dir, img_name)\n\n    results1 = model1.predict(img_path, conf=1e-6, device=0, verbose=False)[0]\n    results2 = model2.predict(img_path, conf=1e-6, device=0, verbose=False)[0]\n\n    pred_str1 = format_boxes(results1, class_offset=1)\n    pred_str2 = format_boxes(results2, class_offset=0)\n\n    combined_pred_str = (pred_str1 + \" \" + pred_str2).strip()\n    if combined_pred_str == \"\":\n        combined_pred_str = \"no boxes\"\n\n    image_id = os.path.splitext(img_name)[0]\n\n    output_rows.append({\n        \"image_id\": image_id,\n        \"prediction_string\": combined_pred_str\n    })","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-14T09:00:51.828816Z","iopub.execute_input":"2025-07-14T09:00:51.829034Z","iopub.status.idle":"2025-07-14T09:05:31.026914Z","shell.execute_reply.started":"2025-07-14T09:00:51.829018Z","shell.execute_reply":"2025-07-14T09:05:31.026310Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save predictions to CSV for submission\ncsv_path = \"submission.csv\"\nwith open(csv_path, 'w', newline='') as f:\n    writer = csv.DictWriter(f, fieldnames=[\"image_id\", \"prediction_string\"])\n    writer.writeheader()\n    writer.writerows(output_rows)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Visualizations","metadata":{}},{"cell_type":"code","source":"random_images = random.sample(image_files, 10)\n\ndef draw_boxes(image, boxes, color=(0, 255, 0), label_prefix=''):\n    for box in boxes:\n        xyxy = box.xyxy[0].cpu().numpy().astype(int)\n        cls = int(box.cls.cpu().numpy())\n        conf = float(box.conf.cpu().numpy())\n\n        cv2.rectangle(image, (xyxy[0], xyxy[1]), (xyxy[2], xyxy[3]), color, 2)\n        label = f\"{label_prefix}{cls} {conf:.2f}\"\n        cv2.putText(image, label, (xyxy[0], xyxy[1] - 10),\n                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)\n    return image\n\nplt.figure(figsize=(20, 40))\n\nfor i, img_name in enumerate(random_images):\n    img_path = os.path.join(test_images_dir, img_name)\n    img = cv2.imread(img_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n    results1 = model1(img_path)[0]\n    results2 = model2(img_path)[0]\n\n    img_with_boxes = draw_boxes(img.copy(), results1.boxes, color=(0, 255, 0), label_prefix='M1:')\n    img_with_boxes = draw_boxes(img_with_boxes, results2.boxes, color=(255, 0, 0), label_prefix='M2:')\n\n    plt.subplot(5, 2, i+1)\n    plt.imshow(img_with_boxes)\n    plt.title(img_name)\n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-14T09:07:08.422318Z","iopub.execute_input":"2025-07-14T09:07:08.422595Z","iopub.status.idle":"2025-07-14T09:07:43.404522Z","shell.execute_reply.started":"2025-07-14T09:07:08.422576Z","shell.execute_reply":"2025-07-14T09:07:43.403226Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}