{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport tensorflow as tf\nimport cv2\nimport json\nimport numpy as np\nimport os\nimport time\nimport glob\n\n# forked a github repository to add fine tuning to efficient det\n!cp -r ../input/repository-efficient/EfficientDet-master/* ./\n!python setup.py build_ext --inplace\nfrom model import efficientdet\n\n# You can write up to 5GB 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 sessio","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"def get_frozen_graph(graph_file):\n    with tf.io.gfile.GFile(graph_file, \"rb\") as f:\n        graph_def = tf.compat.v1.GraphDef()\n        graph_def.ParseFromString(f.read())\n    return graph_def\n\ndef preprocess_image(image, image_size):\n    # image, RGB\n    image_height, image_width = image.shape[:2]\n    if image_height > image_width:\n        scale = image_size / image_height\n        resized_height = image_size\n        resized_width = int(image_width * scale)\n    else:\n        scale = image_size / image_width\n        resized_height = int(image_height * scale)\n        resized_width = image_size\n\n    image = cv2.resize(image, (resized_width, resized_height))\n    image = image.astype(np.float32)\n    image /= 255.\n    mean = [0.485, 0.456, 0.406]\n    std = [0.229, 0.224, 0.225]\n    image -= mean\n    image /= std\n    pad_h = image_size - resized_height\n    pad_w = image_size - resized_width\n    image = np.pad(image, [(0, pad_h), (0, pad_w), (0, 0)], mode='constant')\n\n    return image, scale\n\ndef postprocess_boxes(boxes, scale, height, width):\n    c_boxes = boxes.copy()\n    c_boxes /= scale\n    c_boxes[:, 0] = np.clip(c_boxes[:, 0], 0, width - 1)\n    c_boxes[:, 1] = np.clip(c_boxes[:, 1], 0, height - 1)\n    c_boxes[:, 2] = np.clip(c_boxes[:, 2], 0, width - 1)\n    c_boxes[:, 3] = np.clip(c_boxes[:, 3], 0, height - 1)\n    return c_boxes\n\n# import keras\nimport numpy as np\nfrom tensorflow import keras\n\nfrom utils.compute_overlap import compute_overlap\nfrom utils.anchors import anchors_for_shape\n\n\nphi = 4\nmodel_path = '/kaggle/input/efficientdetfrozen/efficientdet_0-80.pb'\nimage_sizes = (512, 640, 768, 896, 1024, 1280, 1408)\nimage_size = image_sizes[phi]\nclasses = [\n    'wheat'\n]\nnum_classes = len(classes)\n\nscore_threshold = 0.70\n\n_, model = efficientdet(phi=phi,\n                            weighted_bifpn=True,\n                            num_classes=num_classes,\n                            score_threshold=score_threshold,\n                            finetuned_num_classes=1)\n\n#model.load_weights(model_path, by_name=True)\n#model.load_weights('/kaggle/input/efficientdetwheat-may/EfficientDet-23-0.8077.h5', by_name=True)\nmodel.load_weights('/kaggle/input/efficientdet-04-084/EfficientDet-04-0.8407.h5', by_name=True)\n\n\nresult_data = []\nfor image_path in glob.glob('/kaggle/input/global-wheat-detection/test/*.jpg'):\n    image_name = image_path.split('/')[-1]\n    image = cv2.imread(image_path)\n    src_image = image.copy()\n    # BGR -> RGB\n    image = image[:, :, ::-1]\n    h, w = image.shape[:2]\n\n    image, scale = preprocess_image(image, image_size=image_size)\n    # run network\n    start = time.time()\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    print(time.time() - start)\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    row = [image_name.replace('.jpg','')]\n    r_boxes = \"\"\n    for s,b in zip(scores, boxes):\n        if r_boxes != \"\":\n            r_boxes += \" \"\n        r_boxes += f\"{round(float(s),2)} {int(b[0])} {int(b[1])} {int(b[2]-b[0])} {int(b[3]-b[1])}\"\n    \n    row.append(r_boxes)\n    \n    print(row)\n    result_data.append(row)\ntest_df = pd.DataFrame(result_data, columns=['image_id','PredictionString'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.to_csv(\"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}