{"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":"none","dataSources":[{"sourceId":67836,"databundleVersionId":7527339,"sourceType":"competition"}],"dockerImageVersionId":30646,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"pip install pybboxes","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2024-02-23T17:48:10.705626Z","iopub.execute_input":"2024-02-23T17:48:10.706017Z","iopub.status.idle":"2024-02-23T17:48:29.103126Z","shell.execute_reply.started":"2024-02-23T17:48:10.705975Z","shell.execute_reply":"2024-02-23T17:48:29.101387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\n\nimport cv2\nfrom tqdm import tqdm\nimport pybboxes as pbx\n\nimport matplotlib.pyplot as plt\nimport colorsys","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-02-23T17:48:29.105596Z","iopub.execute_input":"2024-02-23T17:48:29.105993Z","iopub.status.idle":"2024-02-23T17:48:29.890327Z","shell.execute_reply.started":"2024-02-23T17:48:29.105958Z","shell.execute_reply":"2024-02-23T17:48:29.888974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create Data Frame\n\nWe will create a dataframe from the input dataset. This will seve easy analysis and further modeling.","metadata":{}},{"cell_type":"code","source":"with open(\n    '/kaggle/input/dl-enigma-10-sust-cse-carnival-2024/dlenigma1/BadODD/badodd.txt', 'r'\n) as f:\n    class_labels = [line.strip().replace('_', ' ') for line in f.readlines()]\n\nclass_label_map = {class_labels[i]: i for i in range(len(class_labels))}\nclass_label_map","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:48:53.961188Z","iopub.execute_input":"2024-02-23T17:48:53.961660Z","iopub.status.idle":"2024-02-23T17:48:53.979101Z","shell.execute_reply.started":"2024-02-23T17:48:53.961612Z","shell.execute_reply":"2024-02-23T17:48:53.977069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_root = '/kaggle/input/dl-enigma-10-sust-cse-carnival-2024/dlenigma1/BadODD'\n\ndef get_possible_box_format(bbox, input_shape=None):\n    voc_bbox = pbx.convert_bbox(\n        bbox, from_type=\"yolo\", to_type=\"voc\", image_size=input_shape\n    )\n    coco_bbox = pbx.convert_bbox(\n        bbox, from_type=\"yolo\", to_type=\"coco\", image_size=input_shape\n    )\n    voc_bbox  = ', '.join(map(str, voc_bbox))\n    coco_bbox = ', '.join(map(str, coco_bbox))\n    yolo_bbox = ', '.join(map(str, bbox))\n    return voc_bbox, coco_bbox, yolo_bbox\n\ndef prepare_dataframe(data_set='train'):\n    image_path = os.path.join(data_root, 'images', data_set)\n    label_path = os.path.join(data_root, 'labels', data_set)\n\n    data = []\n    for image_file in tqdm(os.listdir(image_path), desc=f'processing {data_set} set'):\n        img_h, img_w = cv2.imread(os.path.join(image_path, image_file)).shape[:2]\n        image_id = image_file.split('.')[0]\n        with open(os.path.join(label_path, image_id + '.txt'), 'r') as f:\n            lines = f.readlines()\n            for line in lines:\n                class_label, *bbox = map(float, line.strip().split())\n                class_label = int(class_label)\n                voc_bbox, coco_bbox, yolo_bbox = get_possible_box_format(\n                    bbox,  input_shape=(img_w, img_h)\n                )\n                class_name = class_labels[class_label]\n                data.append(\n                    {\n                        'image_id': image_id, \n                        'voc_bbox': voc_bbox, \n                        'coco_bbox': coco_bbox,\n                        'yolo_bbox': yolo_bbox,\n                        'class_label': class_label,\n                        'class_name': class_name,\n                        'image_height': img_h,\n                        'image_width': img_w,\n\n                    }\n                )\n    df = pd.DataFrame(data)\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:48:56.488751Z","iopub.execute_input":"2024-02-23T17:48:56.489177Z","iopub.status.idle":"2024-02-23T17:48:56.505616Z","shell.execute_reply.started":"2024-02-23T17:48:56.489145Z","shell.execute_reply":"2024-02-23T17:48:56.503332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = prepare_dataframe(data_set='train')","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:48:56.920359Z","iopub.execute_input":"2024-02-23T17:48:56.920826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualization\n\nLet's test some sample and visualize it.","metadata":{}},{"cell_type":"code","source":"thickness = 5\nfont_scale = 1.2\nfont_thickness = 2\n\ndef generate_colors(num_classes):\n    hsv_tuples = [(x / num_classes, 1., 1.) for x in range(num_classes)]\n    colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n    colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))\n    return colors\n\ndef draw_boxes(image_path, df):\n    image = cv2.imread(image_path)\n    colors = generate_colors(len(class_labels))\n    class_color_map = {class_labels[i]: colors[i] for i in range(len(class_labels))}\n    \n    for _, row in df.iterrows():\n        box = eval(row['voc_bbox'])\n        class_name = row['class_name']\n        color = class_color_map[class_name]\n        box = [int(coord) for coord in box]\n        \n        cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), color, thickness)\n        cv2.putText(\n            image, \n            class_name, \n            (box[0], box[1] - 5), \n            cv2.FONT_HERSHEY_SIMPLEX, \n            font_scale, \n            color, \n            font_thickness\n        )\n\n    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    plt.figure(figsize=(20,10))\n    plt.imshow(image_rgb)\n    plt.axis('off')\n    plt.show()\n\n\nimage_id = train_df.sample().reset_index().loc[0, 'image_id']\nimage_path = '/kaggle/input/dl-enigma-10-sust-cse-carnival-2024/dlenigma1/BadODD/images/train'\nimage_path = os.path.join(image_path, image_id + '.jpg')\ndf_image = train_df[train_df['image_id'] == image_id]\ndraw_boxes(image_path, df_image)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.to_csv('train.csv',index=False)\ntrain_df.sample()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}