{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install  ultralytics","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T17:56:38.060271Z","iopub.execute_input":"2026-06-13T17:56:38.061237Z","iopub.status.idle":"2026-06-13T17:56:41.909057Z","shell.execute_reply.started":"2026-06-13T17:56:38.061199Z","shell.execute_reply":"2026-06-13T17:56:41.908221Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Import Libraries","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport ast\nimport os\nimport shutil\nimport random\nimport torch\nimport cv2\nfrom glob import glob\nfrom ultralytics import YOLO\nfrom PIL import Image\nfrom IPython.display import display","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T17:30:03.844425Z","iopub.execute_input":"2026-06-13T17:30:03.845249Z","iopub.status.idle":"2026-06-13T17:30:04.360597Z","shell.execute_reply.started":"2026-06-13T17:30:03.845210Z","shell.execute_reply":"2026-06-13T17:30:04.359610Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load Data\n\ndf = pd.read_csv('/kaggle/input/competitions/tensorflow-great-barrier-reef/train.csv')\nprint(df.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T17:57:36.830643Z","iopub.execute_input":"2026-06-13T17:57:36.831171Z","iopub.status.idle":"2026-06-13T17:57:36.869982Z","shell.execute_reply.started":"2026-06-13T17:57:36.831134Z","shell.execute_reply":"2026-06-13T17:57:36.869151Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Convert CSV Annotations -> YOLO Labels\n\nCSV_PATH = \"/kaggle/input/competitions/tensorflow-great-barrier-reef/train.csv\"\nIMG_ROOT = \"/kaggle/input/competitions/tensorflow-great-barrier-reef/train_images\"\n\n# Output folders\nos.makedirs(\"/kaggle/working/dataset/images\", exist_ok=True)\nos.makedirs(\"/kaggle/working/dataset/labels\", exist_ok=True)\n\ndf = pd.read_csv(CSV_PATH)\n\ncount = 0\n\nfor _, row in df.iterrows():\n\n    # Skip images without annotations\n    if row[\"annotations\"] == \"[]\":\n        continue\n\n    image_path = f\"{IMG_ROOT}/video_{row.video_id}/{row.video_frame}.jpg\"\n\n    if not os.path.exists(image_path):\n        continue\n\n    img = Image.open(image_path)\n    w, h = img.size\n\n    image_name = f\"{row.video_id}_{row.video_frame}\"\n\n    anns = ast.literal_eval(row[\"annotations\"])\n\n    # Copy image\n    os.system(\n        f'cp \"{image_path}\" \"/kaggle/working/dataset/images/{image_name}.jpg\"'\n    )\n\n    # Create YOLO label file\n    with open(f\"/kaggle/working/dataset/labels/{image_name}.txt\", \"w\") as f:\n        for ann in anns:\n\n            x = ann[\"x\"]\n            y = ann[\"y\"]\n            bw = ann[\"width\"]\n            bh = ann[\"height\"]\n\n            xc = (x + bw/2) / w\n            yc = (y + bh/2) / h\n            bw = bw / w\n            bh = bh / h\n\n            f.write(f\"0 {xc} {yc} {bw} {bh}\\n\")\n\n    count += 1\n\nprint(\"Converted Images:\", count)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T17:57:44.994594Z","iopub.execute_input":"2026-06-13T17:57:44.995447Z","iopub.status.idle":"2026-06-13T17:58:26.655319Z","shell.execute_reply.started":"2026-06-13T17:57:44.995415Z","shell.execute_reply":"2026-06-13T17:58:26.654557Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Create Images & Labels Folder \n\ndf = pd.read_csv('/kaggle/input/competitions/tensorflow-great-barrier-reef/train.csv')\n\nos.makedirs(\"/kaggle/input/competitions/tensorflow-great-barrier-reef/train_images\", exist_ok=True)\nos.makedirs(\"dataset/train/labels\", exist_ok=True)\n\nfor _, row in df.iterrows():\n\n    image_path = f\"/kaggle/input/tensorflow-great-barrier-reef/train_images/video_{row.video_id}/{row.video_frame}.jpg\"\n\n    if not os.path.exists(image_path):\n        continue\n\n    img = Image.open(image_path)\n    w, h = img.size\n\n    label_file = f\"dataset/train/labels/{row.video_id}_{row.video_frame}.txt\"\n\n    anns = ast.literal_eval(row.annotations)\n\n    with open(label_file, \"w\") as f:\n        for ann in anns:\n            x = ann['x']\n            y = ann['y']\n            bw = ann['width']\n            bh = ann['height']\n\n            xc = (x + bw/2) / w\n            yc = (y + bh/2) / h\n            bw /= w\n            bh /= h\n\n            f.write(f\"0 {xc} {yc} {bw} {bh}\\n\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T17:58:59.745352Z","iopub.execute_input":"2026-06-13T17:58:59.745986Z","iopub.status.idle":"2026-06-13T17:59:00.951335Z","shell.execute_reply.started":"2026-06-13T17:58:59.745954Z","shell.execute_reply":"2026-06-13T17:59:00.950401Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train and Valid Split\n\nrandom.seed(42)\n\nimages = glob(\"/kaggle/working/dataset/images/*.jpg\")\nrandom.shuffle(images)\n\nsplit = int(len(images) * 0.8)\n\ntrain_imgs = images[:split]\nvalid_imgs = images[split:]\n\nfor folder in [\n    \"/kaggle/working/cots_yolo/train/images\",\n    \"/kaggle/working/cots_yolo/train/labels\",\n    \"/kaggle/working/cots_yolo/valid/images\",\n    \"/kaggle/working/cots_yolo/valid/labels\"\n]:\n    os.makedirs(folder, exist_ok=True)\n\nfor img in train_imgs:\n    name = os.path.basename(img)\n    label = img.replace(\"/images/\", \"/labels/\").replace(\".jpg\", \".txt\")\n\n    shutil.copy(img, f\"/kaggle/working/cots_yolo/train/images/{name}\")\n    shutil.copy(label, f\"/kaggle/working/cots_yolo/train/labels/{name.replace('.jpg','.txt')}\")\n\nfor img in valid_imgs:\n    name = os.path.basename(img)\n    label = img.replace(\"/images/\", \"/labels/\").replace(\".jpg\", \".txt\")\n\n    shutil.copy(img, f\"/kaggle/working/cots_yolo/valid/images/{name}\")\n    shutil.copy(label, f\"/kaggle/working/cots_yolo/valid/labels/{name.replace('.jpg','.txt')}\")\n\nprint(\"Train:\", len(train_imgs))\nprint(\"Valid:\", len(valid_imgs))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T17:59:07.400456Z","iopub.execute_input":"2026-06-13T17:59:07.401494Z","iopub.status.idle":"2026-06-13T17:59:10.179609Z","shell.execute_reply.started":"2026-06-13T17:59:07.401442Z","shell.execute_reply":"2026-06-13T17:59:10.178946Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# CREATE data.yaml file \n\nwith open(\"/kaggle/working/data.yaml\", \"w\") as f:\n    f.write(\"\"\"\npath: /kaggle/working/cots_yolo\n\ntrain: train/images\nval: valid/images\n\nnc: 1\n\nnames:\n  0: starfish\n\"\"\")\n\nprint(\"data.yaml created\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T17:59:54.844437Z","iopub.execute_input":"2026-06-13T17:59:54.845203Z","iopub.status.idle":"2026-06-13T17:59:54.851038Z","shell.execute_reply.started":"2026-06-13T17:59:54.845169Z","shell.execute_reply":"2026-06-13T17:59:54.850136Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Verify Dataset\n\nfrom glob import glob\n\nprint(\"Train Images:\", len(glob(\"/kaggle/working/cots_yolo/train/images/*\")))\nprint(\"Train Labels:\", len(glob(\"/kaggle/working/cots_yolo/train/labels/*.txt\")))\n\nprint(\"Valid Images:\", len(glob(\"/kaggle/working/cots_yolo/valid/images/*\")))\nprint(\"Valid Labels:\", len(glob(\"/kaggle/working/cots_yolo/valid/labels/*.txt\")))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T18:00:51.186162Z","iopub.execute_input":"2026-06-13T18:00:51.186597Z","iopub.status.idle":"2026-06-13T18:00:51.211591Z","shell.execute_reply.started":"2026-06-13T18:00:51.186554Z","shell.execute_reply":"2026-06-13T18:00:51.210964Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Check GPU\n\nprint(torch.cuda.is_available())\nprint(torch.cuda.get_device_name(0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T16:28:53.113371Z","iopub.execute_input":"2026-06-13T16:28:53.113864Z","iopub.status.idle":"2026-06-13T16:28:53.423356Z","shell.execute_reply.started":"2026-06-13T16:28:53.113827Z","shell.execute_reply":"2026-06-13T16:28:53.422649Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train Yolo Model\n\nfrom ultralytics import YOLO\nmodel = YOLO(\"yolov8n.pt\")\n\nresults = model.train(\n    data=\"data.yaml\",\n    epochs=20,\n    imgsz=640,\n    batch=16,\n    device=0,\n    cache=True,\n    workers=2\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T18:05:59.718352Z","iopub.execute_input":"2026-06-13T18:05:59.718904Z","iopub.status.idle":"2026-06-13T18:21:27.583475Z","shell.execute_reply.started":"2026-06-13T18:05:59.718861Z","shell.execute_reply":"2026-06-13T18:21:27.582652Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#  IMAGE DETECTION\n\nmodel = YOLO(\"/kaggle/working/runs/detect/train/weights/best.pt\")\n\nresults = model.predict(\n    source=\"/kaggle/working/cots_yolo/valid/images/1_8663.jpg\",\n    conf=0.25,\n    save=True,\n    imgsz=640\n)\n\nprint(\"Detection completed\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T18:22:20.423917Z","iopub.execute_input":"2026-06-13T18:22:20.424866Z","iopub.status.idle":"2026-06-13T18:22:20.783313Z","shell.execute_reply.started":"2026-06-13T18:22:20.424821Z","shell.execute_reply":"2026-06-13T18:22:20.782461Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pip install ultralytics","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T18:22:24.787401Z","iopub.execute_input":"2026-06-13T18:22:24.788350Z","iopub.status.idle":"2026-06-13T18:22:28.663980Z","shell.execute_reply.started":"2026-06-13T18:22:24.788298Z","shell.execute_reply":"2026-06-13T18:22:28.662942Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Model Evaluation \n\nfrom ultralytics import YOLO\nmodel = YOLO(\"/kaggle/working/runs/detect/train/weights/best.pt\")\n\nmetrics = model.val(data=\"/kaggle/working/data.yaml\")\n\nprint(metrics)","metadata":{"trusted":true,"collapsed":true,"jupyter":{"outputs_hidden":true},"execution":{"iopub.status.busy":"2026-06-13T18:22:34.052838Z","iopub.execute_input":"2026-06-13T18:22:34.053633Z","iopub.status.idle":"2026-06-13T18:22:46.748978Z","shell.execute_reply.started":"2026-06-13T18:22:34.053594Z","shell.execute_reply":"2026-06-13T18:22:46.748084Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict on Validation Images\n\nfrom ultralytics import YOLO\n\nmodel = YOLO(\"/kaggle/working/runs/detect/train/weights/best.pt\")\n\nresults = model.predict(\n    source=\"/kaggle/working/cots_yolo/valid/images\",\n    conf=0.25,\n    save=True\n)\n\nprint(\"Prediction Complete\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T18:23:01.688751Z","iopub.execute_input":"2026-06-13T18:23:01.689254Z","iopub.status.idle":"2026-06-13T18:23:32.753721Z","shell.execute_reply.started":"2026-06-13T18:23:01.689214Z","shell.execute_reply":"2026-06-13T18:23:32.753020Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Result file\n\nresults = model.predict(\n    source=\"/kaggle/working/cots_yolo/valid/images\",\n    conf=0.25,\n    save=True\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T18:23:46.123104Z","iopub.execute_input":"2026-06-13T18:23:46.124004Z","iopub.status.idle":"2026-06-13T18:24:17.610521Z","shell.execute_reply.started":"2026-06-13T18:23:46.123963Z","shell.execute_reply":"2026-06-13T18:24:17.609922Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Image with bounding boxes \n\nfrom PIL import Image\nfrom IPython.display import display\nimport glob\n\npred_images = glob.glob(\"/kaggle/working/runs/detect/predict/*.jpg\")\n\nimg = Image.open(pred_images[0])\ndisplay(img)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T18:24:44.468782Z","iopub.execute_input":"2026-06-13T18:24:44.469297Z","iopub.status.idle":"2026-06-13T18:24:44.675718Z","shell.execute_reply.started":"2026-06-13T18:24:44.469256Z","shell.execute_reply":"2026-06-13T18:24:44.674498Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# To see predicted images\n\nfrom PIL import Image\nfrom IPython.display import display\nimport glob\n\nfor img_path in glob.glob(\"/kaggle/working/runs/detect/predict/*.jpg\")[:5]:\n    print(img_path)\n    display(Image.open(img_path))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T18:24:53.962312Z","iopub.execute_input":"2026-06-13T18:24:53.962949Z","iopub.status.idle":"2026-06-13T18:24:54.167751Z","shell.execute_reply.started":"2026-06-13T18:24:53.962918Z","shell.execute_reply":"2026-06-13T18:24:54.164627Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Bounding Box coordinates \n\nfrom ultralytics import YOLO\n\nmodel = YOLO(\"/kaggle/working/runs/detect/train/weights/best.pt\")\n\nresults = model.predict(\n    source=\"/kaggle/working/cots_yolo/valid/images\",\n    conf=0.25\n)\n\nfor result in results:\n    for box in result.boxes:\n        x1, y1, x2, y2 = box.xyxy[0].tolist()\n        conf = float(box.conf[0])\n\n        print(f\"Box: ({x1:.0f}, {y1:.0f}, {x2:.0f}, {y2:.0f})\")\n        print(f\"Confidence: {conf:.3f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-06-13T18:25:01.829420Z","iopub.execute_input":"2026-06-13T18:25:01.830127Z","iopub.status.idle":"2026-06-13T18:25:24.656343Z","shell.execute_reply.started":"2026-06-13T18:25:01.830093Z","shell.execute_reply":"2026-06-13T18:25:24.655473Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null}]}