{"cells":[{"metadata":{},"cell_type":"markdown","source":"* Inference part from this nice kernel: https://www.kaggle.com/pednt9/gwd-keras-unet-starter\n* Train part: https://www.kaggle.com/armin25/gwd-starter-gpu-v2-train"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\nimport sys\nimport numpy as np\nimport pandas as pd\nimport keras\nfrom matplotlib import pyplot as plt\nfrom skimage.io import imread, imshow \nfrom skimage.transform import resize\nfrom skimage.morphology import label\nfrom PIL import Image, ImageDraw\nfrom tqdm.notebook import tqdm\nfrom skimage.measure import label, regionprops\n\nsys.path.insert(0, '/kaggle/input/efficientnet-keras-source-code/')\nimport efficientnet.keras","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = keras.models.load_model('/kaggle/input/gwd-starter-gpu-v2-train/model.h5', compile=False)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"IMG_WIDTH = 256\nIMG_HEIGHT = 256\nIMG_CHANNELS = 3\nPATH = \"../input/global-wheat-detection/\"\nTEST_PATH = '/kaggle/input/global-wheat-detection/test/'\ntest_folder = os.path.join(PATH, \"test\")\nsample_sub = pd.read_csv(PATH + \"sample_submission.csv\")\ntest_ids = os.listdir(TEST_PATH)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Get and resize test images\nX_test = np.zeros((len(test_ids), IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), dtype=np.uint8)\nsizes_test = []\nprint('Getting and resizing test images ... ')\nsys.stdout.flush()\nfor n, id_ in tqdm(enumerate(test_ids), total=len(test_ids)):\n    path = TEST_PATH + id_\n    img = imread(path)[:,:,:IMG_CHANNELS]\n    sizes_test.append([img.shape[0], img.shape[1]])\n    img = resize(img, (IMG_HEIGHT, IMG_WIDTH), mode='constant', preserve_range=True)\n    X_test[n] = img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\nTHRESH = 0.75\n\npreds = model.predict(X_test)[:, :, :, 0]\nmasked_preds = preds > THRESH","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n_rows = 3\n\nf, ax = plt.subplots(n_rows, 3, figsize=(14, 10))\n\nfor j, idx in enumerate([4,5,6]):\n    for k, kind in enumerate(['original', 'pred', 'masked_pred']):\n        if kind == 'original':\n            img = X_test[idx]\n        elif kind == 'pred':\n            img = preds[idx]\n        elif kind == 'masked_pred':\n            masked_pred = preds[idx] > .75\n            img = masked_pred\n        ax[j, k].imshow(img)\n\nplt.tight_layout()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_params_from_bbox(coords, scaling_factor=1):\n    xmin, ymin = coords[1] * scaling_factor, coords[0] * scaling_factor\n    w = (coords[3] - coords[1]) * scaling_factor\n    h = (coords[2] - coords[0]) * scaling_factor\n    \n    return xmin, ymin, w, h","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Allows to extract bounding boxes from binary masks\nbboxes = list()\n\nfor j in range(masked_preds.shape[0]):\n    label_j = label(masked_preds[j, :, :]) \n    props = regionprops(label_j)\n    bboxes.append(props)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"output = dict()\nfor i in range(masked_preds.shape[0]):\n    bboxes_processed = [get_params_from_bbox(bb.bbox, scaling_factor=4) for bb in bboxes[i]]\n    formated_boxes = ['1.0 ' + ' '.join(map(str, bb_m)) for bb_m in bboxes_processed]\n    \n    output[sample_sub[\"image_id\"][i]] = \" \".join(formated_boxes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_sub[\"PredictionString\"] = output.values()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_sub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_sub.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}