{"cells":[{"metadata":{},"cell_type":"markdown","source":"Modification of this greate kernel: https://www.kaggle.com/pednt9/gwd-keras-unet-starter"},{"metadata":{},"cell_type":"markdown","source":"Inference part: https://www.kaggle.com/armin25/gwd-starter-gpu-v2-infer"},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -qq segmentation-models","execution_count":null,"outputs":[]},{"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\nfrom matplotlib import pyplot as plt\nfrom skimage.io import imread\nfrom skimage.transform import resize\nfrom PIL import Image, ImageDraw\nfrom tqdm.notebook import tqdm\nimport segmentation_models as sm","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"EPOCHS = 10\n\nIMG_WIDTH = 256\nIMG_HEIGHT = 256\nIMG_CHANNELS = 3\nTRAIN_PATH = '/kaggle/input/global-wheat-detection/train/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"PATH = \"../input/global-wheat-detection/\"\ntrain_folder = os.path.join(PATH, \"train\")\ntrain_csv_path = os.path.join(PATH, \"train.csv\")\ndf = pd.read_csv(train_csv_path)\n\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_ids = os.listdir(TRAIN_PATH)\nlen(train_ids)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def make_polygon(coords):\n    xm, ym, w, h = coords\n    xm, ym, w, h = xm / 4, ym / 4, w / 4, h / 4\n    polygon = [(xm, ym), (xm, ym + h), (xm + w, ym + h), (xm + w, ym)]\n    return polygon\n\nmasks = dict() # dictionnary containing all masks\n\nfor img_id, gp in tqdm(df.groupby(\"image_id\")):\n    gp['polygons'] = gp['bbox'].apply(eval).apply(lambda x: make_polygon(x))\n\n    img = Image.new('L', (IMG_WIDTH, IMG_HEIGHT), 0)\n    for pol in gp['polygons'].values:\n        ImageDraw.Draw(img).polygon(pol, outline=1, fill=1)\n\n    mask = np.array(img, dtype=np.uint8)\n    masks[img_id] = mask","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Get and resize train images and masks\nX_train = np.zeros((len(train_ids), IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), dtype=np.uint8)\nY_train = np.zeros((len(train_ids), IMG_HEIGHT, IMG_WIDTH, 1), dtype=np.bool)\nprint('Getting and resizing train images and masks ... ')\nsys.stdout.flush()\n\nfor n, id_ in tqdm(enumerate(train_ids[:]), total=len(train_ids)):\n    path = TRAIN_PATH + id_\n    img = imread(path)[:,:,:IMG_CHANNELS]\n    img = resize(img, (IMG_HEIGHT, IMG_WIDTH), mode='constant', preserve_range=True)\n    X_train[n] = img\n    mask = np.zeros((IMG_HEIGHT, IMG_WIDTH, 1), dtype=np.bool)\n    \n    id_clean = id_.split('.')[0]\n    if id_clean in masks.keys():\n        Y_train[n] = masks[id_clean][:, :, np.newaxis]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train.shape, Y_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"a=2\nplt.imshow(X_train[a])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(Y_train[a,:,:,0].astype(int))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = sm.Unet('efficientnetb3', encoder_weights='imagenet')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(\n    'Adam',\n    loss=sm.losses.bce_jaccard_loss,\n    metrics=[sm.metrics.iou_score],\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(\n   x=X_train,\n   y=Y_train,\n   batch_size=16,\n   epochs=EPOCHS\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('model.h5')","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}