{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Turning Image Tiles into Pandas DataFrame + Tiling the Images Together\n\nCredit to the tile image dataset creator: lafoss [link](https://www.kaggle.com/iafoss/panda-16x128x128-tiles-data)\n\n![img](https://i.ibb.co/hF6LRVm/TILE.png)\n\nBefore that, why would anyone need this?\nI am creating this for those who will be using **Keras FlowFromDataFrame method** ([documentation](https://keras.io/api/preprocessing/image/#flowfromdataframe-method))\n\nAnd also for those who want to combine these tiles into **1 single image**.\n\n\nLets get it done! ","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"First lets import all the things we need.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport cv2\nimport skimage.io\nfrom tqdm.notebook import tqdm\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport glob\nimport pandas as pd","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Loading the data csv\n\nWe use pandas read csv method.","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"df_train = pd.read_csv(\"../input/prostate-cancer-grade-assessment/train.csv\")\ndf_train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Getting image files list\n\nFor this, I used Glob.\nThe images are formatted in the following manner:\n\n* 0005f7aaab2800f6170c399693a96917_0.png\n* 0005f7aaab2800f6170c399693a96917_1.png\n* 0005f7aaab2800f6170c399693a96917_2.png\n* 0005f7aaab2800f6170c399693a96917_3.png\n\n... and so on.\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"img_path = \"../input/panda-16x128x128-tiles-data/train\"\nimg_id = list(df_train[\"image_id\"])\nimg_files = glob.glob(img_path + f\"/{img_id[1]}\" + \"*\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Get data function\n\nThis is just to get the datas","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_df():\n    data = {\"image_id\": [], \"isup_grade\": []}\n    img_path = \"../input/panda-16x128x128-tiles-data/train\"\n    img_ids = list(df_train[\"image_id\"])\n    labels = list(df_train[\"isup_grade\"])\n    for i in tqdm(range(len(img_ids))):\n        img_id = img_ids[i]\n        img_files = []\n        label = [labels[i]] * 16\n        for i in range(16):\n            img_files.append(f\"{img_id}\"+f\"_{i}\"+\".png\")\n        data[\"image_id\"].extend(img_files)\n        data[\"isup_grade\"].extend(label)\n        \n    return data","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Get our pandas dataframe!","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def to_pandas(data):\n    df = pd.DataFrame(data, columns = [\"image_id\", 'isup_grade'])\n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = get_df()\ndf_new = to_pandas(data)\n\ndf_new.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Formatting our dataframe.\n\nFlowFromDataFrame method can be used in 2 ways, either specifying the directory of the image or making sure each data in the dataframe has absolute paths to the images.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"example = df_new[\"image_id\"].iloc[:16]\nexample = list(example.map(lambda x: os.path.join(\"../input/panda-16x128x128-tiles-data/train\", x)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Example without combining the images together","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\nw = 10\nh = 10\nfig = plt.figure(figsize=(9, 13))\ncolumns = 4\nrows = 4     \n\nax = []\n\nfor i in range(columns*rows):\n    img = cv2.imread(example[i], cv2.COLOR_BGR2RGB)\n    ax.append( fig.add_subplot(rows, columns, i+1) )\n    ax[-1].set_title(\"tile:\"+str(i)) \n    plt.imshow(img)\n\nplt.show()  ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Example on how to combine the image tiles into one single image.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_img_tiles(image_list):\n    img_rows = []\n    rc = 0\n    for i in range(rows):\n        img1 = cv2.imread(image_list[rc + 1], cv2.COLOR_BGR2RGB)\n        img2 = cv2.imread(image_list[rc + 2], cv2.COLOR_BGR2RGB)\n        img3 = cv2.imread(image_list[rc + 3], cv2.COLOR_BGR2RGB)\n        img4 = cv2.imread(image_list[rc + 4], cv2.COLOR_BGR2RGB)\n        img_row = np.concatenate((img1, img2, img3, img4), axis = 1)\n        if rc == 0:\n            rc += 3\n        elif rc == 3 or rc == 7:\n            rc += 4\n        else:\n            rc += 0\n        img_rows.append(img_row)\n    img_stacked = img_row = np.concatenate((img_rows[0], img_rows[1], img_rows[2], img_rows[3]), axis = 0)\n    return img_stacked","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"example_tile = get_img_tiles(example)\nplt.imshow(example_tile)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}