{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":19989,"databundleVersionId":1160143,"sourceType":"competition"}],"dockerImageVersionId":31236,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"%%capture\n!pip install ultralytics --no-deps --upgrade","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-12-23T07:16:34.630621Z","iopub.execute_input":"2025-12-23T07:16:34.631224Z","iopub.status.idle":"2025-12-23T07:16:38.019169Z","shell.execute_reply.started":"2025-12-23T07:16:34.631195Z","shell.execute_reply":"2025-12-23T07:16:38.018410Z"},"_kg_hide-output":false},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from ultralytics import YOLO\nmodel = YOLO(\"yolo11s.pt\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-23T07:16:38.020678Z","iopub.execute_input":"2025-12-23T07:16:38.020942Z","iopub.status.idle":"2025-12-23T07:16:46.268878Z","shell.execute_reply.started":"2025-12-23T07:16:38.020901Z","shell.execute_reply":"2025-12-23T07:16:46.268277Z"},"_kg_hide-output":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os, ast, cv2, random\nimport pandas as pd\nfrom tqdm import tqdm\n\nIMG_DIR = \"/kaggle/input/global-wheat-detection/train\"\nOUT_DIR = \"yolo_wheat\"\n\nos.makedirs(f\"{OUT_DIR}/images/train\", exist_ok=True)\nos.makedirs(f\"{OUT_DIR}/images/val\", exist_ok=True)\nos.makedirs(f\"{OUT_DIR}/labels/train\", exist_ok=True)\nos.makedirs(f\"{OUT_DIR}/labels/val\", exist_ok=True)\n\ndf = pd.read_csv(\"/kaggle/input/global-wheat-detection/train.csv\")\n\nimage_ids = df.image_id.unique().tolist()\n\n# 🔥 manual split (NO sklearn)\nrandom.seed(42)\nrandom.shuffle(image_ids)\n\nsplit_idx = int(0.8 * len(image_ids))\ntrain_ids = image_ids[:split_idx]\nval_ids = image_ids[split_idx:]\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-23T07:16:46.269687Z","iopub.execute_input":"2025-12-23T07:16:46.270062Z","iopub.status.idle":"2025-12-23T07:16:46.959145Z","shell.execute_reply.started":"2025-12-23T07:16:46.270035Z","shell.execute_reply":"2025-12-23T07:16:46.958333Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def write_labels(image_id, split):\n    rows = df[df.image_id == image_id]\n    img_path = f\"{IMG_DIR}/{image_id}.jpg\"\n    img = cv2.imread(img_path)\n\n    if img is None:\n        return\n\n    h, w, _ = img.shape\n\n    label_path = f\"{OUT_DIR}/labels/{split}/{image_id}.txt\"\n    with open(label_path, \"w\") as f:\n        for _, r in rows.iterrows():\n            x, y, bw, bh = ast.literal_eval(r[\"bbox\"])\n\n            cx = (x + bw / 2) / w\n            cy = (y + bh / 2) / h\n            bw /= w\n            bh /= h\n\n            f.write(f\"0 {cx} {cy} {bw} {bh}\\n\")\n\n    os.system(f\"cp {img_path} {OUT_DIR}/images/{split}/\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-23T07:16:46.960921Z","iopub.execute_input":"2025-12-23T07:16:46.961267Z","iopub.status.idle":"2025-12-23T07:16:46.966519Z","shell.execute_reply.started":"2025-12-23T07:16:46.961241Z","shell.execute_reply":"2025-12-23T07:16:46.965904Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for img_id in tqdm(train_ids):\n    write_labels(img_id, \"train\")\n\nfor img_id in tqdm(val_ids):\n    write_labels(img_id, \"val\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-23T07:16:46.967485Z","iopub.execute_input":"2025-12-23T07:16:46.967724Z","iopub.status.idle":"2025-12-23T07:18:52.444602Z","shell.execute_reply.started":"2025-12-23T07:16:46.967700Z","shell.execute_reply":"2025-12-23T07:18:52.443981Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"yaml_path = \"/kaggle/working/dataset.yaml\"\nyaml_content = \"\"\"\n    path: yolo_wheat\n    train: images\n    val: images\n    \n    nc: 1\n    names: [\"wheat\"]\n\"\"\"\n\nwith open(yaml_path, \"w\") as f:\n    f.write(yaml_content)\n\nprint(\" dataset.yaml created at /kaggle/working/dataset.yaml\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-23T07:18:52.445548Z","iopub.execute_input":"2025-12-23T07:18:52.445810Z","iopub.status.idle":"2025-12-23T07:18:52.450814Z","shell.execute_reply.started":"2025-12-23T07:18:52.445784Z","shell.execute_reply":"2025-12-23T07:18:52.450125Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.train(\n    data=\"dataset.yaml\",\n    epochs=40,\n    imgsz=1024,\n    batch=12,\n    device=0,\n    optimizer=\"AdamW\",\n    lr0=3e-4,\n    cos_lr=True,\n    amp=True,\n    cache=True,\n    freeze=None,\n    single_cls=True,\n    patience=10,\n    close_mosaic=5,\n    degrees=20,\n    translate=0.2,\n    flipud=0.5,\n    fliplr=0.5\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-23T07:18:52.451799Z","iopub.execute_input":"2025-12-23T07:18:52.452188Z","iopub.status.idle":"2025-12-23T07:25:16.238362Z","shell.execute_reply.started":"2025-12-23T07:18:52.452154Z","shell.execute_reply":"2025-12-23T07:25:16.237737Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from PIL import Image\nimport matplotlib.pyplot as plt\nimport seaborn as sns\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-12-23T07:25:48.328787Z","iopub.execute_input":"2025-12-23T07:25:48.329120Z","iopub.status.idle":"2025-12-23T07:26:05.440566Z","shell.execute_reply.started":"2025-12-23T07:25:48.329090Z","shell.execute_reply":"2025-12-23T07:26:05.439947Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nfrom tqdm import tqdm\n\ntest_df = pd.read_csv(\"/kaggle/input/global-wheat-detection/sample_submission.csv\")\n\npreds = []\n\nfor image_id in tqdm(test_df.image_id):\n    results = model.predict(\n        source=f\"/kaggle/input/global-wheat-detection/test/{image_id}.jpg\",\n        conf=0.25,\n        iou=0.5,\n        verbose=False\n    )[0]\n\n    boxes = results.boxes\n    pred_str = \"\"\n\n    if boxes is not None:\n        for b in boxes:\n            x1, y1, x2, y2 = b.xyxy[0].tolist()\n            conf = b.conf[0].item()\n            w = x2 - x1\n            h = y2 - y1\n            pred_str += f\"{conf:.4f} {int(x1)} {int(y1)} {int(w)} {int(h)} \"\n\n    preds.append(pred_str.strip())\n\ntest_df[\"PredictionString\"] = preds\ntest_df.to_csv(\"submission.csv\", index=False)\n\nprint(\"submission.csv ready ✅\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-23T07:31:33.958612Z","iopub.execute_input":"2025-12-23T07:31:33.958974Z","iopub.status.idle":"2025-12-23T07:31:34.631026Z","shell.execute_reply.started":"2025-12-23T07:31:33.958914Z","shell.execute_reply":"2025-12-23T07:31:34.630225Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-23T07:31:55.452814Z","iopub.execute_input":"2025-12-23T07:31:55.453385Z","iopub.status.idle":"2025-12-23T07:31:55.474461Z","shell.execute_reply.started":"2025-12-23T07:31:55.453353Z","shell.execute_reply":"2025-12-23T07:31:55.473862Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}