{"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":13361029,"sourceType":"datasetVersion","datasetId":8474812}],"dockerImageVersionId":31154,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install ultralytics --no-deps","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:11:48.653198Z","iopub.execute_input":"2025-11-24T07:11:48.653509Z","iopub.status.idle":"2025-11-24T07:11:53.490992Z","shell.execute_reply.started":"2025-11-24T07:11:48.653483Z","shell.execute_reply":"2025-11-24T07:11:53.490158Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Library Imported","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport os\nimport cv2\nimport shutil\nfrom pathlib import Path\nimport random\nfrom sklearn.model_selection import train_test_split\nfrom ultralytics import YOLO\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport warnings\nwarnings.filterwarnings('ignore')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:11:59.091741Z","iopub.execute_input":"2025-11-24T07:11:59.092707Z","iopub.status.idle":"2025-11-24T07:12:08.002594Z","shell.execute_reply.started":"2025-11-24T07:11:59.092672Z","shell.execute_reply":"2025-11-24T07:12:08.001745Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Visualize train image sample","metadata":{}},{"cell_type":"code","source":"train_images_dir = Path(\"/kaggle/input/dengu-image-dataset/Dengu Images/train/images\")\n\nimage_files = list(train_images_dir.glob(\"*.jpg\"))\n\nsample_files = random.sample(image_files, min(9, len(image_files)))\n\nfig, axes = plt.subplots(3, 3, figsize=(20, 12))\naxes = axes.flatten()\n\nfor ax, img_path in zip(axes, sample_files):\n    img = cv2.imread(str(img_path))                  \n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)       \n    ax.imshow(img)\n    ax.axis(\"off\")\n    ax.set_title(img_path.name, fontsize=20)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:12:08.003991Z","iopub.execute_input":"2025-11-24T07:12:08.004350Z","iopub.status.idle":"2025-11-24T07:12:10.021988Z","shell.execute_reply.started":"2025-11-24T07:12:08.004314Z","shell.execute_reply":"2025-11-24T07:12:10.021143Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class_img = { 1: \"Dengue\"}\n\ndef plot_with_boxes(image_path,label_path):\n    image = cv2.imread(image_path)\n    height, width = image.shape[:2]\n    \n    with open(label_path, \"r\") as f:\n        lines = f.readlines()\n    \n    for line in lines:\n        class_id, x_center, y_center, w, h = map(float, line.strip().split())\n        \n        # Convert normalized coords to pixel values\n        x_center *= width\n        y_center *= height\n        w *= width\n        h *= height\n    \n        # Get top-left and bottom-right\n        x1 = int(x_center - w / 2)\n        y1 = int(y_center - h / 2)\n        x2 = int(x_center + w / 2)\n        y2 = int(y_center + h / 2)\n    \n        # Draw rectangle\n        cv2.rectangle(image, (x1, y1), (x2, y2),(235, 52, 16), 6)\n        cv2.putText(image, f\"{class_img[class_id]}\", (x1, y1 - 10),\n                    cv2.FONT_HERSHEY_SIMPLEX, 3, (224, 16, 34), 2)\n    \n    return image","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:12:22.944870Z","iopub.execute_input":"2025-11-24T07:12:22.945628Z","iopub.status.idle":"2025-11-24T07:12:22.951726Z","shell.execute_reply.started":"2025-11-24T07:12:22.945602Z","shell.execute_reply":"2025-11-24T07:12:22.950981Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# train and Val image show with boxes","metadata":{}},{"cell_type":"code","source":"# train_images_dir = Path(\"/kaggle/input/dengu-image-dataset/Dengu Images/train/images\")\n# train_label_dir = Path(\"/kaggle/input/dengu-image-dataset/Dengu Images/train/labels\")\n\n# image_files = list(train_images_dir.glob(\"*.jpg\"))\n\n# valid_images = [img for img in image_files if (train_label_dir / f\"{img.stem}.txt\").exists()]\n\n# sample_files = random.sample(valid_images, min(6, len(valid_images)))\n\n# fig, axes = plt.subplots(3, 2, figsize=(20, 12))\n# axes = axes.flatten()\n\n# for ax, img_path in zip(axes, sample_files):\n#     label_path = train_label_dir / f\"{img_path.stem}.txt\"\n#     image_with_boxes = plot_with_boxes(img_path, label_path)\n#     image_with_boxes = cv2.cvtColor(image_with_boxes, cv2.COLOR_BGR2RGB)\n    \n#     ax.imshow(image_with_boxes)\n#     ax.axis(\"off\")\n#     ax.set_title(img_path.name, fontsize=12)\n\n# plt.tight_layout()\n# plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T13:32:50.918236Z","iopub.execute_input":"2025-10-29T13:32:50.918775Z","iopub.status.idle":"2025-10-29T13:32:50.922399Z","shell.execute_reply.started":"2025-10-29T13:32:50.918753Z","shell.execute_reply":"2025-10-29T13:32:50.921591Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Create dataset.yaml ","metadata":{}},{"cell_type":"code","source":"yaml_path = \"/kaggle/working/dataset.yaml\"\nyaml_content = \"\"\"\ntrain: /kaggle/input/dengu-image-dataset/Dengu Images/train\nval: /kaggle/input/dengu-image-dataset/Dengu Images/valid\n\nnc: 2\nnames: \n    0: Dengue\n    1: Normal\n    \n\"\"\"\n\nwith open(yaml_path, \"w\") as f:\n    f.write(yaml_content)\n\nprint(\" dataset.yaml created at /kaggle/working/dataset.yaml\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:13:53.568001Z","iopub.execute_input":"2025-11-24T07:13:53.568327Z","iopub.status.idle":"2025-11-24T07:13:53.574505Z","shell.execute_reply.started":"2025-11-24T07:13:53.568296Z","shell.execute_reply":"2025-11-24T07:13:53.573674Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Visualization train image with bounding boxes yaml","metadata":{}},{"cell_type":"code","source":"import yaml\n\nbase_dir = \"/kaggle/input/dengu-image-dataset/Dengu Images/train\"\nimages_dir = os.path.join(base_dir, \"images\")\nlabels_dir = os.path.join(base_dir, \"labels\")\n\nwith open(\"/kaggle/working/dataset.yaml\", \"r\") as f:\n    data_yaml = yaml.safe_load(f)\nclass_names = data_yaml.get(\"names\", [])\n\ndef plot_image_with_boxes(img_path, label_path):\n    img = cv2.imread(img_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    h, w, _ = img.shape\n\n    if not os.path.exists(label_path):\n        return img\n\n    with open(label_path, \"r\") as f:\n        for line in f:\n            parts = line.strip().split()\n            if len(parts) < 5:\n                continue\n            cls_id, x_center, y_center, bw, bh = map(float, parts[:5])\n            cls_id = int(cls_id)\n            \n            x_center, y_center, bw, bh = x_center * w, y_center * h, bw * w, bh * h\n            x1, y1 = int(x_center - bw / 2), int(y_center - bh / 2)\n            x2, y2 = int(x_center + bw / 2), int(y_center + bh / 2)\n\n            color = (random.randint(0,255), random.randint(0,255), random.randint(0,255))\n            cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)\n            label = class_names[cls_id] if cls_id < len(class_names) else str(cls_id)\n            cv2.putText(img, label, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 2, color, 2)\n\n    return img\n    \n\nshown_classes = set()\n\nplt.figure(figsize=(16, 12))\n\nfor img_file in os.listdir(images_dir):\n    if len(shown_classes) == len(class_names):\n        break\n\n    img_name = os.path.splitext(img_file)[0]\n    label_file = os.path.join(labels_dir, f\"{img_name}.txt\")\n\n    if not os.path.exists(label_file):\n        continue\n\n    with open(label_file, \"r\") as f:\n        for line in f:\n            cls_id = int(line.strip().split()[0])\n            if cls_id not in shown_classes:\n                img_path = os.path.join(images_dir, img_file)\n                img = plot_image_with_boxes(img_path, label_file)  # called the funtion\n\n                plt.subplot(1, (len(class_names)), cls_id + 1)\n                plt.imshow(img)\n                plt.title(class_names[cls_id] if cls_id < len(class_names) else f\"Class {cls_id}\")\n                plt.axis(\"off\")\n\n                shown_classes.add(cls_id)\n                break\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:16:37.205258Z","iopub.execute_input":"2025-11-24T07:16:37.205653Z","iopub.status.idle":"2025-11-24T07:16:38.116785Z","shell.execute_reply.started":"2025-11-24T07:16:37.205620Z","shell.execute_reply":"2025-11-24T07:16:38.115771Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# YOLO11s model training","metadata":{}},{"cell_type":"code","source":"# train.py\nimport os\nfrom ultralytics import YOLO\nmodel = YOLO('yolo11s.pt')\n\n\nmodel.train(\n        data=\"/kaggle/working/dataset.yaml\",\n        epochs=50,\n        imgsz=640,\n        batch=32,\n        optimizer='AdamW',\n        lr0=0.01,\n        lrf=0.01,\n        weight_decay=5e-4,\n        warmup_epochs=5,\n        patience=20,\n        exist_ok=True,\n        augment=True,\n        workers=8, \n        device=0,\n        verbose=False\n    )\nprint(\"Training complete. Best model saved.\")\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:21:41.522694Z","iopub.execute_input":"2025-11-24T07:21:41.523674Z","iopub.status.idle":"2025-11-24T07:23:43.201190Z","shell.execute_reply.started":"2025-11-24T07:21:41.523629Z","shell.execute_reply":"2025-11-24T07:23:43.200305Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.val","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-29T13:38:40.019401Z","iopub.execute_input":"2025-10-29T13:38:40.020376Z","iopub.status.idle":"2025-10-29T13:38:40.029997Z","shell.execute_reply.started":"2025-10-29T13:38:40.020349Z","shell.execute_reply":"2025-10-29T13:38:40.029163Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Model saved","metadata":{}},{"cell_type":"code","source":"# Save the trained model\nmodel.save('yolov11_trained.pt')\nprint(\"Model trained and saved successfully!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:24:30.149178Z","iopub.execute_input":"2025-11-24T07:24:30.150255Z","iopub.status.idle":"2025-11-24T07:24:30.319073Z","shell.execute_reply.started":"2025-11-24T07:24:30.150229Z","shell.execute_reply":"2025-11-24T07:24:30.318384Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"post_training_files_path ='/kaggle/working/runs/detect/train'\n\n# List the files in the directory\n!ls {post_training_files_path}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:24:34.029847Z","iopub.execute_input":"2025-11-24T07:24:34.030372Z","iopub.status.idle":"2025-11-24T07:24:34.230297Z","shell.execute_reply.started":"2025-11-24T07:24:34.030330Z","shell.execute_reply":"2025-11-24T07:24:34.229525Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# After trained Detect Images","metadata":{}},{"cell_type":"code","source":"from PIL import Image\n\n# Define the path to the directory containing the images\n#image_directory = \"/kaggle/working/runs/detect/train2\"\nimage_directory ='/kaggle/working/runs/detect/train'\n\n# Iterate through all image files in the directory\nfor filename in os.listdir(image_directory):\n    if filename.lower().endswith((\".jpg\",\".png\")):\n        image_path = os.path.join(image_directory, filename)\n        image = Image.open(image_path)\n\n        # Display the image\n        plt.figure(figsize=(12, 12), dpi=150)\n        plt.imshow(image)\n        plt.title(f\"Image: {filename}\", fontsize=20, fontweight='bold', color='blue')  # Customize font properties\n        plt.axis(\"off\")  # Hide axes\n        plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:24:37.518702Z","iopub.execute_input":"2025-11-24T07:24:37.519042Z","iopub.status.idle":"2025-11-24T07:24:51.524302Z","shell.execute_reply.started":"2025-11-24T07:24:37.519014Z","shell.execute_reply":"2025-11-24T07:24:51.523236Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Result_Final_model = pd.read_csv('/kaggle/working/runs/detect/train/results.csv')\nResult_Final_model.tail(10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:25:53.432062Z","iopub.execute_input":"2025-11-24T07:25:53.432688Z","iopub.status.idle":"2025-11-24T07:25:53.494925Z","shell.execute_reply.started":"2025-11-24T07:25:53.432661Z","shell.execute_reply":"2025-11-24T07:25:53.494058Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# After trained Metrics and Loss","metadata":{}},{"cell_type":"code","source":"# Read the results.csv file as a pandas dataframe,\nResult_Final_model.columns = Result_Final_model.columns.str.strip()\n\n# Create subplots\nfig, axs = plt.subplots(nrows=5, ncols=2, figsize=(15, 15))\n\n# Plot the columns using seaborn\nsns.lineplot(x='epoch', y='train/box_loss', data=Result_Final_model, ax=axs[0,0])\nsns.lineplot(x='epoch', y='train/cls_loss', data=Result_Final_model, ax=axs[0,1])\nsns.lineplot(x='epoch', y='train/dfl_loss', data=Result_Final_model, ax=axs[1,0])\nsns.lineplot(x='epoch', y='metrics/precision(B)', data=Result_Final_model, ax=axs[1,1])\nsns.lineplot(x='epoch', y='metrics/recall(B)', data=Result_Final_model, ax=axs[2,0])\nsns.lineplot(x='epoch', y='metrics/mAP50(B)', data=Result_Final_model, ax=axs[2,1])\nsns.lineplot(x='epoch', y='metrics/mAP50-95(B)', data=Result_Final_model, ax=axs[3,0])\nsns.lineplot(x='epoch', y='val/box_loss', data=Result_Final_model, ax=axs[3,1])\nsns.lineplot(x='epoch', y='val/cls_loss', data=Result_Final_model, ax=axs[4,0])\nsns.lineplot(x='epoch', y='val/dfl_loss', data=Result_Final_model, ax=axs[4,1])\n\n# Set titles and axis labels for each subplot\naxs[0,0].set(title='Train Box Loss')\naxs[0,1].set(title='Train Class Loss')\naxs[1,0].set(title='Train DFL Loss')\naxs[1,1].set(title='Metrics Precision (B)')\naxs[2,0].set(title='Metrics Recall (B)')\naxs[2,1].set(title='Metrics mAP50 (B)')\naxs[3,0].set(title='Metrics mAP50-95 (B)')\naxs[3,1].set(title='Validation Box Loss')\naxs[4,0].set(title='Validation Class Loss')\naxs[4,1].set(title='Validation DFL Loss')\n\n\nplt.suptitle('Training Metrics and Loss', fontsize=24)\nplt.subplots_adjust(top=0.8)\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:26:26.057071Z","iopub.execute_input":"2025-11-24T07:26:26.057422Z","iopub.status.idle":"2025-11-24T07:26:27.704758Z","shell.execute_reply.started":"2025-11-24T07:26:26.057396Z","shell.execute_reply":"2025-11-24T07:26:27.703900Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Loading the best performing model\nValid_model = YOLO('/kaggle/working/runs/detect/train/weights/best.pt')\n\n# Evaluating the model on the validset\nmetrics = Valid_model.val(split = 'val')\n\n# final results \nprint(\"precision(B): \", metrics.results_dict[\"metrics/precision(B)\"])\nprint(\"metrics/recall(B): \", metrics.results_dict[\"metrics/recall(B)\"])\nprint(\"metrics/mAP50(B): \", metrics.results_dict[\"metrics/mAP50(B)\"])\nprint(\"metrics/mAP50-95(B): \", metrics.results_dict[\"metrics/mAP50-95(B)\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:26:34.897198Z","iopub.execute_input":"2025-11-24T07:26:34.897845Z","iopub.status.idle":"2025-11-24T07:26:45.902866Z","shell.execute_reply.started":"2025-11-24T07:26:34.897819Z","shell.execute_reply":"2025-11-24T07:26:45.902065Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Test the prediction for test images","metadata":{}},{"cell_type":"code","source":"original_images_path = Path('/kaggle/input/dengu-image-dataset/Dengu Images/test/images')\n\nclass_names = ['Dengue','Normal']\n\nimage_files = sorted([f for f in original_images_path.iterdir() if f.suffix.lower() == '.jpg'])\nprediction_string =[]\n\nstep = max(1, len(image_files) // 10)\nselected_images = image_files[::step][:10]\n\nrows = len(selected_images)\nfig, axes = plt.subplots(rows, 1, figsize=(15, rows * 4))\n\ntest_model = YOLO(\"/kaggle/working/runs/detect/train/weights/best.pt\")\n\nfor i, img_path in enumerate(selected_images):\n    results = test_model.predict(source=str(img_path), imgsz=640, conf=0.5)\n    \n    print(f\"{img_path.name}: Detected boxes count: {len(results[0].boxes)}\")\n\n    pred_annotated = results[0].plot(line_width=3)\n    pred_annotated_rgb = cv2.cvtColor(pred_annotated, cv2.COLOR_BGR2RGB)\n\n    axes[i].imshow(pred_annotated_rgb)\n    axes[i].set_title(f\"Predictions - {img_path.name}\", fontsize=12)\n    axes[i].axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-24T07:27:10.209792Z","iopub.execute_input":"2025-11-24T07:27:10.210111Z","iopub.status.idle":"2025-11-24T07:27:12.315489Z","shell.execute_reply.started":"2025-11-24T07:27:10.210088Z","shell.execute_reply":"2025-11-24T07:27:12.314398Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Submission","metadata":{}},{"cell_type":"code","source":"# sub = pd.read_csv('/kaggle/input/the-3lc-cotton-weed-detection-challenge/cotton_weed_competition_dataset/sample_submission.csv')\n# sub.shape","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # Load model\n# model = YOLO(\"/kaggle/working/runs/detect/train/weights/best.pt\")\n\n# # Test images folder\n# test_images_path = Path('/kaggle/input/the-3lc-cotton-weed-detection-challenge/cotton_weed_competition_dataset/test/images')\n\n# # All test images\n# image_files = sorted([f for f in test_images_path.iterdir() if f.suffix.lower() in ['.jpg', '.jpeg', '.png']])\n\n# # Class names\n# class_names = ['carpetweed', 'morningglory', 'palmer_amaranth']\n\n# submission_rows = []\n\n# # Predict loop\n# for img_path in image_files:\n#     results = model.predict(source=str(img_path), imgsz=640, conf=0.45, verbose=False)\n#     boxes = results[0].boxes\n    \n#     if boxes is None or len(boxes) == 0:\n#         pred_str = \"no box\"\n#     else:\n#         preds = []\n#         for box in boxes:\n#             cls = int(box.cls.cpu().numpy()[0])\n#             conf = float(box.conf.cpu().numpy()[0])\n#             x1, y1, x2, y2 = box.xyxy.cpu().numpy()[0]\n            \n#             # Convert to normalized format (x_center, y_center, width, height)\n#             x_center = ((x1 + x2) / 2) / results[0].orig_shape[1]\n#             y_center = ((y1 + y2) / 2) / results[0].orig_shape[0]\n#             w = (x2 - x1) / results[0].orig_shape[1]\n#             h = (y2 - y1) / results[0].orig_shape[0]\n            \n#             preds.append(f\"{cls} {conf:.3f} {x_center:.3f} {y_center:.3f} {w:.3f} {h:.3f}\")\n        \n#         pred_str = \" \".join(preds)\n    \n#     image_id = img_path.stem  # remove .jpg\n#     submission_rows.append({\"image_id\": image_id, \"prediction_string\": pred_str})\n\n# # Convert to DataFrame\n# submission_df = pd.DataFrame(submission_rows)\n# submission_df.to_csv(\"submission.csv\", index=False)\n\n# print(\"✅ submission.csv saved successfully!\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# submission_df.head()","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}