{"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":"markdown","source":"# STRIP AI - processing images to 16x256x256 tiles\n\n","metadata":{}},{"cell_type":"markdown","source":"- In this competition, handling images has extremely high resolution, so we must resize images.\n- But images has large area of empty, simple resize method should not be used.\n- In this notebook, to solve this problem, images are converted to 16x256x256 tiles in which boold clot is magnified.\n\n<img src=\"https://i.imgur.com/CLRRvJM.png\" width=\"50%\">","metadata":{}},{"cell_type":"markdown","source":"- Dataset of 16x256x256 tiles is [here](https://www.kaggle.com/datasets/yusaku5739/mayoclinicstripaiimg-16-256-256)","metadata":{}},{"cell_type":"markdown","source":"## Import library","metadata":{}},{"cell_type":"code","source":"import os\nimport cv2\nfrom tqdm.notebook import tqdm\nimport zipfile\nimport numpy as np\nimport pandas as pd\nimport glob\nfrom tifffile import TiffFile\nimport matplotlib.pyplot as plt\nimport random","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-07-12T12:15:16.892707Z","iopub.execute_input":"2022-07-12T12:15:16.893162Z","iopub.status.idle":"2022-07-12T12:15:17.450384Z","shell.execute_reply.started":"2022-07-12T12:15:16.89307Z","shell.execute_reply":"2022-07-12T12:15:17.449179Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Setting","metadata":{}},{"cell_type":"code","source":"TRAIN = '../input/mayo-clinic-strip-ai/train/'\nOUTPUT_FILE = \"mayo-clinic-strip-ai-img_16_256_256\"\nos.mkdir(\"/kaggle/working/\"+OUTPUT_FILE)\ndata = pd.read_csv(\"../input/mayo-clinic-strip-ai/train.csv\")\nimg_list = glob.glob(TRAIN + \"*.tif\")\nsz = 256\nN = 16","metadata":{"execution":{"iopub.status.busy":"2022-07-12T12:15:17.453096Z","iopub.execute_input":"2022-07-12T12:15:17.453931Z","iopub.status.idle":"2022-07-12T12:15:17.526123Z","shell.execute_reply.started":"2022-07-12T12:15:17.453881Z","shell.execute_reply":"2022-07-12T12:15:17.525097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Utility","metadata":{}},{"cell_type":"code","source":"def tile(img):\n    shape = img.shape\n    pad0,pad1 = (sz - shape[0]%sz)%sz, (sz - shape[1]%sz)%sz\n    img = np.pad(img,[[pad0//2,pad0-pad0//2],[pad1//2,pad1-pad1//2],[0,0]],\n                constant_values=255)\n    img = img.reshape(img.shape[0]//sz,sz,img.shape[1]//sz,sz,3)\n    img = img.transpose(0,2,1,3,4).reshape(-1,sz,sz,3)\n    \n    if len(img) < N:\n        mask = np.pad(mask,[[0,N-len(img)],[0,0],[0,0],[0,0]],constant_values=0)\n        img = np.pad(img,[[0,N-len(img)],[0,0],[0,0],[0,0]],constant_values=255)\n        print(img.shape)\n    idxs = np.argsort(img.reshape(img.shape[0],-1).sum(-1))[:N]\n    img = img[idxs]\n    return img\n\ndef read_img(image_file, dset, min_edge_size=4096, verbose=1):\n    with TiffFile(os.path.join(image_file)) as tif:\n        tif_tags = {}\n        for tag in tif.pages[0].tags.values():\n            name, value = tag.name, tag.value\n            tif_tags[name] = value\n        del tif_tags[\"TileOffsets\"] \n        del tif_tags[\"TileByteCounts\"]\n        image = tif.pages[0].asarray()\n    \n    image_id = image_file.split(\"/\")[-1]\n    if verbose:\n        print(f\"[{image_id}] Image shape: {image.shape}\")\n    \n    min_edge = min(image.shape[:2])\n    scale = min_edge//min_edge_size\n    \n    new_size = (image.shape[1] // scale, image.shape[0] // scale)\n    image = cv2.resize(image, new_size, interpolation=cv2.INTER_AREA)\n    if image.shape[1]>1.5*image.shape[0]:\n        out=cv2.transpose(image)\n        image=cv2.flip(out,flipCode=0)\n        \n    if verbose:\n        print(f\"[{image_id}] Resized Image shape: {image.shape}\")\n        \n    return image, tif_tags","metadata":{"execution":{"iopub.status.busy":"2022-07-12T12:15:17.529844Z","iopub.execute_input":"2022-07-12T12:15:17.530491Z","iopub.status.idle":"2022-07-12T12:15:17.550138Z","shell.execute_reply.started":"2022-07-12T12:15:17.530456Z","shell.execute_reply":"2022-07-12T12:15:17.548839Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Processing","metadata":{}},{"cell_type":"code","source":"for path in tqdm(img_list):\n    img_name = path.split(\"/\")[-1].split(\".\")[0]\n    img, tags = read_img(path, data, min_edge_size=4096, verbose=False)\n    imgs = tile(img)\n    np.save(\"/kaggle/working/\" + OUTPUT_FILE + \"/\" + img_name, imgs)","metadata":{"execution":{"iopub.status.busy":"2022-07-12T12:15:17.553203Z","iopub.execute_input":"2022-07-12T12:15:17.554101Z","iopub.status.idle":"2022-07-12T16:11:04.563648Z","shell.execute_reply.started":"2022-07-12T12:15:17.554043Z","shell.execute_reply":"2022-07-12T16:11:04.560597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Visualization","metadata":{}},{"cell_type":"code","source":"tiles = glob.glob(\"/kaggle/working/mayo-clinic-strip-ai-img_16_256_256/*.npy\")\nex_id = random.randint(0, len(tiles)-1)\nex_path = tiles[ex_id]\n\nprint(\"image before proseccing\")\npre_img, _ = read_img(TRAIN + ex_path.split(\"/\")[-1].split(\".\")[0] + \".tif\", data, min_edge_size=4096, verbose=False)\nplt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=0, hspace=0)\nshape = [pre_img.shape[0], pre_img.shape[1]]\nplt.figure(figsize=(int(shape[0]*0.001), int(shape[1]*0.001)))\nplt.imshow(pre_img)\nax = plt.gca()\nax.axes.xaxis.set_visible(False)\nax.axes.yaxis.set_visible(False)\nplt.savefig(\"pre_img.png\")\nplt.show()\n\nimg = np.load(ex_path)\nprint(\"\")\nprint(\"\")\nprint(\"images after proseccing\")\nprint(f\"image shape: {img.shape}\")\nprint(\"\")\n\nplt.figure(figsize=(7,7))\nplt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=0, hspace=0)\nfor i in range(len(img)):\n    plt.subplot(4, 4, i+1).imshow(img[i])\n    plt.axis('tight')\n    ax = plt.gca()\n    ax.axes.xaxis.set_visible(False)\n    ax.axes.yaxis.set_visible(False)\n    \nplt.savefig('tiles.png')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-12T16:44:58.910082Z","iopub.execute_input":"2022-07-12T16:44:58.910567Z","iopub.status.idle":"2022-07-12T16:45:23.121054Z","shell.execute_reply.started":"2022-07-12T16:44:58.910527Z","shell.execute_reply":"2022-07-12T16:45:23.119706Z"},"trusted":true},"execution_count":null,"outputs":[]}]}