{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":85240,"databundleVersionId":9622164,"sourceType":"competition"}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2\nimport matplotlib.pyplot as plt\nimport glob\nimport random\nimport os","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# install ultralytics\n\n!pip install ultralytics","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"%%writefile Mosquito_v8.yaml\npath: '/kaggle/input/dlp-object-detection/final_dlp_data/final_dlp_data'\ntrain: '/kaggle/input/dlp-object-detection/final_dlp_data/final_dlp_data/train/images'\nval: '/kaggle/input/dlp-object-detection/final_dlp_data/final_dlp_data/test/images'\n\n# class names\nnames:\n  0: \"aegypti\"\n  1: \"albopictus\"\n  2: \"anopheles\"\n  3: \"culex\"\n  4: \"culiseta\"\n  5: \"japonicus/koreicus\"\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Specify the number of epochs and batch size for training.\n\nEPOCHS = 20\nBATCH=8","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # Train the YOLOv8 model.\n\n# !yolo task=detect \\\n# mode=train \\\n# model=yolov8n.pt \\\n# imgsz=640 \\\n# data=/kaggle/working/Mosquito_v8.yaml \\\n# epochs={EPOCHS} \\\n# batch={BATCH} \\\n# augment=True \\\n# name=yolov8n_v8_50e","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"HELLO\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport torch\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom ultralytics import YOLO\nimport numpy as np\nfrom PIL import Image\nimport random\n\nclass ObjectDetection:\n    # Custom class names\n    dict1 = {\n        0: \"aegypti\",\n        1: \"albopictus\",\n        2: \"anopheles\",\n        3: \"culex\",\n        4: \"culiseta\",\n        5: \"japonicus/koreicus\"\n    }\n    \n    def __init__(self):\n        self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n        print(\"Using Device: \", self.device)\n        self.model = self.load_model()\n        \n    def load_model(self):\n        model = YOLO(\"/kaggle/input/20epoch_yolo/pytorch/default/1/best (1).pt\")  # Load pretrained YOLOv8 model\n        model.fuse()  # Optimize the model for inference\n        return model\n    \n    def predict(self, image):\n        results = self.model(image)\n        return results\n    \n    def process_bboxes(self, results, image_id, image_name, image_height, image_width):\n        detections = []\n        print(\"ID:\", image_id)\n        \n        for result in results:\n            boxes = result.boxes.cpu().numpy()  # Extract bounding boxes\n            \n            if len(boxes) == 0:  # If no detections, generate a random label and values\n                random_cls = random.randint(0, 5)  # Random class from dict1\n                random_label = self.dict1[random_cls]\n                xmid = random.random()\n                ymid = random.random()\n                width = random.random()\n                height = random.random()\n                \n                # Add random detection\n                detections.append({\n                    'id': image_id,\n                    'ImageID': image_name,\n                    'LabelName': random_label,\n                    'Conf': random.random(),  # Random confidence\n                    'xcenter': xmid,\n                    'ycenter': ymid,\n                    'bbx_width': width,\n                    'bbx_height': height\n                })\n            else:\n                # Find the box with the maximum confidence score\n                max_conf_idx = np.argmax([box.conf[0] for box in boxes])\n                box = boxes[max_conf_idx]  # Select the best box\n                \n                # Extract bounding box coordinates and class\n                xyxy = box.xyxy[0]\n                conf = box.conf[0]\n                cls = int(box.cls[0])  # Convert to integer for indexing\n                \n                # Convert (xmin, ymin, xmax, ymax) to normalized (xmid, ymid, width, height)\n                xmin, ymin, xmax, ymax = xyxy\n                xmid = (xmin + xmax) / 2\n                ymid = (ymin + ymax) / 2\n                width = xmax - xmin\n                height = ymax - ymin\n                \n                # Normalize bounding box to the image size\n                xmid /= image_width\n                ymid /= image_height\n                width /= image_width\n                height /= image_height\n                \n                # Add the best result to the list\n                detections.append({\n                    'id': image_id,\n                    'ImageID': image_name,\n                    'LabelName': self.dict1[cls],\n                    'Conf': np.round(conf, 3),\n                    'xcenter': np.round(xmid, 3),\n                    'ycenter': np.round(ymid, 3),\n                    'bbx_width': np.round(width, 3),\n                    'bbx_height': np.round(height, 3)\n                })\n        \n        return detections\n\ndef main():\n    detector = ObjectDetection()\n    \n    # Initialize a list to store all detections\n    all_detections = []\n    \n    # Load all jpeg images from the folder\n    images = os.listdir(\"/kaggle/input/dlp-object-detection/final_dlp_data/final_dlp_data/test/images/\")\n    \n    for image_id, image_path in enumerate(sorted(images)):\n        if not image_path.endswith('.jpeg'):\n            continue  # Skip non-JPEG files\n        \n        print(f\"Processing {image_path}\")\n        \n        # Load the image and convert it to a numpy array\n        image = Image.open(\"/kaggle/input/dlp-object-detection/final_dlp_data/final_dlp_data/test/images/\" + image_path)\n        image = np.array(image)  # Convert PIL image to numpy array\n        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)  # Convert to BGR format for OpenCV\n        \n        # Perform inference\n        results = detector.predict(image)\n        \n        # Process bounding boxes and collect detections, passing image height and width\n        image_height, image_width = image.shape[:2]\n        detections = detector.process_bboxes(results, image_id, image_path.split('.')[0], image_height, image_width)\n        \n        # Add the detections to the list\n        all_detections.extend(detections)\n    \n    # Convert detections list to a DataFrame\n    df = pd.DataFrame(all_detections)\n    \n    # Save to CSV\n    df.to_csv(\"submission.csv\", index=False)\n    print(\"Detection results saved to dummy.csv\")\n\nif __name__ == \"__main__\":\n    main()\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nop=pd.read_csv(\"/kaggle/working/submission.csv\")\nop","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labels_path = '/kaggle/input/dlp-object-detection/final_dlp_data/final_dlp_data/test/images'\nprint(len(os.listdir(labels_path)))","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}