{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.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":19989,"databundleVersionId":1160143,"sourceType":"competition"}],"dockerImageVersionId":30665,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Introduction\n\nWelcome to this Kaggle notebook dedicated to leveraging [YOLOv8](https://docs.ultralytics.com/models/yolov8/) with [Ultralytics](https://docs.ultralytics.com) for the task of wheat detection using image analysis. YOLOv8, an evolution of the popular YOLO (You Only Look Once) series, offers a powerful and efficient approach to object detection. With its Python interface and integration with Ultralytics, YOLOv8 becomes a seamless and versatile tool for incorporating object detection capabilities into your Python projects.\n\n## YOLOv8 Python Interface\n\nYOLOv8's Python interface is designed for simplicity and ease of use, allowing users to effortlessly integrate the model into their projects. The interface enables key functionalities such as loading, running, and processing the model's output with just a few lines of code. Whether you're working on object detection, segmentation, or classification tasks, YOLOv8's Python interface provides a convenient solution.\n\n### Key Features\n\n* ***Advanced Backbone and Neck Architectures*** : YOLOv8 utilizes cutting-edge backbone and neck architectures, enhancing its ability to extract features and detect objects with greater precision and efficiency.\n\n* ***Anchor-free Split Ultralytics Head*** : YOLOv8 features an anchor-free split Ultralytics head, which improves accuracy and streamlines the detection process compared to traditional anchor-based methods. This innovative approach contributes to more reliable object detection results.\n\n* ***Optimized Accuracy-Speed Tradeoff*** : With a keen focus on achieving an optimal balance between accuracy and speed, YOLOv8 is well-suited for real-time object detection tasks across a wide range of applications. Users can expect high-performance results without compromising on efficiency.\n\n* ***Variety of Pre-trained Models*** : YOLOv8 offers a diverse selection of pre-trained models tailored to different tasks and performance needs. This variety makes it easier for users to find the perfect model for their specific use case, whether it's for general object detection or specialized applications.\n\n## Getting Started\n\nTo dive into YOLOv8 for your global wheat detection project, follow these steps :\n\n* ***Installation*** : Install YOLOv8 and Ultralytics by following the setup instructions provided in the [Python Guide](https://docs.ultralytics.com/usage/python).\n\n* ***Loading and Training*** : Use the Python interface to load the YOLOv8 model, train it on your global wheat dataset, and fine-tune its performance.\n\n* ***Evaluation*** : Assess the model's performance on a validation set to ensure its effectiveness in detecting wheat instances.\n\nIn the subsequent sections of this Kaggle notebook, we will walk through these steps, providing code snippets and explanations to guide you in implementing YOLOv8 for global wheat detection. Let's embark on this journey to harness the power of YOLOv8 and Ultralytics for accurate and efficient object detection.","metadata":{"_uuid":"1f1b6d66-b841-4dc7-a922-ba426d6ac20f","_cell_guid":"a41283e5-dace-4668-924c-2ee8d0b8492e","trusted":true}},{"cell_type":"markdown","source":"# Installing Required Packages","metadata":{"_uuid":"15b39f4f-3f92-4281-a0b3-97647eb6fbbc","_cell_guid":"95e5009e-9820-4361-bcd2-5140297341f5","trusted":true}},{"cell_type":"code","source":"!pip install -q -U ultralytics wandb\n!pip install -q -U ipywidgets # To avoid a future warning\n!wandb off","metadata":{"_uuid":"d9613158-042a-444b-9419-710638902a9f","_cell_guid":"ab8e9168-7c61-446c-8f7d-5cd452cfccc9","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:17:30.281683Z","iopub.execute_input":"2024-03-19T07:17:30.282109Z","iopub.status.idle":"2024-03-19T07:17:57.710625Z","shell.execute_reply.started":"2024-03-19T07:17:30.282074Z","shell.execute_reply":"2024-03-19T07:17:57.709362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Libraries Overview\n\n* ***[os](https://docs.python.org/3/library/os.html)*** : Handles operating system-dependent functionality for file system and directory operations.\n\n* ***[yaml](https://pyyaml.org/wiki/PyYAMLDocumentation)*** (v6.0.1) : A Python library for reading YAML files, commonly used for configuration purposes.\n\n* ***[ast](https://docs.python.org/3/library/ast.html)*** : Parses Python code into tree structures for programmatic analysis and manipulation. Commonly used for safely evaluating string representations of Python code.\n\n* ***[OpenCV (cv2)](https://docs.opencv.org/4.x/index.html)*** (v4.9.0) : OpenCV is a popular computer vision library providing tools for image and video analysis, including image processing, object detection, and feature extraction.\n\n* ***[Pandas](https://pandas.pydata.org/docs/)*** (v2.2.0) : Powerful data manipulation library for handling and organizing structured data.\n\n* ***[NumPy](https://numpy.org/doc/1.26/)*** (v1.26.4) : It's a fundamental package for scientific computing with Python, providing support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays.\n\n* ***[tqdm](https://tqdm.github.io)*** (v4.66.1) : Provides a fast, extensible progress bar for visualizing loop and task progress. \n\n* ***[Shutil](https://docs.python.org/3/library/shutil.html)*** : Offers high-level file operations within the project.\n\n* ***[Sklearn](https://scikit-learn.org/stable/)*** (v1.2.2) : A versatile machine learning library in Python, providing efficient tools for classification, regression, clustering, and more. In this script, `sklearn` is used for dataset splitting, a key step in model evaluation.\n\n* ***[Matplotlib](https://matplotlib.org/3.7.5/index.html)*** (v3.7.5) : Comprehensive library for creating static, animated, and interactive visualizations in Python. It offers a wide range of plotting functions for creating plots, histograms, bar charts, scatterplots, and more.\n\n* ***[Ultralytics](https://docs.ultralytics.com)*** (v8.1.27) : It simplifies and streamlines object detection tasks, offering a convenient interface for loading, training, and evaluating models.\n\n### Warning Suppression\nWe suppress warnings using `filterwarnings('ignore')` to ensure that the code output is clean and concise.","metadata":{"_uuid":"bc764328-07ab-4d53-85ac-fab8359cac99","_cell_guid":"7e0f6ce3-9f31-4d6c-a3c7-8006cb880e76","trusted":true}},{"cell_type":"code","source":"# Data Preprocessing\nimport os, yaml, ast\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nfrom shutil import copyfile\nfrom sklearn.model_selection import train_test_split\n\n# Visualization\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.image as mpimg\n\n# Model\nimport ultralytics\nfrom ultralytics import YOLO\nultralytics.checks()\n\n# Suppressing warnings\nfrom warnings import filterwarnings\nfilterwarnings('ignore')","metadata":{"_uuid":"83f43221-7384-43d1-8425-8d1714a5ef53","_cell_guid":"6a4e5ada-757b-4d50-bdb8-17910b4e9f25","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:17:57.712780Z","iopub.execute_input":"2024-03-19T07:17:57.713113Z","iopub.status.idle":"2024-03-19T07:18:05.229849Z","shell.execute_reply.started":"2024-03-19T07:17:57.713083Z","shell.execute_reply":"2024-03-19T07:18:05.228896Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Preprocessing & Visualization","metadata":{"_uuid":"9d96c86b-43d4-40d3-a500-450bf4afafa3","_cell_guid":"e423cb1e-2043-4a8b-bd81-9ca6b91a9c72","trusted":true}},{"cell_type":"code","source":"# Defining root folder\nroot = '/kaggle/input/global-wheat-detection/'","metadata":{"_uuid":"13c326db-db46-4a7e-8a2c-652ebdf28399","_cell_guid":"2c253474-f9c9-4db4-8ef2-8eb62d327249","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:18:05.230989Z","iopub.execute_input":"2024-03-19T07:18:05.231399Z","iopub.status.idle":"2024-03-19T07:18:05.235550Z","shell.execute_reply.started":"2024-03-19T07:18:05.231374Z","shell.execute_reply":"2024-03-19T07:18:05.234502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Loading dataset\ndata = pd.read_csv(root + 'train.csv', usecols = ['image_id', 'bbox'])\n\n# Creating column 'path' to store file path\ndata['path'] = data.apply(lambda row : root + 'train/' + row.image_id + '.jpg', axis = 1)\n\n# Converting bounding boxes to list datatype\ndata['bbox'] = data['bbox'].apply(ast.literal_eval)\n\ndata.head()","metadata":{"_uuid":"163e0c1f-b2ca-4fe8-9f8b-a7110a3a9828","_cell_guid":"304a13b7-fdad-4849-8175-ba68504043cc","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:18:05.238252Z","iopub.execute_input":"2024-03-19T07:18:05.238623Z","iopub.status.idle":"2024-03-19T07:18:10.208162Z","shell.execute_reply.started":"2024-03-19T07:18:05.238589Z","shell.execute_reply":"2024-03-19T07:18:10.207184Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Function to display images with bounding boxes\ndef displayImagesWithBoxes():\n    # Shuffling the list of unique image paths\n    uniqueImages = data['path'].unique()\n    np.random.shuffle(uniqueImages)\n    \n    # Determining max number of images to display (9 here)\n    numImages = min(len(uniqueImages), 9)\n    rows = cols = 3\n    \n    # Creating subplots\n    fig, axes = plt.subplots(rows, cols, figsize = (12, 12))\n    \n    for i, imgPath in enumerate(uniqueImages[:numImages]):\n        # Reading image and converting to RGB\n        img = cv2.imread(imgPath)\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        \n        # Getting all bounding boxes for current image\n        boxes = data[data['path'] == imgPath]['bbox'].tolist()\n        for box in boxes:\n            x, y, w, h = box\n            \n            # Adding rectangle patch to current subplot\n            rect = patches.Rectangle((x, y), w, h, linewidth = 2, edgecolor = 'r', facecolor = 'none')\n            axes[i // cols, i % cols].add_patch(rect)\n\n        # Displaying image and turning off axis labels\n        axes[i // cols, i % cols].imshow(img)\n        axes[i // cols, i % cols].axis('off')\n\n    plt.tight_layout()\n    plt.show()","metadata":{"_uuid":"4c611ddf-3db7-4daf-89d2-a83516f8c4dc","_cell_guid":"33424d6b-2962-44b4-804e-f5a65b299649","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:18:10.209324Z","iopub.execute_input":"2024-03-19T07:18:10.209626Z","iopub.status.idle":"2024-03-19T07:18:10.220037Z","shell.execute_reply.started":"2024-03-19T07:18:10.209601Z","shell.execute_reply":"2024-03-19T07:18:10.218954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"displayImagesWithBoxes()","metadata":{"_uuid":"68292e47-a2fc-4efb-907f-67302d1712fb","_cell_guid":"dfd30e42-62ca-4e91-903e-b36beadc85e3","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:18:10.221447Z","iopub.execute_input":"2024-03-19T07:18:10.221785Z","iopub.status.idle":"2024-03-19T07:18:13.963583Z","shell.execute_reply.started":"2024-03-19T07:18:10.221757Z","shell.execute_reply":"2024-03-19T07:18:13.962181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train-validation split\ntrainList, valList = train_test_split(data.image_id.unique(), random_state = 0)","metadata":{"_uuid":"8ae17c29-e91c-4cb4-b9ef-19475aad20ac","_cell_guid":"9473877d-f9b2-4071-a412-05aaa3fec05a","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:18:13.965241Z","iopub.execute_input":"2024-03-19T07:18:13.965720Z","iopub.status.idle":"2024-03-19T07:18:13.986050Z","shell.execute_reply.started":"2024-03-19T07:18:13.965657Z","shell.execute_reply":"2024-03-19T07:18:13.984958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Filtering out train and validation data\ntrainDf = data.loc[data.image_id.isin(trainList)]\nvalDf = data.loc[data.image_id.isin(valList)]\n\ntrainDf.loc[:, 'split'] = 'train'\nvalDf.loc[:, 'split'] = 'valid'\n\n# Concatenating the training and validation datasets\ndata = pd.concat([trainDf, valDf]).reset_index(drop = True)\ndata.head()","metadata":{"_uuid":"7f220940-e0ef-41a9-ad8f-297c3e6e0740","_cell_guid":"8ef460b5-05e8-4d66-b209-eb68270ff3eb","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:18:13.987508Z","iopub.execute_input":"2024-03-19T07:18:13.987832Z","iopub.status.idle":"2024-03-19T07:18:14.087333Z","shell.execute_reply.started":"2024-03-19T07:18:13.987805Z","shell.execute_reply":"2024-03-19T07:18:14.086361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating necessary directories for images and labels\nos.makedirs('images/train', exist_ok = True)\nos.makedirs('images/valid', exist_ok = True)\n\nos.makedirs('labels/train', exist_ok = True)\nos.makedirs('labels/valid', exist_ok = True)","metadata":{"_uuid":"cdf5ba28-53f3-41c8-9661-659a701f9f9f","_cell_guid":"6a9a0d13-f734-42e0-ba00-13a98bad4778","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:18:14.088992Z","iopub.execute_input":"2024-03-19T07:18:14.089638Z","iopub.status.idle":"2024-03-19T07:18:14.095773Z","shell.execute_reply.started":"2024-03-19T07:18:14.089601Z","shell.execute_reply":"2024-03-19T07:18:14.094724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Copying training and validation images to new folder\nfor i in tqdm(range(len(data))):\n    row = data.loc[i]\n    copyfile(row.path, f'images/{row.split}/{row.image_id}.jpg')","metadata":{"_uuid":"e7bf4c55-9207-4ed3-9dd6-b8a57f6669a8","_cell_guid":"48e4c8f4-1cf4-4bc1-a773-0c472b2fc080","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:18:14.099725Z","iopub.execute_input":"2024-03-19T07:18:14.100001Z","iopub.status.idle":"2024-03-19T07:21:14.543274Z","shell.execute_reply.started":"2024-03-19T07:18:14.099979Z","shell.execute_reply":"2024-03-19T07:21:14.542247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating the yaml file required for YOLO\ncontent = '''\npath: '/kaggle/working/'\n\ntrain: 'images/train'\nval: 'images/valid'\n    \nnames:\n    0: none\n    1: opacity\n'''\n\nwith open('GlobalWheatDataset.yaml', 'w') as file:\n    file.write(content)","metadata":{"_uuid":"9f8b6e86-dc16-45d8-87e3-ebfbce8274b0","_cell_guid":"df58582b-3b77-43a4-abae-3d07dcb0c82a","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:21:14.544482Z","iopub.execute_input":"2024-03-19T07:21:14.544782Z","iopub.status.idle":"2024-03-19T07:21:14.550129Z","shell.execute_reply.started":"2024-03-19T07:21:14.544756Z","shell.execute_reply":"2024-03-19T07:21:14.549174Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Function to create YOLO-formatted bounding boxes\ndef createYOLOBox(bbox):\n    # Unpacking coordinates from list\n    x, y, w, h = bbox\n    \n    # Normalizing coordinates\n    x_center = (x + w / 2) / 1024\n    y_center = (y + h / 2) / 1024\n    \n    return f'1 {x_center} {y_center} {w / 1024} {h / 1024}'","metadata":{"_uuid":"f68f5edd-0a5a-4b9f-8a46-6ccc9005572d","_cell_guid":"f664a950-8a25-4794-936a-da301b2fb143","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:21:14.551295Z","iopub.execute_input":"2024-03-19T07:21:14.551602Z","iopub.status.idle":"2024-03-19T07:21:16.186650Z","shell.execute_reply.started":"2024-03-19T07:21:14.551580Z","shell.execute_reply":"2024-03-19T07:21:16.185712Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating text file for each image containing required bounding box coordinates\nfor i in tqdm(range(len(data))):\n    row = data.loc[i]\n    yoloBox = createYOLOBox(row['bbox'])\n    \n    # Defining file path\n    filePath = f'labels/{row.split}/{row.image_id}.txt'\n    with open(filePath, 'a') as file:\n        file.write(yoloBox + '\\n')","metadata":{"_uuid":"458ad37f-0f3e-4a56-bfa3-6b92a3dcd080","_cell_guid":"a1698a41-2e7a-4271-b8c0-e206ff7fee38","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:21:16.190243Z","iopub.execute_input":"2024-03-19T07:21:16.190514Z","iopub.status.idle":"2024-03-19T07:21:31.191998Z","shell.execute_reply.started":"2024-03-19T07:21:16.190491Z","shell.execute_reply":"2024-03-19T07:21:31.191092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Defining Model","metadata":{"_uuid":"bd92927f-83e6-4bdd-9b13-ff461a903618","_cell_guid":"a022a33d-4eb7-4020-91bd-e31bdbb6de53","trusted":true}},{"cell_type":"code","source":"# Loading pre-trained YOLOv8n model\nmodel = YOLO('yolov8n.pt')\nmodel.info()","metadata":{"_uuid":"78b4e58d-b15b-4e8d-ab7e-8a15f0729811","_cell_guid":"3d87f8cf-7324-4efa-9295-465ac46a01f4","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:21:31.193246Z","iopub.execute_input":"2024-03-19T07:21:31.193552Z","iopub.status.idle":"2024-03-19T07:21:32.066787Z","shell.execute_reply.started":"2024-03-19T07:21:31.193527Z","shell.execute_reply":"2024-03-19T07:21:32.065938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training Parameters Overview\n\n| Parameter | Default | Description |\n|:----------:|:-------:|:-----------:|\n|   model    |   `None`  | Specifies the model file for training, either a path to a `.pt` pretrained model or a `.yaml` configuration file. Essential for defining the model structure or initializing weights. |\n|   data     |   `None`  | Path to the dataset configuration file (e.g. `coco128.yaml`). Contains dataset-specific parameters, including paths to training and validation data, class names, and the number of classes. |\n|  epochs    |   `100`   | Total number of training epochs. Each epoch represents a full pass over the dataset, affecting training duration and model performance. |\n|    batch    |    `16`     |  Batch size for training, indicating how many images are processed before the model's internal parameters are updated. AutoBatch (batch=-1) dynamically adjusts the batch size based on GPU memory availability.  |\n|   imgsz    |   `640`   | Target image size for training. All images are resized to this dimension before being fed into the model, impacting accuracy and computational complexity. |\n| optimizer  |  `auto`   | Choice of optimizer for training, including options like `SGD`, `Adam`, `AdamW`, `NAdam`, `RAdam`, `RMSProp`, or `auto` for automatic selection based on model configuration. Affects convergence speed and stability. |\n|  cos_lr    |  `False`  | Utilizes a cosine learning rate scheduler, adjusting the learning rate following a cosine curve over epochs. Helps manage the learning rate for improved convergence. |\n|  dropout   |   `0.0`   | Dropout rate for regularization in classification tasks. Prevents overfitting by randomly omitting units during training. |\n|  device    |   `None`  | Specifies the computational device(s) for training, such as a single GPU (`device = 0`), multiple GPUs (`device = [0,1]`), CPU (`device = cpu`), or MPS for Apple silicon (`device = mps`). |","metadata":{"_uuid":"164528ff-cdf4-4feb-8ed4-9f2660e522b3","_cell_guid":"efad9f0c-9a54-4043-a30c-d65108850d23","trusted":true}},{"cell_type":"code","source":"# Training the model\nresults = model.train(\n    data = 'GlobalWheatDataset.yaml',\n    epochs = 100,\n    batch = 32,\n    imgsz = 1024,\n    optimizer = 'Adam',\n    cos_lr = True,\n    dropout = 0.2,\n    device = [0, 1]\n)","metadata":{"_uuid":"2e01abb4-dc40-4732-9875-dff5993ef8dc","_cell_guid":"64e63c44-fbd9-4729-878b-d98cb089b4e3","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-03-19T07:21:32.067812Z","iopub.execute_input":"2024-03-19T07:21:32.068114Z","iopub.status.idle":"2024-03-19T09:48:18.943327Z","shell.execute_reply.started":"2024-03-19T07:21:32.068089Z","shell.execute_reply":"2024-03-19T09:48:18.942408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Loading the metrics JPG file\nimg = mpimg.imread('/kaggle/working/runs/detect/train/results.png')\n\n# Displaying the image\nplt.figure(figsize = (30, 30))\nplt.imshow(img)\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-03-19T09:59:24.155822Z","iopub.execute_input":"2024-03-19T09:59:24.156781Z","iopub.status.idle":"2024-03-19T09:59:25.358659Z","shell.execute_reply.started":"2024-03-19T09:59:24.156745Z","shell.execute_reply":"2024-03-19T09:59:25.357702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating Submission","metadata":{}},{"cell_type":"code","source":"# Creating best-weighted model\nbestModel = YOLO('/kaggle/working/runs/detect/train/weights/best.pt')","metadata":{"execution":{"iopub.status.busy":"2024-03-19T09:48:20.158574Z","iopub.execute_input":"2024-03-19T09:48:20.158981Z","iopub.status.idle":"2024-03-19T09:48:20.210064Z","shell.execute_reply.started":"2024-03-19T09:48:20.158946Z","shell.execute_reply":"2024-03-19T09:48:20.209177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Prediction Parameters Overview","metadata":{}},{"cell_type":"markdown","source":"### Inference Arguments\n|      Argument     | Type | Default | Description                                                                                                  |\n|:-----------------:|:----:|:-------:|--------------------------------------------------------------------------------------------------------------|\n|      source       | `str`  |  `ultralytics/assets`  | Specifies the data source for inference. Can be an image path, video file, directory, URL, or device ID for live feeds. Supports a wide range of formats and sources, enabling flexible application across different types of input. |\n|      imgsz        | `int` or `tuple` |  `640`  | Defines the image size for inference. Can be a single integer 640 for square resizing or a (height, width) tuple. Proper sizing can improve detection accuracy and processing speed. |\n|       conf        | `float` |   `0.25`  | Sets the minimum confidence threshold for detections. Objects detected with confidence below this threshold will be disregarded. Adjusting this value can help reduce false positives. |\n|       iou         | `float` |   `0.7`   | Intersection Over Union (IoU) threshold for Non-Maximum Suppression (NMS). Higher values result in fewer detections by eliminating overlapping boxes, useful for reducing duplicates. |","metadata":{}},{"cell_type":"markdown","source":"### Visualization arguments\n\n|    Argument   | Type | Default | Description                                                                                                       |\n|:-------------:|:----:|:-------:|-------------------------------------------------------------------------------------------------------------------|\n|   save_txt    | `bool` |  `False`  | Saves detection results in a text file, following the format `[class] [x_center] [y_center] [width] [height] [confidence]`. Useful for integration with other analysis tools. |\n|   save_conf   | `bool` |  `False`  | Includes confidence scores in the saved text files. Enhances the detail available for post-processing and analysis. |","metadata":{}},{"cell_type":"code","source":"# Making predictions on test set\npred = bestModel.predict(\n    source = '/kaggle/input/global-wheat-detection/test',\n    imgsz = 1024,\n    conf = 0.65,\n    iou = 0.65,\n    save_txt = True,\n    save_conf = True\n)","metadata":{"execution":{"iopub.status.busy":"2024-03-19T09:48:20.211344Z","iopub.execute_input":"2024-03-19T09:48:20.212052Z","iopub.status.idle":"2024-03-19T09:48:22.097747Z","shell.execute_reply.started":"2024-03-19T09:48:20.212014Z","shell.execute_reply":"2024-03-19T09:48:22.096678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating submission-formatted text file\npredPath = '/kaggle/working/runs/detect/predict/labels'\nresults = []\n\nfor filename in os.listdir(predPath):\n    # Extracting file name\n    fileID = filename.split('/')[-1][:-4]\n    predStr = ''\n    \n    with open(os.path.join(predPath, filename)) as file:\n        # Iterating over each line (containing bounding box coordinates)\n        for line in file.readlines():\n            _, x_center, y_center, w, h, conf = np.array(line.strip('\\n').split()).astype(float)\n            \n            # Calculating x_min and y_min\n            x = (x_center - w / 2) * 1024\n            y = (y_center - h / 2) * 1024\n            \n            # Rounding up coordinates to third decimal place\n            bbox = np.round([x, y, w * 1024, h * 1024], 3)\n            \n            # Setting a minimum threshold value for coordinates (here 1e-10)\n            bbox = np.where(np.abs(bbox) < 1e-10, 0.0, bbox).tolist()\n            predStr += f\" {str(conf)} {' '.join(map(str, bbox))}\"\n    \n    # Adding bounding boxes to results\n    results.append({\n        'image_id' : fileID,\n        'PredictionString' : predStr.lstrip()\n    })","metadata":{"execution":{"iopub.status.busy":"2024-03-19T09:48:22.098981Z","iopub.execute_input":"2024-03-19T09:48:22.099270Z","iopub.status.idle":"2024-03-19T09:48:22.118198Z","shell.execute_reply.started":"2024-03-19T09:48:22.099244Z","shell.execute_reply":"2024-03-19T09:48:22.117444Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Converting it into a Pandas DataFrame\nresults = pd.DataFrame(results)\nresults","metadata":{"execution":{"iopub.status.busy":"2024-03-19T09:48:22.119690Z","iopub.execute_input":"2024-03-19T09:48:22.120076Z","iopub.status.idle":"2024-03-19T09:48:22.132062Z","shell.execute_reply.started":"2024-03-19T09:48:22.120049Z","shell.execute_reply":"2024-03-19T09:48:22.131057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating submission CSV file\nresults.to_csv('submission.csv', index = False)","metadata":{"execution":{"iopub.status.busy":"2024-03-19T09:48:22.133111Z","iopub.execute_input":"2024-03-19T09:48:22.133391Z","iopub.status.idle":"2024-03-19T09:48:22.147073Z","shell.execute_reply.started":"2024-03-19T09:48:22.133368Z","shell.execute_reply":"2024-03-19T09:48:22.146267Z"},"trusted":true},"execution_count":null,"outputs":[]}]}