{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":19989,"databundleVersionId":1160143,"sourceType":"competition"}],"dockerImageVersionId":30626,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport cv2\nimport csv\nimport glob\nimport pandas as pd\nimport numpy as np\nimport random\nimport itertools\nfrom collections import Counter\nfrom math import ceil\nimport matplotlib.pyplot as plt\nfrom tqdm.notebook import tqdm\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:23:50.439705Z","iopub.execute_input":"2024-01-01T07:23:50.440968Z","iopub.status.idle":"2024-01-01T07:23:51.216822Z","shell.execute_reply.started":"2024-01-01T07:23:50.440913Z","shell.execute_reply":"2024-01-01T07:23:51.215881Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def skip_csv_header(file):\n    has_header = csv.Sniffer().has_header(file.read(1024))\n    file.seek(0)\n    if has_header:\n        next(file)\n\n\ndef total_image_list(image_folder_path):\n    total_img_list = [os.path.basename(img_path_name) for img_path_name in glob.glob(os.path.join(image_folder_path, \"*.jpg\"))]\n    return total_img_list\n\ndef draw_rect(img, bboxes, color=None):\n    img = img.copy()\n    bboxes = bboxes[:, :4]\n    bboxes = bboxes.reshape(-1, 4)\n    for bbox in bboxes:\n        pt1, pt2 = (bbox[0], bbox[1]), (bbox[2], bbox[3])\n        pt1 = int(pt1[0]), int(pt1[1])\n        pt2 = int(pt2[0]), int(pt2[1])\n        img = cv2.rectangle(img.copy(), pt1, pt2, color, int(max(img.shape[:2]) / 200))\n    return img\n\ndef plot_multiple_img(img_matrix_list, title_list, ncols, main_title=\"\"):\n    fig, myaxes = plt.subplots(figsize=(20, 15), nrows=ceil(len(img_matrix_list) / ncols), ncols=ncols, squeeze=False)\n    fig.suptitle(main_title, fontsize = 30)\n    fig.subplots_adjust(wspace=0.3)\n    fig.subplots_adjust(hspace=0.3)\n    for i, (img, title) in enumerate(zip(img_matrix_list, title_list)):\n        myaxes[i // ncols][i % ncols].imshow(img)\n        myaxes[i // ncols][i % ncols].set_title(title, fontsize=15)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:23:56.348897Z","iopub.execute_input":"2024-01-01T07:23:56.349551Z","iopub.status.idle":"2024-01-01T07:23:56.366885Z","shell.execute_reply.started":"2024-01-01T07:23:56.349503Z","shell.execute_reply":"2024-01-01T07:23:56.365963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/global-wheat-detection/train.csv\")  \nimage_folder_path = \"/kaggle/input/global-wheat-detection/train/\"","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:24:09.181996Z","iopub.execute_input":"2024-01-01T07:24:09.182419Z","iopub.status.idle":"2024-01-01T07:24:09.614480Z","shell.execute_reply.started":"2024-01-01T07:24:09.182385Z","shell.execute_reply":"2024-01-01T07:24:09.613071Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"bboxes = np.stack(train['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=',')))\nfor i, column in enumerate(['x_min', 'y_min', 'width', 'height']):\n    train[column] = bboxes[:,i]\n    \ntrain[\"x_max\"] = train.apply(lambda col: col.x_min + col.width, axis=1)\ntrain[\"y_max\"] = train.apply(lambda col: col.y_min + col.height, axis = 1)\ntrain.drop(columns=['bbox'], inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:24:23.387896Z","iopub.execute_input":"2024-01-01T07:24:23.388327Z","iopub.status.idle":"2024-01-01T07:24:32.445564Z","shell.execute_reply.started":"2024-01-01T07:24:23.388295Z","shell.execute_reply":"2024-01-01T07:24:32.444525Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:24:40.412279Z","iopub.execute_input":"2024-01-01T07:24:40.412678Z","iopub.status.idle":"2024-01-01T07:24:40.446149Z","shell.execute_reply.started":"2024-01-01T07:24:40.412647Z","shell.execute_reply":"2024-01-01T07:24:40.444663Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train[train[\"x_max\"] > 1024]\ntrain[train[\"y_max\"] > 1024]\ntrain[train[\"x_min\"] < 0]\ntrain[train[\"y_min\"] < 0]","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:24:48.037426Z","iopub.execute_input":"2024-01-01T07:24:48.037873Z","iopub.status.idle":"2024-01-01T07:24:48.073862Z","shell.execute_reply.started":"2024-01-01T07:24:48.037837Z","shell.execute_reply":"2024-01-01T07:24:48.072496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_max = np.array(train[\"x_max\"].values.tolist())\ny_max = np.array(train[\"y_max\"].values.tolist())\ntrain[\"x_max\"] = np.where(x_max > 1024, 1024, x_max).tolist()\ntrain[\"y_max\"] = np.where(y_max > 1024, 1024, y_max).tolist()","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:24:59.474888Z","iopub.execute_input":"2024-01-01T07:24:59.475301Z","iopub.status.idle":"2024-01-01T07:24:59.567957Z","shell.execute_reply.started":"2024-01-01T07:24:59.475269Z","shell.execute_reply":"2024-01-01T07:24:59.566790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del train[\"width\"]\ndel train[\"height\"]\ndel train[\"source\"]\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:25:06.707063Z","iopub.execute_input":"2024-01-01T07:25:06.707849Z","iopub.status.idle":"2024-01-01T07:25:06.728349Z","shell.execute_reply.started":"2024-01-01T07:25:06.707805Z","shell.execute_reply":"2024-01-01T07:25:06.726961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train[\"class\"] = \"1\"","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:25:16.427870Z","iopub.execute_input":"2024-01-01T07:25:16.428464Z","iopub.status.idle":"2024-01-01T07:25:16.435528Z","shell.execute_reply.started":"2024-01-01T07:25:16.428424Z","shell.execute_reply":"2024-01-01T07:25:16.434287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def check_file_type(image_folder_path):\n    extension_type = []\n    file_list = os.listdir(image_folder_path)\n    for file in file_list:\n        extension_type.append(file.rsplit(\".\", 1)[1].lower())\n    print(Counter(extension_type).keys())\n    print(Counter(extension_type).values())\n    \ncheck_file_type(image_folder_path)","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:25:18.664081Z","iopub.execute_input":"2024-01-01T07:25:18.665424Z","iopub.status.idle":"2024-01-01T07:25:19.310574Z","shell.execute_reply.started":"2024-01-01T07:25:18.665371Z","shell.execute_reply":"2024-01-01T07:25:19.309542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train[\"image_id\"] = train[\"image_id\"].apply(lambda x: str(x) + \".jpg\")\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:25:28.887620Z","iopub.execute_input":"2024-01-01T07:25:28.888536Z","iopub.status.idle":"2024-01-01T07:25:28.969186Z","shell.execute_reply.started":"2024-01-01T07:25:28.888491Z","shell.execute_reply":"2024-01-01T07:25:28.968279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train[\"image_id\"] = train[\"image_id\"].astype(\"str\")","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:25:37.405744Z","iopub.execute_input":"2024-01-01T07:25:37.406180Z","iopub.status.idle":"2024-01-01T07:25:37.419731Z","shell.execute_reply.started":"2024-01-01T07:25:37.406145Z","shell.execute_reply":"2024-01-01T07:25:37.418387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.to_csv(\"wheat.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:25:44.512103Z","iopub.execute_input":"2024-01-01T07:25:44.512601Z","iopub.status.idle":"2024-01-01T07:25:45.459654Z","shell.execute_reply.started":"2024-01-01T07:25:44.512564Z","shell.execute_reply":"2024-01-01T07:25:45.458280Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def check_image_size(image_folder_path):\n    total_img_list = glob.glob(os.path.join(image_folder_path,\"*\"))\n    counter = 0\n    for image in tqdm(total_img_list, desc = \"Checking in progress\"):\n        try:\n            img = cv2.imread(image)\n            height, width = img.shape[1], img.shape[0]\n            if not (height == 1024 and width == 1024):\n                counter = counter + 1\n        except:\n            print(\"This {} is problematic.\".format(image))\n    return counter \n        ","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:25:48.387615Z","iopub.execute_input":"2024-01-01T07:25:48.388313Z","iopub.status.idle":"2024-01-01T07:25:48.396228Z","shell.execute_reply.started":"2024-01-01T07:25:48.388277Z","shell.execute_reply":"2024-01-01T07:25:48.394855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"check_image_size(image_folder_path)","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:25:58.922075Z","iopub.execute_input":"2024-01-01T07:25:58.922510Z","iopub.status.idle":"2024-01-01T07:27:32.809777Z","shell.execute_reply.started":"2024-01-01T07:25:58.922466Z","shell.execute_reply":"2024-01-01T07:27:32.808623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"## our new dataset\nwheat = pd.read_csv(\"wheat.csv\") \nimage_folder_path = \"/kaggle/input/global-wheat-detection/train/\"\nimage_annotation_file = \"wheat.csv\"","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:28:01.000447Z","iopub.execute_input":"2024-01-01T07:28:01.000885Z","iopub.status.idle":"2024-01-01T07:28:01.151474Z","shell.execute_reply.started":"2024-01-01T07:28:01.000850Z","shell.execute_reply":"2024-01-01T07:28:01.150173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"wheat.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:28:03.804521Z","iopub.execute_input":"2024-01-01T07:28:03.805018Z","iopub.status.idle":"2024-01-01T07:28:03.821242Z","shell.execute_reply.started":"2024-01-01T07:28:03.804951Z","shell.execute_reply":"2024-01-01T07:28:03.820289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def sanity_tally(image_folder_path, image_annotation_file):\n    img_dict = {}\n    with open(image_annotation_file, \"r\") as file:\n        skip_csv_header(file)\n        for row in file:\n            try:\n                image_name, x_min, y_min, x_max, y_max, class_idx = row.split(\",\")\n                if image_name not in img_dict:\n                    img_dict[image_name] = list()\n                img_dict[image_name].append(\n                    [float(x_min), float(y_min), float(x_max), float(y_max), int(class_idx)]\n                )\n            except ValueError:\n                print(\"Could not convert float to string, likely that your data has empty values.\")\n        \n    img_annotation_list = [*img_dict]\n    total_img_list = total_image_list(image_folder_path)\n    if set(img_annotation_list) == set(total_img_list):\n        print(\"Sanity Check Status: True\")\n    else:\n        print(\"Sanity Check Status: Failed. \\nThe elements in wheat/train.csv but not in the train image folder is {}. \\nThe elements in train image folder but not in wheat/train.csv is {}\".format(\n                set(img_annotation_list) - set(total_img_list), set(total_img_list) - set(img_annotation_list)))\n        return list(set(img_annotation_list) - set(total_img_list)), list(set(total_img_list) - set(img_annotation_list))","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:28:13.986270Z","iopub.execute_input":"2024-01-01T07:28:13.986726Z","iopub.status.idle":"2024-01-01T07:28:13.998471Z","shell.execute_reply.started":"2024-01-01T07:28:13.986689Z","shell.execute_reply":"2024-01-01T07:28:13.996910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"set_diff1, set_diff2 = sanity_tally(image_folder_path, image_annotation_file = image_annotation_file)\n\nprint(\"There are {} images without annotations in the train/wheat.csv\".format(len(set_diff2)))","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:28:24.856068Z","iopub.execute_input":"2024-01-01T07:28:24.856520Z","iopub.status.idle":"2024-01-01T07:28:25.430133Z","shell.execute_reply.started":"2024-01-01T07:28:24.856474Z","shell.execute_reply":"2024-01-01T07:28:25.428777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_random_images(image_folder_path, image_annotation_file, num = 12):\n    img_dict = {}\n    with open(image_annotation_file, \"r\") as file:\n        skip_csv_header(file)\n        for row in file:\n            try:\n                image_name, x_min, y_min, x_max, y_max, class_idx = row.split(\",\")\n                if image_name not in img_dict:\n                    img_dict[image_name] = list()\n                img_dict[image_name].append(\n                    [float(x_min), float(y_min), float(x_max), float(y_max), int(class_idx)]\n                )\n            except ValueError:\n                print(\"Could not convert float to string, likely that your data has empty values.\")\n\n    # randomly choose 12 images to plot\n    img_files_list = np.random.choice(list(img_dict.keys()), num)\n    print(\"The images' names are {}\".format(img_files_list))\n    img_matrix_list = []\n    \n    for img_file in img_files_list:\n        image_file_path = os.path.join(image_folder_path, img_file)\n        img = cv2.imread(image_file_path)[:,:,::-1]  \n        img_matrix_list.append(img)\n\n    \n    return plot_multiple_img(img_matrix_list, title_list = img_files_list, ncols = 4, main_title=\"Wheat Images\")","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:28:36.250769Z","iopub.execute_input":"2024-01-01T07:28:36.251204Z","iopub.status.idle":"2024-01-01T07:28:36.262091Z","shell.execute_reply.started":"2024-01-01T07:28:36.251169Z","shell.execute_reply":"2024-01-01T07:28:36.261231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_random_images(image_folder_path, image_annotation_file, num = 12)","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:28:49.379128Z","iopub.execute_input":"2024-01-01T07:28:49.379564Z","iopub.status.idle":"2024-01-01T07:28:55.191815Z","shell.execute_reply.started":"2024-01-01T07:28:49.379502Z","shell.execute_reply":"2024-01-01T07:28:55.187610Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def random_bbox_check(image_folder_path, image_annotation_file, num = 12):\n    img_dict = {}\n    labels = [\"wheat\", \"no wheat\"]\n    with open(image_annotation_file, \"r\") as file:\n        skip_csv_header(file)\n        for row in file:\n            try:\n                image_name, x_min, y_min, x_max, y_max, class_idx = row.split(\",\")\n                if image_name not in img_dict:\n                    img_dict[image_name] = list()\n                img_dict[image_name].append(\n                    [float(x_min), float(y_min), float(x_max), float(y_max), int(class_idx)]\n                )\n            except ValueError:\n                print(\"Could not convert float to string, likely that your data has empty values.\")\n\n    # randomly choose 12 image.\n    img_files_list = np.random.choice(list(img_dict.keys()), num)\n    print(\"The images' names are {}\".format(img_files_list))\n    image_file_path_list = []\n\n    bbox_list = []\n    img_matrix_list = []\n    random_image_matrix_list = []\n    \n    for img_file in img_files_list:\n        image_file_path = os.path.join(image_folder_path, img_file)\n        img = cv2.imread(image_file_path)[:,:,::-1]  \n        height, width, channels = img.shape\n        bbox_list.append(img_dict[img_file])\n        img_matrix_list.append(img)\n\n    \n    final_bbox_list = []\n    for bboxes, img in zip(bbox_list, img_matrix_list):\n        final_bbox_array = np.array([])\n        #bboxes is a 2d array [[...], [...]]\n        for bbox in bboxes:\n            bbox = np.array(bbox).reshape(1,5)\n            final_bbox_array = np.append(final_bbox_array, bbox)\n        final_bbox_array = final_bbox_array.reshape(-1,5)\n        random_image = draw_rect(img.copy(), final_bbox_array.copy(), color = (255,0,0))\n        random_image_matrix_list.append(random_image)\n    plot_multiple_img(random_image_matrix_list, title_list = img_files_list, ncols = 4, main_title=\"Bounding Box Wheat Images\")    \n    ","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:29:17.635073Z","iopub.execute_input":"2024-01-01T07:29:17.635517Z","iopub.status.idle":"2024-01-01T07:29:17.650189Z","shell.execute_reply.started":"2024-01-01T07:29:17.635484Z","shell.execute_reply":"2024-01-01T07:29:17.649277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"random_bbox_check(image_folder_path, image_annotation_file)","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:29:21.104810Z","iopub.execute_input":"2024-01-01T07:29:21.105562Z","iopub.status.idle":"2024-01-01T07:29:27.201448Z","shell.execute_reply.started":"2024-01-01T07:29:21.105524Z","shell.execute_reply":"2024-01-01T07:29:27.200305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Albumentations\nimport albumentations as A","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:29:34.539877Z","iopub.execute_input":"2024-01-01T07:29:34.540345Z","iopub.status.idle":"2024-01-01T07:29:36.216925Z","shell.execute_reply.started":"2024-01-01T07:29:34.540310Z","shell.execute_reply":"2024-01-01T07:29:36.216010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_folder_path = \"/kaggle/input/global-wheat-detection/train/\"\nchosen_image = cv2.imread(os.path.join(image_folder_path, \"1ee6b9669.jpg\"))[:,:,::-1]\nplt.imshow(chosen_image)","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:29:57.892051Z","iopub.execute_input":"2024-01-01T07:29:57.892679Z","iopub.status.idle":"2024-01-01T07:29:58.634903Z","shell.execute_reply.started":"2024-01-01T07:29:57.892643Z","shell.execute_reply":"2024-01-01T07:29:58.633851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"chosen_image_dataframe = wheat.loc[wheat[\"image_id\"]==\"1ee6b9669.jpg\",[\"x_min\",\"y_min\",\"x_max\",\"y_max\",\"class\"]]\nbbox_array_of_chosen_image = np.array(chosen_image_dataframe.values.tolist())\nbbox_array_of_chosen_image.shape","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:30:04.353801Z","iopub.execute_input":"2024-01-01T07:30:04.354775Z","iopub.status.idle":"2024-01-01T07:30:04.397853Z","shell.execute_reply.started":"2024-01-01T07:30:04.354731Z","shell.execute_reply":"2024-01-01T07:30:04.396573Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"draw_chosen_image = draw_rect(chosen_image.copy(), bbox_array_of_chosen_image.copy(), color = (255,0,0))\nplt.imshow(draw_chosen_image)","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:30:07.855693Z","iopub.execute_input":"2024-01-01T07:30:07.856196Z","iopub.status.idle":"2024-01-01T07:30:08.470947Z","shell.execute_reply.started":"2024-01-01T07:30:07.856158Z","shell.execute_reply":"2024-01-01T07:30:08.469811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"albumentation_list = [A.RandomSunFlare(p=1), A.RandomFog(p=1), A.RandomBrightness(p=1),\n                      A.RandomCrop(p=1,height = 512, width = 512), A.Rotate(p=1, limit=90),\n                      A.RGBShift(p=1), A.RandomSnow(p=1),\n                      A.HorizontalFlip(p=1), A.VerticalFlip(p=1), A.RandomContrast(limit = 0.5,p = 1),\n                      A.HueSaturationValue(p=1,hue_shift_limit=20, sat_shift_limit=30, val_shift_limit=50)]\n\nimg_matrix_list = []\nbboxes_list = []\nfor aug_type in albumentation_list:\n    img = aug_type(image = chosen_image)['image']\n    img_matrix_list.append(img)\n\nimg_matrix_list.insert(0,chosen_image)    \n\ntitles_list = [\"Original\",\"RandomSunFlare\",\"RandomFog\",\"RandomBrightness\",\n               \"RandomCrop\",\"Rotate\", \"RGBShift\", \"RandomSnow\",\"HorizontalFlip\", \"VerticalFlip\", \"RandomContrast\",\"HSV\"]\n\n##reminder of helper function\ndef plot_multiple_img(img_matrix_list, title_list, ncols, main_title=\"\"):\n    fig, myaxes = plt.subplots(figsize=(20, 15), nrows=3, ncols=ncols, squeeze=False)\n    fig.suptitle(main_title, fontsize = 30)\n    fig.subplots_adjust(wspace=0.3)\n    fig.subplots_adjust(hspace=0.3)\n    for i, (img, title) in enumerate(zip(img_matrix_list, title_list)):\n        myaxes[i // ncols][i % ncols].imshow(img)\n        myaxes[i // ncols][i % ncols].set_title(title, fontsize=15)\n    plt.show()\n    \nplot_multiple_img(img_matrix_list, titles_list, ncols = 4,main_title=\"Different Types of Augmentations\")","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:30:31.051139Z","iopub.execute_input":"2024-01-01T07:30:31.051570Z","iopub.status.idle":"2024-01-01T07:30:36.485813Z","shell.execute_reply.started":"2024-01-01T07:30:31.051535Z","shell.execute_reply":"2024-01-01T07:30:36.482798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"chosen_image = cv2.imread(os.path.join(image_folder_path, \"1ee6b9669.jpg\"))[:,:,::-1]\nchosen_image_dataframe = wheat.loc[wheat[\"image_id\"]==\"1ee6b9669.jpg\",[\"x_min\",\"y_min\",\"x_max\",\"y_max\"]]\nbbox_array_of_chosen_image = np.array(chosen_image_dataframe.values.tolist())\nlabels_of_chosen_image = np.ones((len(bbox_array_of_chosen_image),))\n\n# A caution here, this competition has all labels to be 1, so a neat trick is just to use np.ones to populate the label fields.\n# However, when dealing with multiple classes, you should not do this and instead just take the labels from the dataframe accordingly.","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:30:53.054774Z","iopub.execute_input":"2024-01-01T07:30:53.055918Z","iopub.status.idle":"2024-01-01T07:30:53.108327Z","shell.execute_reply.started":"2024-01-01T07:30:53.055872Z","shell.execute_reply":"2024-01-01T07:30:53.107066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def draw_rect_with_labels(img, bboxes,class_id, class_dict, color=None):\n    img = img.copy()\n    bboxes = bboxes[:, :4]\n    bboxes = bboxes.reshape(-1, 4)\n    for bbox, label in zip(bboxes, class_id):\n        pt1, pt2 = (bbox[0], bbox[1]), (bbox[2], bbox[3])\n        pt1 = int(pt1[0]), int(pt1[1])\n        pt2 = int(pt2[0]), int(pt2[1])\n        class_name = class_dict[label]\n        ((text_width, text_height), _) = cv2.getTextSize(class_name, cv2.FONT_HERSHEY_SIMPLEX, 0.35, 1) \n        img = cv2.rectangle(img.copy(), pt1, pt2, color, int(max(img.shape[:2]) / 200))\n        img = cv2.putText(img.copy(), class_name, (int(bbox[0]), int(bbox[1]) - int(0.3 * text_height)), cv2.FONT_HERSHEY_SIMPLEX,fontScale=1,color = (255,255,255), lineType=cv2.LINE_AA)\n    return img","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:30:57.403056Z","iopub.execute_input":"2024-01-01T07:30:57.404020Z","iopub.status.idle":"2024-01-01T07:30:57.414873Z","shell.execute_reply.started":"2024-01-01T07:30:57.403952Z","shell.execute_reply":"2024-01-01T07:30:57.413543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ver_flip = A.Compose([\n        A.VerticalFlip(p=1),\n    ], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']})\n\n\nver_flip_annotations = ver_flip(image=chosen_image, bboxes=bbox_array_of_chosen_image, labels=labels_of_chosen_image)\nver_flip_annotations['bboxes'] = [list(bbox) for bbox in ver_flip_annotations['bboxes']]","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:31:00.642757Z","iopub.execute_input":"2024-01-01T07:31:00.643200Z","iopub.status.idle":"2024-01-01T07:31:00.664679Z","shell.execute_reply.started":"2024-01-01T07:31:00.643166Z","shell.execute_reply":"2024-01-01T07:31:00.663613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ver_flip_img = draw_rect_with_labels(img = ver_flip_annotations['image'], bboxes = np.array(ver_flip_annotations['bboxes']),\n                          class_id = ver_flip_annotations['labels'], class_dict = {0: \"background\",1: \"wheat\"}, color=(255,0,0))\n\n## using my good old plotting functions\ndef plot_multiple_img(img_matrix_list, title_list, ncols, main_title=\"\"):\n    fig, myaxes = plt.subplots(figsize=(20, 15), nrows=1, ncols=ncols, squeeze=False)\n    fig.suptitle(main_title, fontsize = 30)\n    fig.subplots_adjust(wspace=0.3)\n    fig.subplots_adjust(hspace=0.3)\n    for i, (img, title) in enumerate(zip(img_matrix_list, title_list)):\n        myaxes[i // ncols][i % ncols].imshow(img)\n        myaxes[i // ncols][i % ncols].set_title(title, fontsize=15)\n    plt.show()\n    \nimg_matrix_list = [draw_chosen_image, ver_flip_img]\ntitles_list = [\"Original\", \"VerticalFlipped\"]\n\nplot_multiple_img(img_matrix_list, titles_list, ncols = 2,main_title=\"Vertical Flip\")","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:31:09.990570Z","iopub.execute_input":"2024-01-01T07:31:09.991029Z","iopub.status.idle":"2024-01-01T07:31:11.635089Z","shell.execute_reply.started":"2024-01-01T07:31:09.990967Z","shell.execute_reply":"2024-01-01T07:31:11.633754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hor_flip = A.Compose([\n        A.HorizontalFlip(p=1),\n    ], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']})\n\n\nhor_flip_annotations = hor_flip(image=chosen_image, bboxes=bbox_array_of_chosen_image, labels=labels_of_chosen_image)\nhor_flip_annotations['bboxes'] = [list(bbox) for bbox in hor_flip_annotations['bboxes']]\n\n\nhor_flip_img = draw_rect_with_labels(img = hor_flip_annotations['image'], bboxes = np.array(hor_flip_annotations['bboxes']),\n                          class_id = hor_flip_annotations['labels'], class_dict = {0: \"background\",1: \"wheat\"}, color=(255,0,0))\n    \nimg_matrix_list = [draw_chosen_image, hor_flip_img]\ntitles_list = [\"Original\", \"HorizontalFlipped\"]\n\nplot_multiple_img(img_matrix_list, titles_list, ncols = 2,main_title=\"Horizontal Flip\")","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:31:22.121424Z","iopub.execute_input":"2024-01-01T07:31:22.121956Z","iopub.status.idle":"2024-01-01T07:31:23.768009Z","shell.execute_reply.started":"2024-01-01T07:31:22.121912Z","shell.execute_reply":"2024-01-01T07:31:23.765967Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform = A.Compose([\n    A.CoarseDropout(max_height=100, max_width=100, p = 1),\n    A.RandomBrightnessContrast(p=0.9),\n    A.HueSaturationValue(\n                        hue_shift_limit=0.2,\n                        sat_shift_limit=0.2,\n                        val_shift_limit=0.2,\n                        p=0.9,\n                        )\n])\nchosen_image = cv2.imread(os.path.join(image_folder_path, \"1ee6b9669.jpg\"))[:,:,::-1]\naugmented_image = transform(image=chosen_image)['image']\nplt.imshow(augmented_image)","metadata":{"execution":{"iopub.status.busy":"2024-01-01T07:31:30.727149Z","iopub.execute_input":"2024-01-01T07:31:30.727563Z","iopub.status.idle":"2024-01-01T07:31:31.342175Z","shell.execute_reply.started":"2024-01-01T07:31:30.727533Z","shell.execute_reply":"2024-01-01T07:31:31.340817Z"},"trusted":true},"execution_count":null,"outputs":[]}]}