{"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":"!pip install ../input/pycocotools202/pycocotools-2.0.2-cp37-cp37m-linux_x86_64.whl","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install \"../input/pytorch/pytorch_zoo-master\"\n!pip install \"../input/hpacellsegmentatormaster/HPA-Cell-Segmentation-master\"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom dask import delayed\nimport os\nimport re\nimport hpacellseg.cellsegmentator as cellsegmentator\nfrom hpacellseg.utils import label_cell, label_nuclei\nimport cv2\nfrom PIL import Image\nfrom keras.models import load_model\nfrom keras_preprocessing.image import ImageDataGenerator\nimport base64\nfrom pycocotools import _mask as coco_mask\nimport typing as t\nimport zlib","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CellProcessor:\n    \n    def __init__(self, cell, protein_path):\n        # 3 channels paths for segmentation\n        self.cell = cell\n        # Last channel for protein img\n        self.protein_path = protein_path \n            \n        self.protein_cells = ()\n        self.resized_masks = () # Used in crop_cell function\n        self.encoded_masks = () # Used for submission.csv\n        self.cropped_cells = () # will be converted to .png to used in test_data generator\n        \n    \n    def add_padding(self, img):\n        img = cv2.copyMakeBorder(img, 224, 224, 224, 224,\n                                 cv2.BORDER_CONSTANT)\n        return img\n    \n    \n    def img_resize(self, img, dim):\n        resized_cell = cv2.resize(img, dim,\n                                  interpolation=cv2.INTER_NEAREST)\n        return resized_cell\n    \n    \n    def encode_binary_mask(self, mask: np.ndarray) -> t.Text:\n        \"\"\"Converts a binary mask into OID challenge encoding ascii text.\"\"\"\n        \n        # check input mask --\n        if mask.dtype != np.bool:\n            raise ValueError(\n                \"encode_binary_mask expects a binary mask, received dtype == %s\" %\n                mask.dtype)\n        \n        mask = np.squeeze(mask)\n        if len(mask.shape) != 2:\n            raise ValueError(\n                \"encode_binary_mask expects a 2d mask, received shape == %s\" %\n                mask.shape)\n        \n        # convert input mask to expected COCO API input --\n        mask_to_encode = mask.reshape(mask.shape[0], mask.shape[1], 1)\n        mask_to_encode = mask_to_encode.astype(np.uint8)\n        mask_to_encode = np.asfortranarray(mask_to_encode)\n        \n        # RLE encode mask --\n        encoded_mask = coco_mask.encode(mask_to_encode)[0][\"counts\"]\n        \n        # compress and base64 encoding --\n        binary_str = zlib.compress(encoded_mask, zlib.Z_BEST_COMPRESSION)\n        base64_str = base64.b64encode(binary_str)\n        \n        # Decode the bytes to get rid of b letter \n        encoded_mask = base64_str.decode('utf-8')\n        \n        # Save encoded mask\n        self.encoded_masks += (encoded_mask,)\n    \n    \n    \n    def crop_cell(self):\n        \n        @delayed\n        def run(protein_cell, bool_mask):\n            # bool_mask is used to create a binary_mask\n            binary_mask = bool_mask.astype(np.uint8)\n            \n            # Make a bounding box around the cell\n            contour,_ = cv2.findContours(\n                binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE\n            )\n            cell_area = max(contour, key=cv2.contourArea)\n            x,y,w,h = cv2.boundingRect(cell_area)\n            cv2.rectangle(protein_cell, (x,y), (x+w, y+h), (0,0), 1)\n            \n            # Cropped the ROI (cell) as square\n            if w > h:\n                h = w # Assign the largest number to both h and w\n            else:\n                w = h\n            cell = protein_cell[y:y+h, x:x+w] # The img size changed\n            \n            # Resize the cell image to 224x224\n            cell = self.img_resize(cell, (224,224))\n            return cell\n            \n        for protein_cell, bool_mask in zip(self.protein_cells,\n                                           self.resized_masks):\n            cropped_cell = delayed(run)(protein_cell, bool_mask)\n            self.cropped_cells += (cropped_cell.compute(),)\n    \n    \n    def overlay_protein_image(self, cells_in_img):\n        \n        @delayed(nout=2)\n        def run(cell):\n            # Make a copy of protein_image;\n            # to prevent inplace changes to the image\n            protein_copy = protein_img.copy()\n            # Mask the cell (boolean_mask)\n            mask_cell = cell != 0\n            \n            # Dilate cells to make border around cell\n            kernel = np.ones((3,3))\n            dilated_cell = cv2.dilate(cell, kernel, iterations=1)\n            mask_cell_with_border = dilated_cell != 0\n            \n            # Overlay protein image on cell mask\n            not_cell = ~ mask_cell\n            border = not_cell & mask_cell_with_border\n            protein_copy[not_cell] = 0\n            protein_copy[border] = 255\n            \n            return protein_copy, mask_cell\n        \n    \n        # Read protein image and convert it to grayscale \n        protein_img = cv2.imread(self.protein_path) \n        protein_img = cv2.cvtColor(protein_img, cv2.COLOR_BGR2GRAY)\n        \n        # Resize the protein cell image to 500x500\n        protein_img = self.img_resize(protein_img, (500,500))\n        \n        # Add padding to crop the cells later with same sizes\n        protein_img = self.add_padding(protein_img)\n        \n        # Iterate ovr cells in the image \n        for cell in cells_in_img:\n            protein_copy, mask_cell = delayed(run)(cell)\n            self.protein_cells += (protein_copy.compute(),)\n            self.resized_masks += (mask_cell.compute(),)\n        \n        return self.crop_cell()\n    \n    \n    \n    def cells_separation(self, cell_mask):\n        # Get the pixels of each cell\n        cell_mask = cell_mask.astype(np.uint8)\n        cells_pixels = set(np.ravel(cell_mask))\n        cells_pixels.remove(0)\n        \n        @delayed\n        def run(cell_pixels):\n            # Get the the array of each cell in image\n            cell = np.where(cell_mask == cell_pixels, cell_mask, 0)\n            # Get the mask of each cell\n            mask = cell != 0\n            # Encode mask to string to be evaluated.\n            self.encode_binary_mask(mask)\n            \n            # Resize the cell image to 500x500\n            cell = self.img_resize(cell, (500,500))\n            # Add padding; to crop the cells later with same sizes\n            cell = self.add_padding(cell)\n            \n            return cell\n        \n        \n        # Iterate over cells pixels to separate each cell\n        cells_in_img = ()\n        for cell_pixels in cells_pixels:\n            cell = delayed(run)(cell_pixels)\n            cells_in_img += (cell.compute(),)\n        \n        return self.overlay_protein_image(cells_in_img)\n    \n    def run(self):\n        self.cells_separation(self.cell)\n        return (self.encoded_masks, self.cropped_cells)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class MakeImage:\n    \n    def __init__(self, cropped_cells, ID):\n        self.cropped_cells = cropped_cells\n        self.ID = ID\n        \n    def start(self):\n        processed_imgs_paths = ()\n        # Save each cell image in .png file\n        for idx, cell in enumerate(self.cropped_cells):\n            img = Image.fromarray(cell)\n            img_path = f'{self.ID}_{idx}.png'\n            processed_imgs_paths += (img_path,)\n            img.save(f'./processed_test_imgs/{self.ID}_{idx}.png')\n        return processed_imgs_paths","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class DFConstructor:\n    \n    def __init__(self, cell_mask, protein_path, img_id):\n        self.cell = cell_mask\n        self.ID = img_id\n        self.protein_path = protein_path\n        \n    def construct(self):    \n        # Get protein_cells, masks, cropped_cells\n        processing = CellProcessor(cell=self.cell, protein_path=self.protein_path)\n        encoded_masks, cropped_cells = processing.run()\n        makeimg = MakeImage(cropped_cells, self.ID)\n        processed_imgs_paths = makeimg.start()\n                \n        # Create df to use in test generator\n        cells_num = len(cropped_cells)\n        df = pd.DataFrame({'ID': [self.ID] * cells_num,\n                           'encoded_masks': encoded_masks,\n                           'processed_imgs': processed_imgs_paths})\n        return df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class SubmissionCreator:\n    def __init__(self, pred_df):\n        self.pred_df = pred_df\n        self.cells_classes = ()\n        self.cells_confidence = ()\n\n    \n    def pred_string(self):\n        # Get classes of each cell and confidence values\n        for idx, row in self.pred_df.iterrows():\n            pred = np.array(row.predictions) \n            pred_bool = (pred > 0.1)\n            cell_classes = np.where(pred_bool)[0].tolist() # ex: [0, 5, 14]\n            cell_confidence = pred[pred_bool].tolist()\n            \n            # Save cell classes and confidence values\n            self.cells_classes += (cell_classes,)\n            self.cells_confidence += (cell_confidence,)\n        \n        # Create classes and confidence columns\n        self.pred_df['classes'] = self.cells_classes\n        self.pred_df['confidence'] = self.cells_confidence\n        \n        # Create prediction string\n        for id in self.pred_df['ID'].unique().tolist():\n            id_pred_df = self.pred_df[self.pred_df['ID'] == id]\n            # These variables are correspond to one image id\n            encoded_masks = id_pred_df['encoded_masks'].tolist()\n            cells_classes = id_pred_df['classes'].tolist()\n            cells_confidence = id_pred_df['confidence'].tolist()\n            \n            # Create prediction string column\n            # pred_list structure: [[pred_str_cell_A_class_1, pred_str_cell_A_class_2,...],\n            # [pred_str_cell_B_class_1, pred_str_cell_B_class_2,...],...]\n            pred_list = [[f'{cells_classes[cell_idx][idx]} {cells_confidence[cell_idx][idx]} {mask}'\n                            for idx in range(len(cells_classes[cell_idx]))]\n                            for cell_idx, mask in enumerate(encoded_masks)] \n            # Flatten the list of lists to one big list\n            pred_list = list(np.concatenate(pred_list).flat)\n            # Join list elements to one big prediction string\n            pred_str = (' ').join(pred_list)\n            \n            # Create df contain only id with prediction string\n            df = pd.DataFrame([{'ID':id,\n                               'PredictionString':pred_str}])\n            yield df\n    \n    def create(self):\n        # Get the whole dataframe of all ids\n        whole_df = pd.concat(list(self.pred_string()), ignore_index=True)\n        whole_df.reset_index(drop=True, inplace=True)\n        \n        # create submission df \n        data_df.drop(columns='PredictionString', inplace=True)\n        submit_df = whole_df.merge(data_df, on='ID')  \n        ordered_cols = ['ID', 'ImageWidth', 'ImageHeight', 'PredictionString']\n        submit_df = submit_df[ordered_cols]\n        return submit_df\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir processed_test_imgs","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The idea of Below cell block (faster_HPA_cell_segmentor) goes to: https://www.kaggle.com/linshokaku/faster-hpa-cell-segmentation/output\n\nBut the code has been modified a little to adapt my approach.","metadata":{}},{"cell_type":"code","source":"import 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('../input/hpa-single-cell-image-classification/sample_submission.csv')\ndata_size = len(data_df)\nbs = 240\n\ntest_data_path = '../input/hpa-single-cell-image-classification/test/'\ndef load_images(df : pd.DataFrame, root=test_data_path):\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        \ndfs = []    \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 img processing ----')\n    \n    for data_id, nuc_seg, cell_seg in zip(test_df.ID.to_list(), nuc_segmentations, cell_segmentations):\n        protein_path = test_data_path + data_id + '_green.png'\n        nuc, cell = label_cell(nuc_seg, cell_seg)\n        # Construct df of processed imgs to use in test data generator\n        construct = DFConstructor(cell_mask= cell, protein_path=protein_path, img_id=data_id)\n        df = construct.construct()\n        dfs.append(df)\n  \n    print('---- finish img processing ----')\n\n\n# Get the whole dataframe of all images (test_df)\ntest_df = pd.concat(dfs, ignore_index=True)\ntest_df.reset_index(drop=True, inplace=True)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load model \nmodel = load_model('../input/model-weights-1/AlexNet_1.hdf5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create test data generator\ntest_datagen = ImageDataGenerator(rescale=1./255.)\ntest_generator = test_datagen.flow_from_dataframe(\ndataframe=test_df,\ndirectory='./processed_test_imgs',\nx_col='processed_imgs',\ntarget_size=(224,224),\nbatch_size=1,\nclass_mode=None,\nshuffle=False)\n\n# Predict the classes of cells\npredictions = model.predict(test_generator)\n\n# Prediction df\npred_df = pd.DataFrame({'processed_imgs':test_generator.filenames,\n                        'predictions':predictions.tolist()})\n# Merge pred_df with test_df\npred_df = pred_df.merge(test_df, on='processed_imgs')\n\n# Create submission file\nsubmission = SubmissionCreator(pred_df)\nsubmit_df = submission.create()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Remove processed_imgs directory\nprocessed_img_dir = './processed_test_imgs'\nfilelist = [f for f in os.listdir(processed_img_dir)]\nfor file in filelist:\n    os.remove(os.path.join(processed_img_dir, file))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submit_df.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}