{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":19989,"databundleVersionId":1160143,"sourceType":"competition"}],"dockerImageVersionId":30461,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport json\nimport glob\nimport copy\nfrom tqdm import tqdm\nfrom pathlib import Path\nimport yaml\nimport shutil\n\nimport cv2\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n#import pybboxes as pbx\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.model_selection import GroupKFold","metadata":{"execution":{"iopub.status.busy":"2023-04-13T13:02:49.155945Z","iopub.execute_input":"2023-04-13T13:02:49.156746Z","iopub.status.idle":"2023-04-13T13:02:50.336822Z","shell.execute_reply.started":"2023-04-13T13:02:49.156705Z","shell.execute_reply":"2023-04-13T13:02:50.335502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install ultralytics","metadata":{"execution":{"iopub.status.busy":"2023-04-13T13:02:50.343532Z","iopub.execute_input":"2023-04-13T13:02:50.346574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/global-wheat-detection/train.csv')\ndf","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir = '/kaggle/input/global-wheat-detection/train/'\ntest_dir = '/kaggle/input/global-wheat-detection/test/'\n\ntrain_list = os.listdir(train_dir)\ntest_list = os.listdir(test_dir)\n\nprint('Number of train images is {}'.format(len(train_list)))\nprint('Number of test images is {}'.format(len(test_list)))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_all_bboxes(df, image_id):\n    image_bboxes = df[df.image_id == image_id]\n    \n    bboxes = []\n    for _,row in image_bboxes.iterrows():\n        bboxes.append((row.x, row.y, row.w, row.h))\n        \n    return bboxes\n\ndef plot_image_examples(df, rows=3, cols=3, title='Image examples'):\n    fig, axs = plt.subplots(rows, cols, figsize=(10,10))\n    for row in range(rows):\n        for col in range(cols):\n            idx = np.random.randint(len(df), size=1)[0]\n            img_id = df.iloc[idx].image_id\n            \n            img = Image.open(train_dir + img_id + '.jpg')\n            axs[row, col].imshow(img)\n            \n            bboxes = get_all_bboxes(df, img_id)\n            \n            for bbox in bboxes:\n                rect = patches.Rectangle((bbox[0],bbox[1]),bbox[2],bbox[3],linewidth=1,edgecolor='r',facecolor='none')\n                axs[row, col].add_patch(rect)\n            \n            axs[row, col].axis('off')\n            \n    plt.suptitle(title)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"FOLD      = 1\n\nkf = GroupKFold(n_splits = 5)\ndf = df.reset_index(drop=True)\ndf['fold'] = -1\nfor fold, (train_idx, val_idx) in enumerate(kf.split(df, groups=df.source.tolist())):\n    df.loc[val_idx, 'fold'] = fold\ndisplay(df.fold.value_counts())\n\ntrain_df = df.query(\"fold!=@FOLD\")\nval_df = df.query(\"fold==@FOLD\")\n\n#train_df = df.iloc[train_index]\n#valid_df = df.iloc[valid_index]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dest_dir = \"wheat_data\"\n!mkdir {dest_dir}\n\n_ = Path(f\"{dest_dir}/dataset.yaml\").write_text(f\"\"\"path: {dest_dir}\ntrain: /kaggle/working/wheat_data/images/train\nval: /kaggle/working/wheat_data/images/val\n\nnc: 1\nnames: ['wheat_head']\n\"\"\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_txt_file(path: Path, bboxes):\n    \"\"\"Creates a .txt file with annotation strings for the given bounding boxes\"\"\"\n    \n    anno_str = []\n    for bbox in bboxes:\n        x, y, w, h = bbox[0] / width, bbox[1] / height, bbox[2] / width, bbox[3] / height\n\n        h = min((1 - y), h)\n        w = min((1 - x), w)\n\n        xc = x + w / 2\n        yc = y + h / 2\n        anno_str.append(f\"0 {xc} {yc} {w} {h}\")\n    path.write_text(\"\\n\".join(anno_str))\n    \n    \npath_list = []\n\n# Iterate over the two modes: train and val\nfor mode in [\"train\", \"val\"]:\n    image_folder = Path(dest_dir) / \"images\" / mode\n    image_folder.mkdir(parents=True, exist_ok=True)\n    \n    label_folder = Path(dest_dir) / \"labels\" / mode\n    label_folder.mkdir(parents=True, exist_ok=True)\n    \n    # Get the DataFrame for the current mode using its name\n    df = globals()[f\"{mode}_df\"]\n    \n    # Group the DataFrame by image ID\n    grouped = df.groupby('image_id')\n    for image_id, group_df in tqdm(grouped, total=len(grouped)):\n        # Get the file name by removing the extension from the image ID\n        file_name = image_id\n        width, height = group_df.iloc[0].width, group_df.iloc[0].height\n        \n        # Parse the bounding box coordinates from each row of the group\n        bboxes = [json.loads(row.bbox) for _, row in group_df.iterrows()]\n        \n        img_path = image_folder / f\"{file_name}.jpg\"\n        label_path = label_folder / f\"{file_name}.txt\"\n        shutil.copy(f\"{train_dir}/{image_id}.jpg\", img_path)\n        create_txt_file(label_path, bboxes)\n        path_list.append((str(img_path), str(label_path)))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import ultralytics\nfrom ultralytics import YOLO\n\n# Load a model\nmodel = YOLO(\"yolov8n.pt\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.train(data=\"/kaggle/working/wheat_data/dataset.yaml\",\n            epochs=10,\n            imgsz=720,\n            batch=16,\n            device=0,\n           name='yolov8n_10epoch'\n           )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result_paths = glob.glob('runs/detect/yolov8n_10epoch/*jpg') +  glob.glob('runs/detect/yolov8n_10epoch/*png')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%matplotlib inline\n\nfor path in result_paths:\n    image = cv2.imread(path)\n    plt.figure(figsize=(14,10))\n    plt.imshow(image)\n    plt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_best = YOLO(\"runs/detect/yolov8n_10epoch/weights/best.pt\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds = model_best.predict(conf = 0.1, source = \"/kaggle/input/global-wheat-detection/test\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}