:orphan: Source: bactoscoop/image.py =========================== .. raw:: html
  1# -*- coding: utf-8 -*-
     2"""
     3Created on Wed Apr  5 09:45:53 2023
     4
     5@author: Bart Steemans. Govers Lab.
     6"""
     7from .features import Features
     8from . import utilities as u
     9from .logging_utils import tqdm_if_verbose
    10import numpy as np
    11import pandas as pd
    12import warnings
    13import cv2 as cv
    14import logging
    15
    16warnings.filterwarnings("ignore")
    17bactoscoop_logger = logging.getLogger("logger")
    18
    19
    20class Image:
    21
    22    def __init__(
    23        self,
    24        image,
    25        image_name,
    26        frame,
    27        mask=None,
    28        processed_mesh_dataframe=None,
    29        px=0.065,
    30    ):
    31        """
    32        Initialize an instance of your class.
    33
    34        Parameters
    35        ----------
    36        image : phase contrast image
    37            The phase contrast image associated with this instance.
    38        image_name : str
    39            The name or identifier of the image.
    40        frame : int
    41            The frame number
    42        mask : mask, optional
    43            The segmented image.
    44        processed_mesh_dataframe : pd.DataFrame, optional
    45            A processed mesh dataframe if available. (default is None)
    46        px : float, optional
    47        The pixel size in micrometers. (default is 0.065)
    48        """
    49
    50        self.mask = mask
    51        self.cells = []  # List of cell objects
    52        self.px = px  # micron per pixel
    53        self.image_name = image_name
    54        self.frame = frame
    55        self.image = image
    56        self.channels = None  # Dictionary of the color channels
    57
    58        self.joined_mask = None  # Mask images after cell joining
    59        self.processing_mask = None  # Optional filtered mask used only for processing
    60        self.prefilter_summary = None
    61        self.mesh_dataframe = (
    62            None  # Resulting dataframe containing the meshes of the cells
    63        )
    64        self.processed_mesh_dataframe = processed_mesh_dataframe
    65
    66        self.im_interp2d = None  # 2D interpolation of the phase contrast image
    67        self.chann_interp2d = {}  # Cached interpolators of background-corrected channels
    68        self.bg_channels = (
    69            {}
    70        )  # Background-subtracted channel images, clipped at zero
    71        self.inverted_image = None  # Placeholder for the inverted phase contrast image
    72        self.feature_errors = []
    73        self.object_detection_errors = []
    74        self.shift_errors = []
    75
    76    def calculate_features(
    77        self,
    78        method,
    79        channel,
    80        all_data,
    81        use_shifted_contours,
    82        shift_signal,
    83        max_mesh_size,
    84        retain_contour_on_object_mesh_failure_channels=None,
    85    ):
    86        """
    87        Calculate features for cells based on the specified method and channel.
    88
    89        This method calculates features for individual cells in the image based on the provided method
    90        and channel. It also allows for adding profiling data if required.
    91
    92        Parameters
    93        ----------
    94        method : str
    95            The method used to calculate features for cells.
    96            The methods are: 'morphological', 'profiling', 'svm', 'objects', 'phase'. (To be expanded)
    97        channel : str
    98            The channel for which features are calculated.
    99        add_profiling_data : bool
   100            Whether to include profiling data in the feature calculations.
   101
   102        Returns
   103        -------
   104        pd.DataFrame
   105            A DataFrame containing the calculated features for the cells.
   106        """
   107        features = Features(self)
   108        if retain_contour_on_object_mesh_failure_channels is None:
   109            retained_channels = frozenset()
   110        elif isinstance(retain_contour_on_object_mesh_failure_channels, str):
   111            raise TypeError(
   112                "retain_contour_on_object_mesh_failure_channels must be a list "
   113                "of channel names, not a string."
   114            )
   115        else:
   116            retained_channels = frozenset(
   117                retain_contour_on_object_mesh_failure_channels
   118            )
   119        if not all(isinstance(name, str) for name in retained_channels):
   120            raise TypeError(
   121                "retain_contour_on_object_mesh_failure_channels must contain "
   122                "only channel names."
   123            )
   124        result_df = None
   125        self.feature_errors = []
   126
   127        # First, filter out cells that should be discarded by discard_large_meshes
   128        filtered_cells = []
   129        for cell in self.cells:
   130            cell.discard = False
   131            features.discard_large_meshes(cell, max_mesh_size)
   132
   133            if not cell.discard:
   134                filtered_cells.append(cell)
   135
   136        # Update self.cells to only contain non-discarded cells
   137        self.cells = filtered_cells
   138
   139        # Now, process the remaining cells
   140        for cell in self.cells:
   141            feature_calculation_method = f"{method}"
   142
   143            if hasattr(features, feature_calculation_method):
   144                try:
   145                    calculation_method = getattr(features, feature_calculation_method)
   146
   147                    if method == "objects":
   148                        calculation_method(
   149                            cell, channel, all_data, use_shifted_contours,
   150                            shift_signal,
   151                            retain_contour_on_object_mesh_failure=(
   152                                channel in retained_channels
   153                            ),
   154                        )
   155                    else:
   156                        calculation_method(
   157                            cell, channel, all_data, use_shifted_contours,
   158                            shift_signal,
   159                        )
   160
   161                except Exception as e:
   162                    cell.discard = True
   163                    self.feature_errors.append(
   164                        {
   165                            "cell_id": cell.cell_id,
   166                            "error_type": type(e).__name__,
   167                            "error": str(e),
   168                        }
   169                    )
   170            if feature_calculation_method == "svm":
   171
   172                filtered_cells = []
   173                for cell in self.cells:
   174                    if not cell.discard:
   175                        filtered_cells.append(cell)
   176
   177                # Update self.cells to only contain non-discarded cells
   178                self.cells = filtered_cells
   179        result_df = self.features_to_dataframe(method)
   180        return result_df
   181
   182    def features_to_dataframe(self, method):
   183        """
   184        Convert cell features stored in a dictionary to a pandas DataFrame.
   185
   186        This method takes a dictionary of cell features, specified by the method name, and converts it into a pandas DataFrame.
   187        Additionally, it adds information features to the DataFrame.
   188
   189        Parameters
   190        ----------
   191        method : str
   192            The name of the method used for feature calculation.
   193
   194        Returns
   195        -------
   196        pd.DataFrame
   197            A DataFrame containing cell features.
   198        """
   199        features_df = self.dataframe_from_dict(f"{method}_features")
   200
   201        self.add_info_feature_df(features_df)
   202
   203        return features_df
   204
   205    def dataframe_from_dict(self, feature_dictionary):
   206        """
   207        Convert a feature dictionary to a pandas DataFrame.
   208
   209        This method takes a feature dictionary, which maps cell IDs to feature values, and converts it into a pandas DataFrame.
   210
   211        Parameters
   212        ----------
   213        feature_dictionary : str
   214            The name of the feature dictionary to convert.
   215
   216        Returns
   217        -------
   218        pd.DataFrame
   219            A DataFrame containing cell features.
   220        """
   221        data = {
   222            cell.cell_id: getattr(cell, feature_dictionary)
   223            for cell in self.cells
   224            if not cell.discard
   225        }
   226
   227        df = pd.DataFrame.from_dict(data, orient="index")
   228
   229        return df
   230
   231    def add_info_feature_df(self, dataframe):
   232        """
   233        Add information columns to a feature DataFrame.
   234
   235        This method adds information columns, including 'image_name', 'cell_id', and 'frame',
   236        to an existing DataFrame.
   237
   238        Parameters
   239        ----------
   240        dataframe : pd.DataFrame
   241            The DataFrame to which information columns will be added.
   242        """
   243
   244        dataframe.insert(0, "image_name", self.image_name)
   245        dataframe.insert(
   246            0, "cell_id", [cell.cell_id for cell in self.cells if not cell.discard]
   247        )
   248        dataframe.insert(0, "frame", self.frame)
   249
   250    def _active_mask(self):
   251        return self.processing_mask if self.processing_mask is not None else self.mask
   252
   253    def apply_neighbor_prefilter(self, max_neighbors=None, connectivity=1):
   254        self.processing_mask = None
   255        self.prefilter_summary = None
   256
   257        if max_neighbors is None:
   258            return None
   259
   260        if self.mask is None:
   261            raise ValueError("Mask image is not loaded")
   262
   263        filtered_mask, stats = u.filter_labels_by_neighbor_count(
   264            self.mask,
   265            max_neighbors=max_neighbors,
   266            connectivity=connectivity,
   267        )
   268
   269        if stats["removed_label_count"] > 0:
   270            self.processing_mask = filtered_mask
   271
   272        self.prefilter_summary = stats
   273        bactoscoop_logger.info(
   274            "Neighbor prefilter on %s kept %s/%s labels (removed %s with > %s neighbors)",
   275            self.image_name,
   276            stats["kept_label_count"],
   277            stats["total_label_count"],
   278            stats["removed_label_count"],
   279            stats["max_neighbors"],
   280        )
   281        return stats
   282
   283    def join_split_pipeline(
   284        self,
   285        join_thresh=4,
   286        split_thresh=0.3,
   287        CD_width=False,
   288        smoothing=0.1,
   289        neighbor_filter_max_neighbors=None,
   290        neighbor_filter_connectivity=1,
   291        max_daughter_cell_mesh_rows=800,
   292    ):
   293        """
   294        Perform a pipeline for joining and splitting cells.
   295
   296        This method is used within the batch_mesh_process() method of ImageCollection. It involves joining cells based on
   297        a specified threshold, converting masks to mesh data, splitting cells based on a specified threshold,
   298        and creating cell objects.
   299
   300        Parameters
   301        ----------
   302        join_thresh : int, optional
   303            Join cell masks when their nearest poles are at most join_thresh
   304            pixels apart. (default is 4)
   305        split_thresh : float, optional
   306            The threshold for splitting cells. (default is 0.3)
   307        max_daughter_cell_mesh_rows : int, optional
   308            Maximum rebuilt daughter mesh rows (default 800, minimum 4).
   309            Oversized resampling is rejected before its dense allocations.
   310
   311        Returns
   312        -------
   313        None
   314        """
   315        max_daughter_cell_mesh_rows = u._validate_max_daughter_cell_mesh_rows(
   316            max_daughter_cell_mesh_rows
   317        )
   318        self.apply_neighbor_prefilter(
   319            max_neighbors=neighbor_filter_max_neighbors,
   320            connectivity=neighbor_filter_connectivity,
   321        )
   322        self.join_cells(join_thresh, smoothing)
   323        self.mask2mesh(smoothing)
   324        self.split_cells(
   325            split_thresh, CD_width,
   326            max_daughter_cell_mesh_rows=max_daughter_cell_mesh_rows,
   327        )
   328        self.create_cell_object()
   329
   330    def create_cell_object(self, verbose=True):
   331        """
   332        Create Cell objects from mesh data.
   333
   334        This method creates Cell objects based on mesh data contained in a DataFrame. The Cell objects are
   335        initialized with contour, mesh, and midline data, and they are added to the list of cells in the Image object.
   336
   337        Parameters
   338        ----------
   339        verbose : bool, optional
   340            Whether to print a message indicating the source of the Cell objects (processed or unprocessed meshes). (default is True)
   341
   342        Returns
   343        -------
   344        None
   345        """
   346        self.cells = []
   347
   348        if self.processed_mesh_dataframe is None:
   349            try:
   350                dataframe = self.mesh_dataframe
   351                message_prefix = "Cell objects are created from unprocessed meshes"
   352            except AttributeError:
   353                bactoscoop_logger.info(
   354                    "No meshes from the masks. Either process the masks or load in mesh data from a .pkl file."
   355                )
   356                return
   357        else:
   358            dataframe = self.processed_mesh_dataframe
   359            message_prefix = "Cell objects are created from processed meshes"
   360
   361        for i, row in dataframe.iterrows():
   362            if "cell_id" not in row or pd.isna(row["cell_id"]):
   363                cell_ID = i
   364            else:
   365                cell_ID = row["cell_id"]
   366            contours = np.array(row["contour"])
   367            meshes = np.array(row["mesh"])
   368            midlines = np.array(row["midline"])
   369            cell = Cell(contours, meshes, midlines, self.image.shape, cell_ID)
   370            self.add_cell(cell)
   371
   372        num_cells_created = len(self.cells)
   373        message = f"{message_prefix}. {num_cells_created} Cell objects are created."
   374
   375        if verbose:
   376            print(message)
   377
   378    def add_cell(self, cell):
   379        """
   380        Add a Cell object to the list of cells in the Image object.
   381        """
   382        self.cells.append(cell)
   383
   384    def get_inverted_image(self):
   385        """
   386        Calculate the inverted image for phase contrast.
   387
   388        This method computes the inverted image for phase contrast imaging. It subtracts the maximum pixel value
   389        from the original image and does a background subtraction (bgr = mean(background intensity)) to obtain the inverted image.
   390
   391        """
   392        inverted_image = np.subtract(np.max(self.image), self.image)
   393        bgr = u.median_background(inverted_image, self.mask)  #
   394        self.inverted_image = np.maximum(inverted_image - bgr, 0)
   395        self.im_interp2d = None
   396
   397    def get_bg_channel(self, channel):
   398        """Cache a background-subtracted image for the requested channel.
   399
   400        Fit the background to pixels outside the segmentation labels, subtract
   401        it from the original channel image, and clip negative values to zero.
   402        The corrected image is stored in ``bg_channels[channel]``; the original
   403        image in ``channels[channel]`` is unchanged. Returns None.
   404        """
   405        _, bg_matrix = u.construct_bg_function(
   406            self.channels[channel], self.mask
   407        )
   408        self.bg_channels[channel] = np.maximum(self.channels[channel] - bg_matrix, 0)
   409        self.chann_interp2d.pop(channel, None)
   410
   411    def get_inverted_interp2d(self):
   412        if self.inverted_image is None:
   413            self.get_inverted_image()
   414        if self.im_interp2d is None:
   415            self.im_interp2d = u.interp2d(self.inverted_image)
   416        return self.im_interp2d
   417
   418    def get_channel_interp2d(self, channel):
   419        if channel not in self.bg_channels:
   420            self.get_bg_channel(channel)
   421        if channel not in self.chann_interp2d:
   422            self.chann_interp2d[channel] = u.interp2d(self.bg_channels[channel])
   423        return self.chann_interp2d[channel]
   424
   425    def channel_interp2d(self):
   426        """
   427        Interpolate channel images using 2D spline interpolation.
   428
   429        This method interpolates the channel images using 2D spline interpolation and stores the interpolated images
   430        in the 'chann_interp2d' dictionary.
   431        """
   432        for channel in self.channels:
   433            self.get_channel_interp2d(channel)
   434
   435    def join_cells(self, thresh=None, smoothing=0.1):
   436        """
   437        Join cells based on pole-to-pole distance.
   438
   439        This method attempts to join adjacent cells within the image based on the distance between their poles. It identifies cell pairs
   440        with pole-to-pole distances at or below a specified threshold and merges them into a single cell. The joined cell IDs are updated in the
   441        'joined_mask' array.
   442
   443        Parameters
   444        ----------
   445        thresh : float, optional
   446            The distance threshold for joining cells. Cells with pole-to-pole distances at or below this value will be merged. If None, no
   447            threshold is applied, and all cells will be considered for joining. (default is None)
   448
   449        """
   450
   451        mask = self._active_mask()
   452        if mask is None:
   453            raise ValueError("Mask image is not loaded")
   454        bactoscoop_logger.info(">>> Joining cells ...")
   455
   456        pole_1 = []
   457        pole_2 = []
   458        cell_ID = []
   459        cell_labels = np.unique(mask)
   460        cell_labels = cell_labels[cell_labels != 0]
   461
   462        for cell in tqdm_if_verbose(cell_labels):
   463            temp_mask = np.where(mask == cell, 1, 0)
   464            temp_mask = cv.convertScaleAbs(temp_mask)
   465
   466            _, cropped_mask, _, x, y = u.crop_image(mask_to_crop=temp_mask)
   467
   468            cell_contours = u.get_object_contours(cropped_mask, smoothing=smoothing)
   469            for cn in cell_contours:
   470                try:
   471                    skeleton = u.extract_skeleton(cropped_mask)
   472                except Exception:
   473                    skeleton = []
   474                    cell_ID.append(cell)
   475                    continue
   476                if np.any(skeleton):
   477                    extended_skeleton, pole1, pole2 = u.extend_skeleton(
   478                        skeleton, cn, find_pole1=True, find_pole2=True
   479                    )
   480                    pole1 += np.array([y, x])
   481                    pole2 += np.array([y, x])
   482                    if pole1.shape == (1, 2) and pole2.shape == (1, 2):
   483                        pole_1.append(pole1)
   484                        pole_2.append(pole2)
   485                    else:
   486                        cell_ID.append(cell)
   487                else:
   488                    cell_ID.append(cell)
   489
   490        if pole_1 == []:
   491            cell_pairs = []
   492        else:
   493            pole_1 = np.vstack(np.array(pole_1))
   494            pole_2 = np.vstack(np.array(pole_2))
   495
   496            cell_pairs = u.get_cell_pairs(pole_1, pole_2, cell_ID, thresh)
   497
   498        if not np.any(cell_pairs):
   499            self.joined_mask = np.copy(mask)
   500        else:
   501            # Create a copy of the original masks array to store the new masks
   502            new_masks = np.copy(mask)
   503            dsu = {}
   504            for mask in np.unique(cell_pairs):
   505                dsu[mask + 1] = mask + 1
   506            # Merge masks that belong to the same group
   507            for mask1, mask2 in cell_pairs:
   508                root1 = mask1 + 1
   509                while root1 != dsu[root1]:
   510                    root1 = dsu[root1]
   511                root2 = mask2 + 1
   512                while root2 != dsu[root2]:
   513                    root2 = dsu[root2]
   514                if root1 != root2:
   515                    dsu[root1] = root2
   516
   517            # Update the masks with the merged values
   518            for mask, root in dsu.items():
   519                new_masks[new_masks == mask] = root
   520            unique_masks = np.unique(new_masks)
   521            # Create a dictionary that maps unique mask values to new mask values starting from 1
   522            mask_dict = {mask: i for i, mask in enumerate(unique_masks)}
   523
   524            # Use the dictionary to relabel the new_masks array and the new_labels array
   525            new_masks_relabel = np.vectorize(mask_dict.get)(new_masks)
   526            self.joined_mask = new_masks_relabel
   527
   528    def mask2mesh(self, smoothing=0.1):
   529        """
   530        Create meshes from cell masks.
   531
   532        This method processes cell masks to create corresponding meshes. It generates contours and skeletons for each cell in the mask,
   533        extends the skeleton, and calculates additional geometric properties, such as length and width. Based on these properties, it
   534        straightens the cell contour and creates a mesh representation. The resulting mesh data, including contour, mesh, and midline,
   535        is stored in a DataFrame and associated with the image frame.
   536
   537        This method is based on the cell profile creation of the MOMIA package (doi: 10.1016/j.celrep.2021.110154)
   538
   539        """
   540        if self.joined_mask is not None:
   541            mask = self.joined_mask
   542            bactoscoop_logger.info(">>> Creating meshes from joined masks ...")
   543        else:
   544            mask = self._active_mask()
   545            bactoscoop_logger.info(">>> Creating meshes from raw masks ...")
   546        # loop through all cells in the frame
   547        self.mesh_dataframe = u.get_cellular_mesh(mask, smoothing=smoothing)
   548        self.mesh_dataframe["frame"] = self.frame
   549        self.mesh_dataframe["image_name"] = self.image_name
   550
   551    def split_cells(self, thresh=0.3, CD_width=False, max_daughter_cell_mesh_rows=800):
   552        """
   553        Split cells based on a constriction degree threshold.
   554
   555        This method separates cells within the image based on a given constriction degree threshold. It calculates the constriction degree
   556        for each cell and, if it exceeds the threshold, splits the cell into two separate cells. The new mesh data, including contour, mesh,
   557        and midline, is stored in a DataFrame and associated with the image frame.
   558
   559        This method is based on the splitting algorithm in the Oufti software package (doi: 10.1111/mmi.13264).
   560
   561        Parameters
   562        ----------
   563        thresh : float, optional
   564            The constriction degree threshold for splitting cells. Cells with a constriction degree greater than this threshold will be split.
   565            The default is 0.3.
   566
   567        max_daughter_cell_mesh_rows : int, optional
   568            Maximum final mesh rows per daughter (default 800, minimum 4).
   569            Reject oversized predicted row counts before reconstruction, then
   570            require both final daughters to have between 4 and
   571            max_daughter_cell_mesh_rows mesh rows, inclusive. If either fails,
   572            neither daughter nor the parent enters the processed dataframe.
   573
   574        """
   575        max_daughter_cell_mesh_rows = u._validate_max_daughter_cell_mesh_rows(
   576            max_daughter_cell_mesh_rows
   577        )
   578        self.get_inverted_image()
   579        im_interp2d = u.interp2d(self.inverted_image)
   580
   581        bactoscoop_logger.info(">>> Splitting cells ...")
   582
   583        new_meshes = []
   584        new_contours = []
   585        new_midlines = []
   586
   587        for row in tqdm_if_verbose(self.mesh_dataframe.itertuples(index=False)):
   588
   589            x1 = row.mesh[:, 0]
   590            y1 = row.mesh[:, 1]
   591            x2 = row.mesh[:, 2]
   592            y2 = row.mesh[:, 3]
   593            contour = row.contour
   594            midline = row.midline
   595
   596            complete_mesh = np.array(np.column_stack((x1, y1, x2, y2)))
   597
   598            step_length_px = u.get_step_length(x1, y1, x2, y2, self.px)
   599
   600            width_px = u.get_width(x1, y1, x2, y2) * self.px
   601            if CD_width:
   602                weighted_intprofile = width_px
   603            else:
   604                intprofile = u.measure_smoothened_intensity(
   605                    midline, im_interp2d, width=5
   606                )
   607                weighted_intprofile = u.get_weighted_intprofile(intprofile, width_px)
   608
   609            constrDegree, relPos, constrDegree_abs, ctpos, _= (
   610                u.constr_degree_single_cell_min(
   611                    weighted_intprofile,
   612                    step_length_px,
   613                    upper_limit=0.95,
   614                    lower_limit=0.05,
   615                )
   616            )
   617
   618            if 0.95 > constrDegree > thresh:
   619                try:
   620                    x, y, left, right = u.split_point(x1, y1, x2, y2, ctpos)
   621
   622                    mesh1rec = np.concatenate(
   623                        (complete_mesh[: (ctpos - 2)], right, np.array([[x, y, x, y]]))
   624                    )
   625                    mesh2rec = np.concatenate(
   626                        (np.array([[x, y, x, y]]), left, complete_mesh[(ctpos + 2) :])
   627                    )
   628
   629                    mesh1, contour1, midline1 = u.split_mesh2mesh(
   630                        mesh1rec[:, 0], mesh1rec[:, 1], mesh1rec[:, 2], mesh1rec[:, 3],
   631                        max_daughter_cell_mesh_rows=max_daughter_cell_mesh_rows,
   632                    )
   633                    mesh2, contour2, midline2 = u.split_mesh2mesh(
   634                        mesh2rec[:, 0], mesh2rec[:, 1], mesh2rec[:, 2], mesh2rec[:, 3],
   635                        max_daughter_cell_mesh_rows=max_daughter_cell_mesh_rows,
   636                    )
   637                except Exception as e:
   638                    bactoscoop_logger.debug(f"{e}")
   639                    continue
   640                if all(4 <= len(daughter) <= max_daughter_cell_mesh_rows for daughter in (mesh1, mesh2)):
   641                    new_meshes.append(mesh1)
   642                    new_meshes.append(mesh2)
   643
   644                    new_contours.append(contour1)
   645                    new_contours.append(contour2)
   646
   647                    new_midlines.append(midline1)
   648                    new_midlines.append(midline2)
   649                else:
   650                    bactoscoop_logger.debug(
   651                        "Splitting resulted in a daughter mesh outside 4-%s rows",
   652                        max_daughter_cell_mesh_rows,
   653                    )
   654
   655            else:
   656
   657                new_meshes.append(complete_mesh)
   658                new_contours.append(contour)
   659                new_midlines.append(midline)
   660        self.processed_mesh_dataframe = pd.DataFrame(
   661            {"mesh": new_meshes, "contour": new_contours, "midline": new_midlines}
   662        )
   663        self.processed_mesh_dataframe["frame"] = self.frame
   664        self.processed_mesh_dataframe["image_name"] = self.image_name
   665
   666    def object_detection(
   667        self,
   668        channels=None,
   669        smoothing=0.1,
   670        align=False,
   671        log_sigma=3,
   672        kernel_width=4,
   673        min_overlap_ratio=0.01,
   674        max_external_ratio=0.1,
   675    ):
   676        """
   677        Detect subcellular objects within cell contours in specified channels.
   678
   679        This method performs object detection within the contours of cells for the specified channels. It uses a Laplacian of Gaussian (LoG)
   680        filter to detect subcellular objects and returns their contours. The detected objects are stored in a DataFrame, including the frame,
   681        cell ID, channel name, and object contours.
   682
   683        Parameters
   684        ----------
   685        channels : List of str, optional
   686            The list of channel names for which to perform object detection.
   687
   688        log_sigma : int, optional
   689            The sigma parameter of the LoG filter used in object detection. Increasing this parameter may detect larger objects.
   690            The default is 3.
   691
   692        kernel_width : int, optional
   693            The kernel width used for dilating object masks. Increasing this value results in larger masks.
   694            The default is 4.
   695
   696        min_overlap_ratio : float, optional
   697            The minimum overlap ratio between detected objects and cell contours to keep the object. Objects with lower overlap are discarded.
   698            The default is 0.01.
   699
   700        max_external_ratio : float, optional
   701            The maximum ratio an object is allowed to lie outside the cell contour. Objects exceeding this ratio are discarded.
   702            The default is 0.1.
   703
   704        Returns
   705        -------
   706        pd.DataFrame
   707            A DataFrame containing information about the detected objects, including frame, cell ID, channel name, and object contours.
   708        """
   709
   710        all_objects = []
   711        self.object_detection_errors = []
   712
   713        for channel in channels:
   714            # A repeat attempt replaces this channel, even when it fails or
   715            # detects no objects. Results for other channels remain intact.
   716            for cell in self.cells:
   717                cell.object_meshdata.pop(channel, None)
   718
   719            if channel in self.channels:
   720
   721                for cell in self.cells:
   722                    if align:
   723                        img = self.image
   724                    else:
   725                        img = None
   726                    try:
   727                        meshdata = u.get_object_mesh(
   728                            cell.contour,
   729                            self.channels[channel],
   730                            img,
   731                            cell.cell_id,
   732                            smoothing,
   733                            log_sigma,
   734                            kernel_width,
   735                            min_overlap_ratio,
   736                            max_external_ratio,
   737                        )
   738                        cell.object_meshdata[channel] = meshdata
   739                        for mesh_error in meshdata.get("mesh_construction_errors", []):
   740                            self.object_detection_errors.append(
   741                                {
   742                                    "cell_id": cell.cell_id,
   743                                    "channel": channel,
   744                                    "error_type": mesh_error["error_type"],
   745                                    "error": (
   746                                        f"Object {mesh_error['object_index']} mesh construction "
   747                                        f"failed: {mesh_error['error']}"
   748                                    ),
   749                                    "recovered": True,
   750                                }
   751                            )
   752
   753                        if cell.object_meshdata[channel]["object_contour"]:
   754                            all_objects.append(
   755                                {
   756                                    "frame": self.frame,
   757                                    "cell_id": cell.cell_id,
   758                                    "cell_mesh": cell.mesh,
   759                                    "channel": channel,
   760                                    "object_contours": cell.object_meshdata[channel][
   761                                        "object_contour"
   762                                    ],
   763                                    "object_mesh": cell.object_meshdata[channel][
   764                                        "object_mesh"
   765                                    ],
   766                                    "object_midline": cell.object_meshdata[channel][
   767                                        "object_midline"
   768                                    ],
   769                                }
   770                            )
   771
   772                    except IndexError as e:
   773                        cell.object_meshdata.pop(channel, None)
   774                        self.object_detection_errors.append(
   775                            {
   776                                "cell_id": cell.cell_id,
   777                                "channel": channel,
   778                                "error_type": type(e).__name__,
   779                                "error": str(e),
   780                            }
   781                        )
   782
   783        detections_df = pd.DataFrame(all_objects)
   784
   785        return detections_df
   786
   787    def shift_correction(
   788        self,
   789        shifted_channel,
   790        log_sigma,
   791        kernel_width,
   792        min_overlap_ratio,
   793        max_external_ratio,
   794        phase_log_sigma,
   795        phase_closing_level,
   796        signal_closing_level,
   797        max_shift_correction,
   798    ):
   799        self.shift_errors = []
   800        if not self.cells:
   801            bactoscoop_logger.warning(
   802                f"No cells available for shift correction in frame {self.frame}."
   803            )
   804            return 0.0
   805
   806        for channel in shifted_channel:
   807            if channel not in self.channels:
   808                raise ValueError(
   809                    f"'{shifted_channel}' is not present in the channels attribute."
   810                )
   811            failed_attempts = 0
   812            for cell in self.cells:
   813                try:
   814                    cell.shifted_contour, cell.shifted_mesh, cell.shifted_midline = (
   815                        u.shift_contour(
   816                            self.image,
   817                            self.channels[channel],
   818                            cell.contour,
   819                            cell.mesh,
   820                            cell.midline,
   821                            log_sigma,
   822                            kernel_width,
   823                            min_overlap_ratio,
   824                            max_external_ratio,
   825                            phase_log_sigma,
   826                            phase_closing_level,
   827                            signal_closing_level,
   828                            max_shift_correction,
   829                        )
   830                    )
   831                except Exception as e:
   832                    self.shift_errors.append(
   833                        {
   834                            "cell_id": cell.cell_id,
   835                            "channel": channel,
   836                            "error_type": type(e).__name__,
   837                            "error": str(e),
   838                        }
   839                    )
   840                    cell.shifted_contour = None
   841                    cell.shifted_mesh = None
   842                    cell.shifted_midline = None
   843                if cell.shifted_contour is None:
   844                    failed_attempts += 1
   845        return (len(self.cells) - failed_attempts) / len(self.cells)
   846
   847
   848class Cell:
   849    """
   850    Class representing a single cell in an image.
   851
   852    This class represents a single cell within an image, characterized by its contour, mesh, and midline data. It is identified by a unique cell ID.
   853
   854    Attributes
   855    ----------
   856    discard : bool
   857        A flag to indicate whether the cell should be discarded during analysis.
   858
   859    contour : ndarray
   860        The contour data of the cell.
   861
   862    mesh : ndarray
   863        The mesh data (4xN).
   864
   865    midline : ndarray
   866        The midline data describing the cell's central axis (2xN).
   867
   868    cell_id : int
   869        A unique identifier for the cell.
   870
   871    x1, y1, x2, y2 : ndarray
   872        Arrays representing the coordinates of the cell's mesh.
   873
   874    profile_mesh : None
   875        Placeholder for profile mesh data.
   876
   877    object_contours : dict
   878        A dictionary to store detected subcellular object contours in different channels.
   879
   880    morphological_features : dict
   881        Dictionary to store morphological features of the cell.
   882
   883    phase_features : dict
   884        Dictionary to store phase contrast features of the cell.
   885
   886    objects_features : dict
   887        Dictionary to store features related to subcellular objects within the cell.
   888
   889    svm_features : dict
   890        Dictionary to store support vector machine (SVM) features.
   891
   892    profiling_features : dict
   893        Dictionary to store profiling features.
   894
   895    profiling_data : dict
   896        Dictionary to store data related to the profiling of the cell.
   897    """
   898
   899    def __init__(self, contour, mesh, midline, shape, cell_id):
   900
   901        self.discard = False
   902        self.contour = contour
   903        self.mesh = mesh
   904        self.midline = midline
   905        self.cell_id = cell_id
   906
   907        self.shifted_contour = None
   908        self.shifted_mesh = None
   909        self.shifted_midline = None
   910
   911        self.x1 = self.mesh[:, 0]
   912        self.y1 = self.mesh[:, 1]
   913        self.x2 = self.mesh[:, 2]
   914        self.y2 = self.mesh[:, 3]
   915
   916        self.profile_mesh = None
   917
   918        self.object_meshdata = {}
   919
   920        self.morphological_features = {}
   921        self.phase_features = {}
   922        self.objects_features = {}
   923        self.svm_features = {}
   924        self.profiling_features = {}
   925        self.signal_correlation_features = {}
   926        self.profiling_data = {}