{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Faseter HPA Cell Segmentation\n\nThe execution time of HPA Cell Segmentation seems to use a lot of time for post-processing.\nTherefore, I applied post-processing to the resized image (512x512) to achieve the speed-up.\n\n\nBy default, the NN model of HPA Cell Segmentation processes 0.25x resized images. Therefore, it is inefficient to perform post-processing on the restored image (2048x2048).\nIn order to properly post-process the resized image, I have adjusted some parameters in the post-processing code to 0.25x. For parameters related to area, I adjusted them by a factor of 1/16.\n\n## About This Code\n\nThe following code writes the code to a Python file and starts it in a separate process to simplify memory management.\n\n\nThe input to be processed is `./sample_submission.csv`. (to experiment with a small amount of data during debugging.)\n\n\nThe output of each mask by HPA Cell Segmentation is\n- `/temp/test_mask/{ID}_cell.npy`\n- `/temp/test_mask/{ID}_nuc.npy`\n\nrespectively.\n\nThe output of each mask by naive HPA Cell Segmentation (for comparison) is\n- `/temp/test_mask_original/{ID}_cell.npy`\n- `/temp/test_mask_original/{ID}_nuc.npy`\n\nrespectively.\n"},{"metadata":{},"cell_type":"markdown","source":"## Setup"},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install ../input/hpacellsegmentatormaster/HPA-Cell-Segmentation-master/\n!pip install ../input/hpapytorchzoozip/pytorch_zoo-master/\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\ntest_df = pd.read_csv('../input/hpa-single-cell-image-classification/sample_submission.csv')\nif len(test_df) == 559:\n    test_df = test_df.sample(n=50, replace=True)\n    test_df.to_csv('./sample_submission.csv', index=False)\nelse:\n    test_df.to_csv('./sample_submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Faster HPA Cell Segmentation"},{"metadata":{},"cell_type":"markdown","source":"### Code"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%writefile faster_hpa_cell_segment.py\n\nimport numpy as np\nimport pandas as pd\nimport os\nfrom tqdm import tqdm\n\nfrom hpacellseg.cellsegmentator import *\n\n\nclass CellSegmentator(object):\n    \"\"\"Uses pretrained DPN-Unet models to segment cells from images.\"\"\"\n\n    def __init__(\n        self,\n        nuclei_model=\"../input/hpacellsegmentatormodelweights/dpn_unet_nuclei_v1.pth\",\n        cell_model=\"../input/hpacellsegmentatormodelweights/dpn_unet_cell_3ch_v1.pth\",\n        scale_factor=1.0,\n        device=\"cuda\",\n        padding=False,\n        multi_channel_model=True,\n    ):\n        \"\"\"Class for segmenting nuclei and whole cells from confocal microscopy images.\n        It takes lists of images and returns the raw output from the\n        specified segmentation model. Models can be automatically\n        downloaded if they are not already available on the system.\n        When working with images from the Huan Protein Cell atlas, the\n        outputs from this class' methods are well combined with the\n        label functions in the utils module.\n        Note that for cell segmentation, there are two possible models\n        available. One that works with 2 channeled images and one that\n        takes 3 channels.\n        Keyword arguments:\n        nuclei_model -- A loaded torch nuclei segmentation model or the\n                        path to a file which contains such a model.\n                        If the argument is a path that points to a non-existant file,\n                        a pretrained nuclei_model is going to get downloaded to the\n                        specified path (default: './nuclei_model.pth').\n        cell_model -- A loaded torch cell segmentation model or the\n                      path to a file which contains such a model.\n                      The cell_model argument can be None if only nuclei\n                      are to be segmented (default: './cell_model.pth').\n        scale_factor -- How much to scale images before they are fed to\n                        segmentation models. Segmentations will be scaled back\n                        up by 1/scale_factor to match the original image\n                        (default: 0.25).\n        device -- The device on which to run the models.\n                  This should either be 'cpu' or 'cuda' or pointed cuda\n                  device like 'cuda:0' (default: 'cuda').\n        padding -- Whether to add padding to the images before feeding the\n                   images to the network. (default: False).\n        multi_channel_model -- Control whether to use the 3-channel cell model or not.\n                               If True, use the 3-channel model, otherwise use the\n                               2-channel version (default: True).\n        \"\"\"\n        if device != \"cuda\" and device != \"cpu\" and \"cuda\" not in device:\n            raise ValueError(f\"{device} is not a valid device (cuda/cpu)\")\n        if device != \"cpu\":\n            try:\n                assert torch.cuda.is_available()\n            except AssertionError:\n                print(\"No GPU found, using CPU.\", file=sys.stderr)\n                device = \"cpu\"\n        self.device = device\n\n        if isinstance(nuclei_model, str):\n            if not os.path.exists(nuclei_model):\n                print(\n                    f\"Could not find {nuclei_model}. Downloading it now\",\n                    file=sys.stderr,\n                )\n                download_with_url(NUCLEI_MODEL_URL, nuclei_model)\n            nuclei_model = torch.load(\n                nuclei_model, map_location=torch.device(self.device)\n            )\n        if isinstance(nuclei_model, torch.nn.DataParallel) and device == \"cpu\":\n            nuclei_model = nuclei_model.module\n\n        self.nuclei_model = nuclei_model.to(self.device).eval()\n\n        self.multi_channel_model = multi_channel_model\n        if isinstance(cell_model, str):\n            if not os.path.exists(cell_model):\n                print(\n                    f\"Could not find {cell_model}. Downloading it now\", file=sys.stderr\n                )\n                if self.multi_channel_model:\n                    download_with_url(MULTI_CHANNEL_CELL_MODEL_URL, cell_model)\n                else:\n                    download_with_url(TWO_CHANNEL_CELL_MODEL_URL, cell_model)\n            cell_model = torch.load(cell_model, map_location=torch.device(self.device))\n        self.cell_model = cell_model.to(self.device).eval()\n        self.scale_factor = scale_factor\n        self.padding = padding\n\n    def _image_conversion(self, images):\n        \"\"\"Convert/Format images to RGB image arrays list for cell predictions.\n        Intended for internal use only.\n        Keyword arguments:\n        images -- list of lists of image paths/arrays. It should following the\n                 pattern if with er channel input,\n                 [\n                     [microtubule_path0/image_array0, microtubule_path1/image_array1, ...],\n                     [er_path0/image_array0, er_path1/image_array1, ...],\n                     [nuclei_path0/image_array0, nuclei_path1/image_array1, ...]\n                 ]\n                 or if without er input,\n                 [\n                     [microtubule_path0/image_array0, microtubule_path1/image_array1, ...],\n                     None,\n                     [nuclei_path0/image_array0, nuclei_path1/image_array1, ...]\n                 ]\n        \"\"\"\n        microtubule_imgs, er_imgs, nuclei_imgs = images\n        if self.multi_channel_model:\n            if not isinstance(er_imgs, list):\n                raise ValueError(\"Please speicify the image path(s) for er channels!\")\n        else:\n            if not er_imgs is None:\n                raise ValueError(\n                    \"second channel should be None for two channel model predition!\"\n                )\n\n        if not isinstance(microtubule_imgs, list):\n            raise ValueError(\"The microtubule images should be a list\")\n        if not isinstance(nuclei_imgs, list):\n            raise ValueError(\"The microtubule images should be a list\")\n\n        if er_imgs:\n            if not len(microtubule_imgs) == len(er_imgs) == len(nuclei_imgs):\n                raise ValueError(\"The lists of images needs to be the same length\")\n        else:\n            if not len(microtubule_imgs) == len(nuclei_imgs):\n                raise ValueError(\"The lists of images needs to be the same length\")\n\n        if not all(isinstance(item, np.ndarray) for item in microtubule_imgs):\n            microtubule_imgs = [\n                os.path.expanduser(item) for _, item in enumerate(microtubule_imgs)\n            ]\n            nuclei_imgs = [\n                os.path.expanduser(item) for _, item in enumerate(nuclei_imgs)\n            ]\n\n            microtubule_imgs = list(\n                map(lambda item: imageio.imread(item), microtubule_imgs)\n            )\n            nuclei_imgs = list(map(lambda item: imageio.imread(item), nuclei_imgs))\n            if er_imgs:\n                er_imgs = [os.path.expanduser(item) for _, item in enumerate(er_imgs)]\n                er_imgs = list(map(lambda item: imageio.imread(item), er_imgs))\n\n        if not er_imgs:\n            er_imgs = [\n                np.zeros(item.shape, dtype=item.dtype)\n                for _, item in enumerate(microtubule_imgs)\n            ]\n        cell_imgs = list(\n            map(\n                lambda item: np.dstack((item[0], item[1], item[2])),\n                list(zip(microtubule_imgs, er_imgs, nuclei_imgs)),\n            )\n        )\n\n        return cell_imgs\n\n    def pred_nuclei(self, images):\n        \"\"\"Predict the nuclei segmentation.\n        Keyword arguments:\n        images -- A list of image arrays or a list of paths to images.\n                  If as a list of image arrays, the images could be 2d images\n                  of nuclei data array only, or must have the nuclei data in\n                  the blue channel; If as a list of file paths, the images\n                  could be RGB image files or gray scale nuclei image file\n                  paths.\n        Returns:\n        predictions -- A list of predictions of nuclei segmentation for each nuclei image.\n        \"\"\"\n\n        def _preprocess(image):\n            if isinstance(image, str):\n                image = imageio.imread(image)\n            self.target_shape = image.shape\n            if len(image.shape) == 2:\n                image = np.dstack((image, image, image))\n            image = transform.rescale(image, self.scale_factor, multichannel=True)\n            nuc_image = np.dstack((image[..., 2], image[..., 2], image[..., 2]))\n            if self.padding:\n                rows, cols = nuc_image.shape[:2]\n                self.scaled_shape = rows, cols\n                nuc_image = cv2.copyMakeBorder(\n                    nuc_image,\n                    32,\n                    (32 - rows % 32),\n                    32,\n                    (32 - cols % 32),\n                    cv2.BORDER_REFLECT,\n                )\n            nuc_image = nuc_image.transpose([2, 0, 1])\n            return nuc_image\n\n        def _segment_helper(imgs):\n            with torch.no_grad():\n                mean = torch.as_tensor(NORMALIZE[\"mean\"], device=self.device)\n                std = torch.as_tensor(NORMALIZE[\"std\"], device=self.device)\n                imgs = torch.tensor(imgs).float()\n                imgs = imgs.to(self.device)\n                imgs = imgs.sub_(mean[:, None, None]).div_(std[:, None, None])\n\n                imgs = self.nuclei_model(imgs)\n                imgs = F.softmax(imgs, dim=1)\n                return imgs\n\n        preprocessed_imgs = list(map(_preprocess, images))\n        bs = 24\n        predictions = []\n        for i in range(0, len(preprocessed_imgs), bs):\n            start = i\n            end = min(len(preprocessed_imgs), i+bs)\n            x = preprocessed_imgs[start:end]\n            pred = _segment_helper(x).cpu().numpy()\n            predictions.append(pred)\n        predictions = list(np.concatenate(predictions, axis=0))\n        predictions = map(util.img_as_ubyte, predictions)\n        predictions = list(map(self._restore_scaling_padding, predictions))\n        return predictions\n\n    def _restore_scaling_padding(self, n_prediction):\n        \"\"\"Restore an image from scaling and padding.\n        This method is intended for internal use.\n        It takes the output from the nuclei model as input.\n        \"\"\"\n        n_prediction = n_prediction.transpose([1, 2, 0])\n        if self.padding:\n            n_prediction = n_prediction[\n                32 : 32 + self.scaled_shape[0], 32 : 32 + self.scaled_shape[1], ...\n            ]\n        if not self.scale_factor == 1:\n            n_prediction[..., 0] = 0\n            n_prediction = cv2.resize(\n                n_prediction,\n                (self.target_shape[0], self.target_shape[1]),\n                interpolation=cv2.INTER_AREA,\n            )\n        return n_prediction\n\n    def pred_cells(self, images, precombined=False):\n        \"\"\"Predict the cell segmentation for a list of images.\n        Keyword arguments:\n        images -- list of lists of image paths/arrays. It should following the\n                  pattern if with er channel input,\n                  [\n                      [microtubule_path0/image_array0, microtubule_path1/image_array1, ...],\n                      [er_path0/image_array0, er_path1/image_array1, ...],\n                      [nuclei_path0/image_array0, nuclei_path1/image_array1, ...]\n                  ]\n                  or if without er input,\n                  [\n                      [microtubule_path0/image_array0, microtubule_path1/image_array1, ...],\n                      None,\n                      [nuclei_path0/image_array0, nuclei_path1/image_array1, ...]\n                  ]\n                  The ER channel is required when multichannel is True\n                  and required to be None when multichannel is False.\n                  The images needs to be of the same size.\n        precombined -- If precombined is True, the list of images is instead supposed to be\n                       a list of RGB numpy arrays (default: False).\n        Returns:\n        predictions -- a list of predictions of cell segmentations.\n        \"\"\"\n\n        def _preprocess(image):\n            self.target_shape = image.shape\n            if not len(image.shape) == 3:\n                raise ValueError(\"image should has 3 channels\")\n            cell_image = transform.rescale(image, self.scale_factor, multichannel=True)\n            if self.padding:\n                rows, cols = cell_image.shape[:2]\n                self.scaled_shape = rows, cols\n                cell_image = cv2.copyMakeBorder(\n                    cell_image,\n                    32,\n                    (32 - rows % 32),\n                    32,\n                    (32 - cols % 32),\n                    cv2.BORDER_REFLECT,\n                )\n            cell_image = cell_image.transpose([2, 0, 1])\n            return cell_image\n\n        def _segment_helper(imgs):\n            with torch.no_grad():\n                mean = torch.as_tensor(NORMALIZE[\"mean\"], device=self.device)\n                std = torch.as_tensor(NORMALIZE[\"std\"], device=self.device)\n                imgs = torch.tensor(imgs).float()\n                imgs = imgs.to(self.device)\n                imgs = imgs.sub_(mean[:, None, None]).div_(std[:, None, None])\n\n                imgs = self.cell_model(imgs)\n                imgs = F.softmax(imgs, dim=1)\n                return imgs\n\n        if not precombined:\n            images = self._image_conversion(images)\n        preprocessed_imgs = list(map(_preprocess, images))\n        bs = 24\n        predictions = []\n        for i in range(0, len(preprocessed_imgs), bs):\n            start = i\n            end = min(len(preprocessed_imgs), i+bs)\n            x = preprocessed_imgs[start:end]\n            pred = _segment_helper(x).cpu().numpy()\n            predictions.append(pred)\n        predictions = list(np.concatenate(predictions, axis=0))\n        predictions = map(self._restore_scaling_padding, predictions)\n        predictions = list(map(util.img_as_ubyte, predictions))\n\n        return predictions\n    \n    \nimport os.path\nimport urllib\nimport zipfile\n\nimport numpy as np\nimport scipy.ndimage as ndi\nfrom skimage import filters, measure, segmentation\nfrom skimage.morphology import (binary_erosion, closing, disk,\n                                remove_small_holes, remove_small_objects)\n\nHIGH_THRESHOLD = 0.4\nLOW_THRESHOLD = HIGH_THRESHOLD - 0.25\n\n\ndef download_with_url(url_string, file_path, unzip=False):\n    \"\"\"Download file with a link.\"\"\"\n    with urllib.request.urlopen(url_string) as response, open(\n        file_path, \"wb\"\n    ) as out_file:\n        data = response.read()  # a `bytes` object\n        out_file.write(data)\n\n    if unzip:\n        with zipfile.ZipFile(file_path, \"r\") as zip_ref:\n            zip_ref.extractall(os.path.dirname(file_path))\n\n\ndef __fill_holes(image):\n    \"\"\"Fill_holes for labelled image, with a unique number.\"\"\"\n    boundaries = segmentation.find_boundaries(image)\n    image = np.multiply(image, np.invert(boundaries))\n    image = ndi.binary_fill_holes(image > 0)\n    image = ndi.label(image)[0]\n    return image\n\n\n\n\n\ndef label_cell(nuclei_pred, cell_pred):\n    \"\"\"Label the cells and the nuclei.\n    Keyword arguments:\n    nuclei_pred -- a 3D numpy array of a prediction from a nuclei image.\n    cell_pred -- a 3D numpy array of a prediction from a cell image.\n    Returns:\n    A tuple containing:\n    nuclei-label -- A nuclei mask data array.\n    cell-label  -- A cell mask data array.\n    0's in the data arrays indicate background while a continous\n    strech of a specific number indicates the area for a specific\n    cell.\n    The same value in cell mask and nuclei mask refers to the identical cell.\n    NOTE: The nuclei labeling from this function will be sligthly\n    different from the values in :func:`label_nuclei` as this version\n    will use information from the cell-predictions to make better\n    estimates.\n    \"\"\"\n    def __wsh(\n        mask_img,\n        threshold,\n        border_img,\n        seeds,\n        threshold_adjustment=0.35,\n        small_object_size_cutoff=10,\n    ):\n        img_copy = np.copy(mask_img)\n        m = seeds * border_img  # * dt\n        img_copy[m <= threshold + threshold_adjustment] = 0\n        img_copy[m > threshold + threshold_adjustment] = 1\n        img_copy = img_copy.astype(np.bool)\n        img_copy = remove_small_objects(img_copy, small_object_size_cutoff).astype(\n            np.uint8\n        )\n\n        mask_img[mask_img <= threshold] = 0\n        mask_img[mask_img > threshold] = 1\n        mask_img = mask_img.astype(np.bool)\n        mask_img = remove_small_holes(mask_img, 63)\n        mask_img = remove_small_objects(mask_img, 1).astype(np.uint8)\n        markers = ndi.label(img_copy, output=np.uint32)[0]\n        labeled_array = segmentation.watershed(\n            mask_img, markers, mask=mask_img, watershed_line=True\n        )\n        return labeled_array\n\n    nuclei_label = __wsh(\n        nuclei_pred[..., 2] / 255.0,\n        0.4,\n        1 - (nuclei_pred[..., 1] + cell_pred[..., 1]) / 255.0 > 0.05,\n        nuclei_pred[..., 2] / 255,\n        threshold_adjustment=-0.25,\n        small_object_size_cutoff=32,\n    )\n\n    # for hpa_image, to remove the small pseduo nuclei\n    nuclei_label = remove_small_objects(nuclei_label, 157)\n    nuclei_label = measure.label(nuclei_label)\n    # this is to remove the cell borders' signal from cell mask.\n    # could use np.logical_and with some revision, to replace this func.\n    # Tuned for segmentation hpa images\n    threshold_value = max(0.22, filters.threshold_otsu(cell_pred[..., 2] / 255) * 0.5)\n    # exclude the green area first\n    cell_region = np.multiply(\n        cell_pred[..., 2] / 255 > threshold_value,\n        np.invert(np.asarray(cell_pred[..., 1] / 255 > 0.05, dtype=np.int8)),\n    )\n    sk = np.asarray(cell_region, dtype=np.int8)\n    distance = np.clip(cell_pred[..., 2], 255 * threshold_value, cell_pred[..., 2])\n    cell_label = segmentation.watershed(-distance, nuclei_label, mask=sk)\n    cell_label = remove_small_objects(cell_label, 344).astype(np.uint8)\n    selem = disk(2)\n    cell_label = closing(cell_label, selem)\n    cell_label = __fill_holes(cell_label)\n    # this part is to use green channel, and extend cell label to green channel\n    # benefit is to exclude cells clear on border but without nucleus\n    sk = np.asarray(\n        np.add(\n            np.asarray(cell_label > 0, dtype=np.int8),\n            np.asarray(cell_pred[..., 1] / 255 > 0.05, dtype=np.int8),\n        )\n        > 0,\n        dtype=np.int8,\n    )\n    cell_label = segmentation.watershed(-distance, cell_label, mask=sk)\n    cell_label = __fill_holes(cell_label)\n    cell_label = np.asarray(cell_label > 0, dtype=np.uint8)\n    cell_label = measure.label(cell_label)\n    cell_label = remove_small_objects(cell_label, 344)\n    cell_label = measure.label(cell_label)\n    cell_label = np.asarray(cell_label, dtype=np.uint16)\n    nuclei_label = np.multiply(cell_label > 0, nuclei_label) > 0\n    nuclei_label = measure.label(nuclei_label)\n    nuclei_label = remove_small_objects(nuclei_label, 157)\n    nuclei_label = np.multiply(cell_label, nuclei_label > 0)\n\n    return nuclei_label, cell_label\n\n\ncellsegmentor = CellSegmentator()\n\ndata_df = pd.read_csv('./sample_submission.csv')\ndata_size = len(data_df)\nbs = 240\n\ndef load_images(df : pd.DataFrame, root='../input/hpa-single-cell-image-classification/test/'):\n    gray = []\n    rgb = []\n    for i, row in tqdm(df.iterrows(), total=len(df)):\n        r = os.path.join(root, f'{row.ID}_red.png')\n        y = os.path.join(root, f'{row.ID}_yellow.png')\n        b = os.path.join(root, f'{row.ID}_blue.png')\n        r = cv2.imread(r, 0)\n        y = cv2.imread(y, 0)\n        b = cv2.imread(b, 0)\n        gray_image = cv2.resize(b, (512, 512))\n        rgb_image = cv2.resize(np.stack((r, y, b), axis=2), (512, 512))\n        gray.append(gray_image)\n        rgb.append(rgb_image)\n    return gray, rgb\n        \n    \nfor i in range(0, data_size, bs):\n    print('!!!!', i, '!!!!')\n    start = i\n    end = min(len(data_df), start + bs)\n    test_df = data_df[start:end]\n    print(len(test_df))\n    print('---- start load images ----')\n    gray, rgb = load_images(test_df)\n    print(len(gray))\n    print('---- finish load images ----')\n    print('---- start pred nuclei ----')\n    nuc_segmentations = cellsegmentor.pred_nuclei(gray)\n    print('---- finish pred nucrei ----')\n    print('---- start pred cells ----')\n    cell_segmentations = cellsegmentor.pred_cells(rgb, precombined=True)\n    print('---- finish pred cells ----')\n\n\n    root = '/temp/test_mask/'\n\n    os.makedirs(root, exist_ok=True)\n\n    print('---- start mask write ----')\n    for data_id, nuc_seg, cell_seg in zip(test_df.ID.to_list(), nuc_segmentations, cell_segmentations):\n        nuc, cell = label_cell(nuc_seg, cell_seg)\n        np.save(os.path.join(root, f'{data_id}_nuc.npy'), nuc)\n        np.save(os.path.join(root, f'{data_id}_cell.npy'), cell)\n    print('---- finish mask write ----')\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Run and Execution Time"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n!python faster_hpa_cell_segment.py","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Original"},{"metadata":{},"cell_type":"markdown","source":"### Code"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%writefile hpa_cell_segment.py\n\nimport hpacellseg.cellsegmentator as cellsegmentator\nfrom hpacellseg.utils import label_cell, label_nuclei\nfrom tqdm import tqdm\nimport os\nimport numpy as np\nimport pandas as pd\n\nNUC_MODEL = \"../input/hpacellsegmentatormodelweights/dpn_unet_nuclei_v1.pth\"\nCELL_MODEL = \"../input/hpacellsegmentatormodelweights/dpn_unet_cell_3ch_v1.pth\"\nsegmentator = cellsegmentator.CellSegmentator(\n    NUC_MODEL,\n    CELL_MODEL,\n    scale_factor=0.25,\n    device=\"cuda\",\n    padding=True,\n    multi_channel_model=True,\n)\n\n\ndef get_segment_mask(data_id, root='../input/hpa-single-cell-image-classification/test/'):\n    r = [os.path.join(root, f'{data_id}_red.png')]\n    y = [os.path.join(root, f'{data_id}_yellow.png')]\n    b = [os.path.join(root, f'{data_id}_blue.png')]\n    data = [r, y, b]\n    nuc_segmentations = segmentator.pred_nuclei(data[2])\n    cell_segmentations = segmentator.pred_cells(data)\n    nuclei_mask, cell_mask = label_cell(nuc_segmentations[0], cell_segmentations[0])\n    return nuclei_mask, cell_mask\n\nroot = '/temp/test_mask_original/'\nos.makedirs(root, exist_ok=True)\n\ndata_df = pd.read_csv('./sample_submission.csv')\nfor data_id in tqdm(data_df.ID.to_list()):\n    nuc, cell = get_segment_mask(data_id)\n    np.save(os.path.join(root, f'{data_id}_nuc.npy'), nuc)\n    np.save(os.path.join(root, f'{data_id}_cell.npy'), cell)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Run and Execution Time"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n!python hpa_cell_segment.py","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Comparing Images"},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport cv2\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Faster HPA Cell Segmentation (Overlay)"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.read_csv('./sample_submission.csv')\nfig, ax = plt.subplots(1,3, figsize=(20,50))\n\nfor i, data_id in enumerate(test_df.ID.to_list()[:3]):\n    cell_mask = np.load(f'/temp/test_mask/{data_id}_cell.npy')\n    nuc_mask = np.load(f'/temp/test_mask/{data_id}_nuc.npy')\n    cell_image = np.stack([\n        cv2.imread(f'../input/hpa-single-cell-image-classification/test/{data_id}_red.png', 0),\n        cv2.imread(f'../input/hpa-single-cell-image-classification/test/{data_id}_yellow.png', 0),\n        cv2.imread(f'../input/hpa-single-cell-image-classification/test/{data_id}_blue.png', 0),\n    ], axis=2)\n    cell_image = cv2.resize(cell_image, (512, 512))\n    ax[i].imshow(cell_image)\n    ax[i].imshow(cell_mask, alpha=0.5)\n    ax[i].axis('off')\n    \n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Original (Overlay)"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.read_csv('./sample_submission.csv')\nfig, ax = plt.subplots(1,3, figsize=(20,50))\n\nfor i, data_id in enumerate(test_df.ID.to_list()[:3]):\n    cell_mask = np.load(f'/temp/test_mask_original/{data_id}_cell.npy')\n    nuc_mask = np.load(f'/temp/test_mask_original/{data_id}_nuc.npy')\n    cell_image = np.stack([\n        cv2.imread(f'../input/hpa-single-cell-image-classification/test/{data_id}_red.png', 0),\n        cv2.imread(f'../input/hpa-single-cell-image-classification/test/{data_id}_yellow.png', 0),\n        cv2.imread(f'../input/hpa-single-cell-image-classification/test/{data_id}_blue.png', 0),\n    ], axis=2)\n#     cell_image = cv2.resize(cell_image, (512, 512))\n    ax[i].imshow(cell_image)\n    ax[i].imshow(cell_mask, alpha=0.5)\n    ax[i].axis('off')\n    \n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Faster HPA Cell Segmentation (Mask Only)"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.read_csv('./sample_submission.csv')\nfig, ax = plt.subplots(1,3, figsize=(20,50))\n\nfor i, data_id in enumerate(test_df.ID.to_list()[:3]):\n    cell_mask = np.load(f'/temp/test_mask/{data_id}_cell.npy')\n    nuc_mask = np.load(f'/temp/test_mask/{data_id}_nuc.npy')\n    cell_image = np.stack([\n        cv2.imread(f'../input/hpa-single-cell-image-classification/test/{data_id}_red.png', 0),\n        cv2.imread(f'../input/hpa-single-cell-image-classification/test/{data_id}_yellow.png', 0),\n        cv2.imread(f'../input/hpa-single-cell-image-classification/test/{data_id}_blue.png', 0),\n    ], axis=2)\n    cell_image = cv2.resize(cell_image, (512, 512))\n#     ax[i].imshow(cell_image)\n    ax[i].imshow(cell_mask, alpha=1.0)\n    ax[i].axis('off')\n    \n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Original (Mask Only)"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.read_csv('./sample_submission.csv')\nfig, ax = plt.subplots(1,3, figsize=(20,50))\n\nfor i, data_id in enumerate(test_df.ID.to_list()[:3]):\n    cell_mask = np.load(f'/temp/test_mask_original/{data_id}_cell.npy')\n    nuc_mask = np.load(f'/temp/test_mask_original/{data_id}_nuc.npy')\n    cell_image = np.stack([\n        cv2.imread(f'../input/hpa-single-cell-image-classification/test/{data_id}_red.png', 0),\n        cv2.imread(f'../input/hpa-single-cell-image-classification/test/{data_id}_yellow.png', 0),\n        cv2.imread(f'../input/hpa-single-cell-image-classification/test/{data_id}_blue.png', 0),\n    ], axis=2)\n#     cell_image = cv2.resize(cell_image, (512, 512))\n#     ax[i].imshow(cell_image)\n    ax[i].imshow(cell_mask, alpha=1.0)\n    ax[i].axis('off')\n    \n","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}