{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\n!pip install ../input/humanhacking/libs/segmentation_models-1.0.1-py3-none-any.whl --no-index --find-links=\"../input/humanhacking/libs/\"\n\nimport os\nimport cv2\nfrom tensorflow import keras\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport segmentation_models as sm","metadata":{"execution":{"iopub.status.busy":"2022-07-13T08:38:31.198486Z","iopub.execute_input":"2022-07-13T08:38:31.199107Z","iopub.status.idle":"2022-07-13T08:38:49.675754Z","shell.execute_reply.started":"2022-07-13T08:38:31.198979Z","shell.execute_reply":"2022-07-13T08:38:49.670637Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optim = keras.optimizers.Adam(0.0001)\n\n# Segmentation models losses can be combined together by '+' and scaled by integer or float factor\ndice_loss = sm.losses.DiceLoss()\nfocal_loss = sm.losses.BinaryFocalLoss()\ntotal_loss = dice_loss + (1 * focal_loss)\nmetrics = [sm.metrics.IOUScore(threshold=0.5), sm.metrics.FScore(threshold=0.5)]\n\nco = {\"dice_loss_plus_1binary_focal_loss\": dice_loss, \"iou_score\": metrics[0], \"f1-score\": metrics[1]}\n\nmodel = keras.models.load_model('../input/humanhacking/unet_resnext101_SGD_lr001_1024_model_aug_envweiNone50', custom_objects=co)\n\npreprocess_input = sm.get_preprocessing('resnext101')","metadata":{"execution":{"iopub.status.busy":"2022-07-13T08:38:49.677477Z","iopub.execute_input":"2022-07-13T08:38:49.678201Z","iopub.status.idle":"2022-07-13T08:39:18.909429Z","shell.execute_reply.started":"2022-07-13T08:38:49.678155Z","shell.execute_reply":"2022-07-13T08:39:18.908338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\n\nrle_list = []\nid_list = []\nimport matplotlib.pyplot as plt\n\ndef rle_encode(img):\n    img = img.T\n    pixels = img.flatten()\n    pixels = np.concatenate([[0], pixels, [0]])\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)\n\n\nfor i in os.listdir(\"../input/hubmap-organ-segmentation/test_images/\"):\n    image = cv2.imread(f\"../input/hubmap-organ-segmentation/test_images/{i}\")\n    h, w, c = image.shape\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n    image = cv2.resize(image, (1024, 1024))\n    image = preprocess_input(np.asarray([image]))\n    \n    mask_predict = model.predict(image)\n    mask = ((mask_predict[..., 0].squeeze() > 0.7) * 255).astype(np.uint8)\n\n    plt.imshow(mask);\n    plt.show()\n    contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n    new_mask = np.zeros((1024, 1024), np.uint8)\n    for j in contours:\n        area = cv2.contourArea(j)\n        if area < 400:\n            continue\n\n        cv2.drawContours(new_mask, np.asarray([j]), -1, (1), -1)\n    \n    kernel = np.ones((7, 7),np.uint8)\n    new_mask = cv2.dilate(new_mask, kernel, iterations=1)\n\n    plt.imshow(new_mask);\n    plt.show()\n    \n    mask = cv2.resize(new_mask, (h, w))\n    \n    rle = rle_encode(mask)\n    rle_list.append(rle)\n    id_list.append(i.split(\".\")[0])\n    \n    print(\"*-\" * 50)\n\ndf = pd.DataFrame()\ndf['id'] = id_list\ndf['rle'] = rle_list\nprint(df)\ndf.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2022-07-13T08:42:09.968745Z","iopub.execute_input":"2022-07-13T08:42:09.969302Z","iopub.status.idle":"2022-07-13T08:42:10.894389Z","shell.execute_reply.started":"2022-07-13T08:42:09.969260Z","shell.execute_reply":"2022-07-13T08:42:10.893113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}