{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nprint(tf.__version__)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport os\nimport cv2\nfrom PIL import Image, ImageDraw\nfrom ast import literal_eval\nimport matplotlib.pyplot as plt\nimport urllib\nfrom tqdm.notebook import tqdm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!cp -r /kaggle/input/efficientdet-code/EfficientDet /kaggle/working/","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls /kaggle/working/EfficientDet","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# !git clone https://github.com/xuannianz/EfficientDet.git\nos.chdir('/kaggle/working/EfficientDet/')\n!python setup.py build_ext --inplace","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from model import efficientdet\nfrom utils import preprocess_image, postprocess_boxes\nfrom utils.draw_boxes import draw_boxes\n\nphi = 3\nweighted_bifpn = True\nmodel_path = '/kaggle/input/efficientdet-version1-weights/phi3_stage1_9286.h5'\nimage_sizes = (512, 640, 768, 896, 1024, 1280, 1408)\nimage_size = image_sizes[phi]\n\nnum_classes = 1\nscore_threshold = 0.5\n_, model = efficientdet(phi=phi,\n                            weighted_bifpn=weighted_bifpn,\n                            num_classes=num_classes,\n                            score_threshold=score_threshold)\nmodel.load_weights(model_path, by_name=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import glob\nfrom tqdm import tqdm\nfrom pathlib import Path\n\nDIR_INPUT = '/kaggle/input/global-wheat-detection'\ndata_dir = '/kaggle/input/global-wheat-detection/test'\nsubmission = pd.read_csv(f'{DIR_INPUT}/sample_submission.csv')\n\nroot_image = Path(\"/kaggle/input/global-wheat-detection/test\")\ntest_images = [root_image / f\"{img}.jpg\" for img in submission.image_id]\n\nsubmission = []\n\ndef clahe(image, clip_limit=4.0, tile_grid_size=(8, 8)): # image is in RGB already, load_image in csv generator\n    lab = cv2.cvtColor(image, cv2.COLOR_RGB2LAB)\n    lab_planes = cv2.split(lab)\n    clahe = cv2.createCLAHE(clipLimit=clip_limit,tileGridSize=tile_grid_size)\n    lab_planes[0] = clahe.apply(lab_planes[0])\n    lab = cv2.merge(lab_planes)\n    return cv2.cvtColor(lab, cv2.COLOR_LAB2RGB)\n\nfor image_path in tqdm(test_images):\n    prediction_string = []\n    \n    image = cv2.imread(str(image_path))\n    image = image[:, :, ::-1]\n    image = clahe(image)\n    \n    h, w = image.shape[:2]\n    image, scale = preprocess_image(image, image_size=image_size)\n    \n    boxes, scores, labels = model.predict_on_batch([np.expand_dims(image, axis=0)])\n    boxes, scores, labels = np.squeeze(boxes), np.squeeze(scores), np.squeeze(labels)\n        \n    boxes = postprocess_boxes(boxes=boxes, scale=scale, height=h, width=w)\n    \n    # select indices which have a score above the threshold\n    indices = np.where(scores[:] > score_threshold)[0]\n\n    # select those detections\n    boxes = boxes[indices]\n    labels = labels[indices]\n    \n    for idx in range(boxes.shape[0]):\n        box,s=boxes[idx],scores[idx]\n        x_min, y_min, x_max, y_max = box\n        \n        x = round(x_min)\n        y = round(y_min)\n        w = round(x_max-x_min)\n        h = round(y_max-y_min)\n        prediction_string.append(f\"{s} {x} {y} {w} {h}\")\n        \n    prediction_string = \" \".join(prediction_string)\n    submission.append([image_path.name[:-4],prediction_string])\n\nsample_submission = pd.DataFrame(submission, columns=[\"image_id\",\"PredictionString\"])\nsample_submission.to_csv('/kaggle/working/submission.csv', index=False)\nsample_submission.head()\n# for image_path in glob.glob(\"/kaggle/input/global-wheat-detection/test/*.jpg\"):\n    \n#     image = cv2.imread(image_path)\n#     image = image[:, :, ::-1]\n    \n#     h, w = image.shape[:2]\n#     image, scale = preprocess_image(image, image_size=image_size)\n    \n#     boxes, scores, labels = model.predict_on_batch([np.expand_dims(image, axis=0)])\n#     boxes, scores, labels = np.squeeze(boxes), np.squeeze(scores), np.squeeze(labels)\n        \n#     boxes = postprocess_boxes(boxes=boxes, scale=scale, height=h, width=w)\n    \n#     # select indices which have a score above the threshold\n#     indices = np.where(scores[:] > score_threshold)[0]\n\n#     # select those detections\n#     boxes = boxes[indices]\n#     labels = labels[indices]\n    \n    \n#     for idx in range(boxes.shape[0]):\n#         box,score=boxes[idx],scores[idx]\n#         imgid.append((image_path.split(\".\")[0]).split('/')[-1])\n#         preds.append(\"{} {} {} {} {}\".format(score, int(box[0]), int(box[1]), int(box[2]-box[0]), int(box[3]-box[1])))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for index, row in sample_submission.iterrows():\n    path = '/kaggle/input/global-wheat-detection/test/' + row[\"image_id\"] + '.jpg'\n    img = cv2.imread(path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img = clahe(img)\n    \n    bboxs = row['PredictionString'].split(' ')\n    for i in range(len(bboxs)//5):\n        bbox = bboxs[i*5:(i+1)*5]\n        score, xmin, ymin, width, height = bbox\n        \n        xmin = int(float(xmin))\n        ymin = int(float(ymin))\n        xmax = xmin + int(float(width))\n        ymax = ymin + int(float(height))\n        \n        cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (255,0,0), 5)\n        \n    plt.imshow(img)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!rm -r /kaggle/working/EfficientDet/","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# sub = {\"image_id\": imgid, \"PredictionString\": preds}\n# sub = pd.DataFrame(sub)\n# sub_ = sub.groupby([\"image_id\"])['PredictionString'].apply(lambda x: ' '.join(x)).reset_index()\n# print(sub_)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# sub_.to_csv('/kaggle/working/submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# samsub=pd.read_csv(\"/kaggle/input/global-wheat-detection/sample_submission.csv\")\n# samsub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# for idx,imgid in enumerate(samsub['image_id']):\n#     samsub.iloc[idx,1]=sub_[sub_['image_id']==imgid].values[0,1]\n    \n# samsub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# samsub.to_csv('/kaggle/working/submission.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# img = cv2.imread('/kaggle/input/global-wheat-detection/test/' + imgid[0] + '.jpg')\n# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n# preds = sub_[sub_['image_id']==imgid[0]].PredictionString.values\n# preds = preds[0].split(' ')\n\n# for i in range(len(preds)//5):\n#     conf, xmin, ymin, width, height = preds[:5]\n#     preds = preds[5:]\n    \n#     xmin = int(xmin)\n#     ymin = int(ymin)\n#     width = int(width)\n#     height = int(height)\n    \n#     cv2.rectangle(img, (xmin,ymin), (xmin+width, ymin+height), (255, 0, 0), 2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# import matplotlib.pyplot as plt\n# plt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# import pandas as pd\n\n# sub=pd.read_csv('/kaggle/input/efficientdet-version1-weights/submission.csv')\n# sub.to_csv('/kaggle/working/submission.csv',index=False)","execution_count":null,"outputs":[]}],"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"}},"nbformat":4,"nbformat_minor":4}