Esempio n. 1
0
def preprocess_img(image5d, preprocs, channel, out_path):
    """Pre-process an image in 3D.

    Args:
        image5d (:obj:`np.ndarray`): 5D array in t,z,y,x[,c].
        preprocs (List[:obj:`profiles.PreProcessKeys`): Sequence of
            pre-processing tasks to perform in the order given.
        channel (int): Channel to preprocess, or None for all channels.
        out_path (str): Output base path.

    Returns:
        :obj:`np.ndarray`: The pre-processed image array.

    """
    if preprocs is None:
        print("No preprocessing tasks to perform, skipping")
        return

    roi = image5d[0]
    for preproc in preprocs:
        # perform global pre-processing task
        print("Pre-processing task:", preproc)
        if preproc is profiles.PreProcessKeys.SATURATE:
            roi = plot_3d.saturate_roi(roi, channel=channel)
        elif preproc is profiles.PreProcessKeys.DENOISE:
            roi = plot_3d.denoise_roi(roi, channel)
        elif preproc is profiles.PreProcessKeys.REMAP:
            roi = plot_3d.remap_intensity(roi, channel)
        elif preproc is profiles.PreProcessKeys.ROTATE:
            roi = rotate_img(roi)

    # save to new file
    image5d = importer.roi_to_image5d(roi)
    importer.save_np_image(image5d, out_path)
    return image5d
Esempio n. 2
0
def preprocess_img(image5d, preprocs, channel, out_path):
    """Pre-process an image in 3D.

    Args:
        image5d (:obj:`np.ndarray`): 5D array in t,z,y,x[,c].
        preprocs (Union[str, list[str]]): Pre-processing tasks that will be
            converted to enums in :class:`config.PreProcessKeys` to perform
            in the order given.
        channel (int): Channel to preprocess, or None for all channels.
        out_path (str): Output base path.

    Returns:
        :obj:`np.ndarray`: The pre-processed image array.

    """
    if preprocs is None:
        print("No preprocessing tasks to perform, skipping")
        return
    if not libmag.is_seq(preprocs):
        preprocs = [preprocs]

    roi = image5d[0]
    for preproc in preprocs:
        # perform global pre-processing task
        task = libmag.get_enum(preproc, config.PreProcessKeys)
        _logger.info("Pre-processing task: %s", task)
        if task is config.PreProcessKeys.SATURATE:
            roi = plot_3d.saturate_roi(roi, channel=channel)
        elif task is config.PreProcessKeys.DENOISE:
            roi = plot_3d.denoise_roi(roi, channel)
        elif task is config.PreProcessKeys.REMAP:
            roi = plot_3d.remap_intensity(roi, channel)
        elif task is config.PreProcessKeys.ROTATE:
            roi = rotate_img(roi)
        else:
            _logger.warn("No preprocessing task found for: %s", preproc)

    # save to new file
    image5d = importer.roi_to_image5d(roi)
    importer.save_np_image(image5d, out_path)
    return image5d
Esempio n. 3
0
    def detect_sub_roi(cls, coord, offset, last_coord, denoise_max_shape,
                       exclude_border, sub_roi, channel, img_path=None,
                       coloc=False):
        """Perform 3D blob detection within a sub-ROI without accessing
        class attributes, such as for spawned multiprocessing.
        
        Args:
            coord (Tuple[int]): Coordinate of the sub-ROI in the order z,y,x.
            offset (Tuple[int]): Offset of the sub-ROI within the full ROI,
                in z,y,x.
            last_coord (:obj:`np.ndarray`): See attributes.
            denoise_max_shape (Tuple[int]): See attributes.
            exclude_border (bool): See attributes.
            sub_roi (:obj:`np.ndarray`): Array in which to perform detections.
            img_path (str): Path from which to load metadatat; defaults to None.
                If given, the command line arguments will be reloaded to
                set up the image and processing parameters.
            coloc (bool): True to perform blob co-localizations; defaults
                to False.
            channel (Sequence[int]): Sequence of channels, where None detects
                in all channels.
        
        Returns:
            Tuple[int], :obj:`np.ndarray`: The coordinate given back again to
            identify the sub-ROI position and an array of detected blobs.

        """
        if img_path:
            # reload command-line parameters and image metadata, which is
            # required if run from a spawned (not forked) process
            cli.process_cli_args()
            _, orig_info = importer.make_filenames(img_path)
            importer.load_metadata(orig_info)
        print("detecting blobs in sub-ROI at {} of {}, offset {}, shape {}..."
              .format(coord, last_coord, tuple(offset.astype(int)),
                      sub_roi.shape))
        
        if denoise_max_shape is not None:
            # further split sub-ROI for preprocessing locally
            denoise_roi_slices, _ = chunking.stack_splitter(
                sub_roi.shape, denoise_max_shape)
            for z in range(denoise_roi_slices.shape[0]):
                for y in range(denoise_roi_slices.shape[1]):
                    for x in range(denoise_roi_slices.shape[2]):
                        denoise_coord = (z, y, x)
                        denoise_roi = sub_roi[denoise_roi_slices[denoise_coord]]
                        _logger.debug(
                            f"preprocessing sub-sub-ROI {denoise_coord} of "
                            f"{np.subtract(denoise_roi_slices.shape, 1)} "
                            f"(shape {denoise_roi.shape} within sub-ROI shape "
                            f"{sub_roi.shape})")
                        denoise_roi = plot_3d.saturate_roi(
                            denoise_roi, channel=channel)
                        denoise_roi = plot_3d.denoise_roi(
                            denoise_roi, channel=channel)
                        # replace slices with denoised ROI
                        denoise_roi_slices[denoise_coord] = denoise_roi
            
            # re-merge back into the sub-ROI
            merged_shape = chunking.get_split_stack_total_shape(
                denoise_roi_slices)
            merged = np.zeros(
                tuple(merged_shape), dtype=denoise_roi_slices[0, 0, 0].dtype)
            chunking.merge_split_stack2(denoise_roi_slices, None, 0, merged)
            sub_roi = merged
        
        if exclude_border is None:
            exclude = None
        else:
            exclude = np.array([exclude_border, exclude_border])
            exclude[0, np.equal(coord, 0)] = 0
            exclude[1, np.equal(coord, last_coord)] = 0
        segments = detector.detect_blobs(sub_roi, channel, exclude)
        if coloc and segments is not None:
            # co-localize blobs and append to blobs array
            colocs = colocalizer.colocalize_blobs(sub_roi, segments)
            segments = np.hstack((segments, colocs))
        #print("segs before (offset: {}):\n{}".format(offset, segments))
        if segments is not None:
            # shift both coordinate sets (at beginning and end of array) to 
            # absolute positioning, using the latter set to store shifted 
            # coordinates based on duplicates and the former for initial 
            # positions to check for multiple duplicates
            detector.shift_blob_rel_coords(segments, offset)
            detector.shift_blob_abs_coords(segments, offset)
            #print("segs after:\n{}".format(segments))
        return coord, segments