示例#1
0
    def __init__(self, inter_flag_parallel_active=True):
        """
        Efficient Python implementation of Radial Variance Transform.

        The main function is :func:`rvt` in the bottom of the file, which applies the transform to a single image (2D numpy array).


        Compared to the vanilla convolution implementation, there are two speed-ups:
        1) Pre-calculating and caching kernel FFT; this way so only one inverse FFT is calculated per convolution + one direct fft of the image is used for all convolutions
        2) When finding MoV, calculate ``np.mean(rsqmeans)`` in a single convolution by averaging all kernels first

        Parameters
        ----------
        inter_flag_parallel_active: bool
            In case the user wants to active general parallel tasks in CPU configuration,
            the user can only active or deactivate this method by this flag.

        References
        ----------
        [1] Kashkanova, Anna D., et al. "Precision single-particle localization using radial variance transform." Optics Express 29.7 (2021): 11070-11083.
        """
        self.cpu = CPUConfigurations()
        self._kernels_fft_cache = {}
        self.video = None
        self.inter_flag_parallel_active = inter_flag_parallel_active
示例#2
0
    def __init__(self, video, select_correction_axis, flag_GUI=False):
        """
        This class uses a heuristic procedure called Median Projection FPN (mFPN) to reduce fixed pattern noise (FPN).

        References
        ----------
        [1] Mirzaalian Dastjerdi, Houman, et al. "Optimized analysis for sensitive detection and analysis of single
        proteins via interferometric scattering microscopy." Journal of Physics D: Applied Physics (2021).
        (http://iopscience.iop.org/article/10.1088/1361-6463/ac2f68)

        Parameters
        ----------
        video: NDArray
            The video is 3D-numpy (number of frames, width, height).

        select_correction_axis: int (0/1)
            * `0`: FPN will be applied row-wise.
            * `1`: FPN will be applied column-wise.
        """

        super(MedianProjectionFPNc, self).__init__()
        self.cpu = CPUConfigurations()
        self.video = video
        self.select_correction_axis = select_correction_axis
        self.flag_GUI = flag_GUI
        self.threadpool = QThreadPool()
        self.signals = WorkerSignals()
示例#3
0
    def __init__(self, video, inter_flag_parallel_active=True):
        """
        This class corrects FPN using two well-known frequency domain techniques from the literature.

        References
        ----------
        [1] Cao, Yanlong, et al. "A multi-scale non-uniformity correction method based on wavelet decomposition and
        guided filtering for uncooled long wave infrared camera." Signal Processing: Image Communication 60 (2018): 13-21.

        [2] Zeng, Qingjie, et al. "Single infrared image-based stripe non-uniformity correction via a two-stage
        filtering method." Sensors 18.12 (2018): 4299.

        Parameters
        ----------
        video: NDArray
            The video is 3D-numpy (number of frames, width, height).

        inter_flag_parallel_active: bool
            If the user wants to enable generic parallel tasks in CPU configuration, this flag is used to disable parallel execution of this function.
        """
        super(FrequencyFPNc, self).__init__()
        self.cpu = CPUConfigurations()
        self.inter_flag_parallel_active = inter_flag_parallel_active

        self.coeffs = None
        self.arr = None
        self.coeff_slices = None
        self.video_out = None
        self.im_fft_noiseless = None
        self.im_fft_noise = None
        self.im_recon = None
        self.coeffs_result = None
        self.print_color = PrintColors()
        self.video = video
示例#4
0
    def __init__(self,
                 video,
                 flag_pn=False,
                 flag_global=False,
                 flag_image_specific=False):
        """
        This class contains a different version of video/image normalization methods.

        Parameters
        ----------
        video: NDArray
            It is Numpy 3D video array.

        optional_1: GUI
            * `flag_pn`: bool
                If it is True, the power_normalized method is applied on input video on GUI.

            * `flag_global`: bool
                If it is True, the normalized_image_global method is applied on input video on GUI.

            * `flag_image_specific`: bool
                If it is True, the normalized_image_specific method is applied on input video on GUI.

        """
        super(Normalization, self).__init__()
        self.cpu = CPUConfigurations()

        self.video = video
        self.roi_x = None
        self.roi_y = None
        self.signals = WorkerSignals()

        self.flag_pn = flag_pn
        self.flag_global = flag_global
        self.flag_image_specific = flag_image_specific
示例#5
0
    def __init__(self, video, mask, inter_flag_parallel_active=True):
        """
        This class produces a masked version of the input video.

        Parameters
        ----------
        video: NDArray
            The video is 3D-numpy (number of frames, width, height).

        mask: NDArray
            The mask is 2D-numpy with binary values and the same dimension as the input video.

         internal_parallel_flag: bool
            Internal flag for activating parallel computation. Default is True!
        """
        
        self.video = video
        self.cpu = CPUConfigurations()
        self.inter_flag_parallel_active = inter_flag_parallel_active
        if mask is not None:
            if mask.ndim == 2:
                print('--- Same mask is used for all frame! ---')
                self.mask_repeater(mask)

            elif video.shape == mask.shape:
                print('--- Mask has same shape with video! ---')
                self.mask = mask
            else:
                print('--- Mask does not have same shape with video! ---')
        else:
            print('--- Mask is not define! ---')
 def __init__(self):
     """
     We have a `SpatialFilter` class in PiSCAT that allows users to filter `outlier_frames`
     that have a strong vibration or a particle flying by, `dense_PSFs`, and non-symmetric PSFs that
     may not properly resemble the iPSF expected from the experimental setup.
     The threshold parameter in each of these filters determines the filter's sensitivity.
     """
     self.cpu = CPUConfigurations()
    def __init__(self, video, flag_transform=False, flag_GUI=False, **kwargs):

        """
        This class employs a variety of PSF localization methods, including DoG/LoG/DoH/RS/RVT.

        It returns a list containing the following details:

        [[frame number, center y, center x, sigma], [frame number, center y, center x, sigma], ...]

                Parameters
                ----------
        video: NDArray
            Numpy 3D video array.

        flag_transform: bool
            In case it is defined as true, the input video is already transformed.
            So it does not need to run this task during localization.

        flag_GUI: bool
            While the GUI is calling this class, it is true.
        """
        super(PSFsExtraction, self).__init__()
        self.cpu = CPUConfigurations()
        self.kwargs = kwargs
        self.counter = 0

        self.flag_GUI = flag_GUI

        self.video = video
        self.flag_transform = flag_transform
        self.norm_vid = None

        self.psf_dog = None
        self.psf_doh = None
        self.psf_log = None
        self.psf_hog = None
        self.psf_frst = None

        self.psf_hog_1D_feature = None

        self.min_sigma = None
        self.max_sigma = None
        self.sigma_ratio = None
        self.threshold = None
        self.overlap = None
        self.radii = None
        self.alpha = None
        self.beta = None
        self.stdFactor = None
        self.mode = None
        self.function = None

        self.df_PSF = None
示例#8
0
    def __init__(self, path, file_format, width_size, height_size, image_type,
                 reader_type):
        """
        This class reads images of a particular kind from a folder and concatenates them into a single NumPy array.

        Parameters
        ----------
        path: str
            The directory path that includes images.

        file_format: str
            Postfix of image names.

        width_size: int
            For binary images, it specifies the image width.

        height_size: int
            For binary images, it specifies the image height.

        image_type: str

            * "i"  (signed) integer, "u" unsigned integer, "f" floating-point.
            * "<" active little-endian.
            * "1" 8-bit, "2" 16-bit, "4" 32-bit, "8" 64-bit.

        reader_type: str
            Specify the video/image format to be loaded.

            * `'binary'`: use this flag to load binary
            * `'tif'`: use this flag to load tif
            * `'avi`': use this flag to load avi
            * `'png'`: use this flag to load png
        """
        self.cpu = CPUConfigurations()

        self.reader_type = reader_type

        self.path = os.path.join(path, file_format)
        self.width_size = width_size
        self.height_size = height_size
        self.type = image_type

        self.path_list = glob(self.path)
        self.img_bin = []
        temp = Parallel(n_jobs=self.cpu.n_jobs,
                        backend=self.cpu.backend,
                        verbose=self.cpu.verbose)(
                            delayed(self.parallel_read_img)(x)
                            for x in tqdm(self.path_list))
        self.video = np.asarray(temp)
示例#9
0
    def save_CPU_setting(self):
        if self.cpu_setting.parallel_active is True:

            setting_dic = {'n_jobs': [self.cpu_setting.n_jobs], 'backend': [self.cpu_setting.backend], 'verbose': [self.cpu_setting.verbose],
                           'parallel_active': [self.cpu_setting.parallel_active],
                           'threshold_for_parallel_run': [self.cpu_setting.threshold_for_parallel_run]}

            cpu_setting = CPUConfigurations()
            cpu_setting.save_cpu_setting(setting_dic)
        else:
            setting_dic = {'n_jobs': [1], 'backend': ['None'],
                           'verbose': [0],
                           'parallel_active': [self.cpu_setting.parallel_active],
                           'threshold_for_parallel_run': [None]}
            cpu_setting = CPUConfigurations()
            cpu_setting.save_cpu_setting(setting_dic)
        print("Done!")
    def __init__(self):
        """
        The RadialCenter localization algorithm is implemented in Python. 

        References
        ----------
        Parthasarathy, R. Rapid, accurate particle tracking by calculation of radial symmetry centers. Nat Methods 9, 724–726 (2012).
        https://doi.org/10.1038/nmeth.2071
        """

        self.cpu = CPUConfigurations()

        self.patch_gen = None
        self.patch = None
        self.video_shape = None
        self.probility_map = None
示例#11
0
    def __init__(self,
                 video,
                 df_PSFs,
                 time_delay=0.1,
                 GUI_progressbar=False,
                 *args,
                 **kwargs):
        """
        This class displays video while highlighting PSFs.

        Parameters
        ----------
        video: NDArray
            Input video.

        df_PSFs: panda data_frame
            Data Frames that contains the location of PSFs.

        time_delay: float
            Delay between frames in milliseconds.

        GUI_progressbar: bool
            This actives GUI progress bar

        """
        self.cpu = CPUConfigurations()
        super(DisplayDataFramePSFsLocalization, self).__init__()

        self.video = video
        self.time_delay = time_delay
        self.df_PSFs = df_PSFs
        self.pressed_key = {}
        self.list_line = []
        if 'particle' in self.df_PSFs.keys():
            self.list_particles_idx = self.df_PSFs.particle.unique()

        else:
            self.df_PSFs['particle'] = 0
            self.list_particles_idx = self.df_PSFs.particle.unique()

        self.GUI_progressbar = GUI_progressbar
        self.args = args
        self.kwargs = kwargs

        colors_ = cm.autumn(np.linspace(0, 1, len(self.list_particles_idx)))
        self.colors = colors_[0:len(self.list_particles_idx), :]
        self.obj_connection = SignalConnection()
示例#12
0
    def __init__(self, video, inter_flag_parallel_active=True):
        """
        This class generates a list of video/image filters.
        To improve performance on large video files, some of them have a parallel implementation.

        Parameters
        ----------
        video: NDArray
            The video is 3D-numpy (number of frames, width, height).

        inter_flag_parallel_active: bool
            If the user wants to enable general parallel tasks in the CPU configuration, he or she can only use this flag to enable or disable this process.
        """
        self.cpu = CPUConfigurations()
        self.inter_flag_parallel_active = inter_flag_parallel_active

        self.video = video
        self.filtered_video = None
示例#13
0
    def __init__(self, video, select_correction_axis, flag_GUI=False):
        """
        This class uses a heuristic procedure called Column Projection FPN (cpFPN) to reduce fixed pattern noise (FPN).

        Parameters
        ----------
        video: NDArray
            The video is 3D-numpy (number of frames, width, height).

        select_correction_axis: int (0/1)
            * `0`: FPN will be applied row-wise.
            * `1`: FPN will be applied column-wise.
        """
        super(ColumnProjectionFPNc, self).__init__()
        self.cpu = CPUConfigurations()
        self.video = video
        self.select_correction_axis = select_correction_axis
        self.flag_GUI = flag_GUI
        self.threadpool = QThreadPool()
        self.signals = WorkerSignals()
示例#14
0
    def __init__(self,
                 video=None,
                 batchSize=500,
                 flag_GUI=False,
                 object_update_progressBar=None,
                 mode_FPN='mFPN',
                 FPN_flag_GUI=False,
                 gui_select_correction_axis=1):
        """
        Differential Rolling Average (DRA).

        Parameters
        ----------
        video: NDArray
            The video is 3D-numpy (number of frames, width, height).

        batchSize: int
            The number of frames in each batch.

        mode_FPN: {‘cpFPN’, ‘mFPN’, ‘wFPN’, 'fFPN'}, optional
            Flag that defines method of FPNc.

                    * `mFPN`: Median fixed pattern noise correction
                    * `cpFPN`: Median fixed pattern noise correction
                    * `wFPN`: Wavelet FPNc
                    * `fFPN`: FFT2D_Wavelet FPNc

        optional_1: GUI
            These flags are used when GUI calls this method.

            * `flag_GUI`: bool
                This flag is defined as True when GUI calls this method.

            * `FPN_flag_GUI`: bool
                This flag is defined as True when GUI calls this method while we want activate FPNc.

            * `gui_select_correction_axis`: int (0/1), 'Both'
                This parameter is used only when FPN_flag_GUI is True, otherwise it will be ignored.

            * `object_update_progressBar`: object
                Object that updates the progress bar in GUI.
        """
        super(DifferentialRollingAverage, self).__init__()

        self.cpu = CPUConfigurations()

        self.flag_GUI = flag_GUI
        self.mode_FPN = mode_FPN
        self.FPN_flag_run = FPN_flag_GUI
        self.DRA_flag_run = True
        self.select_correction_axis_run = gui_select_correction_axis

        self.size_A_diff = (video.shape[0] - 2 * batchSize, video.shape[1],
                            video.shape[2])

        self.video = video.astype(np.float64)
        self.batchSize = batchSize

        self.moving_avg = np.empty_like(self.video)
        self.output_diff = np.empty(self.size_A_diff)

        self.output_batch_1 = np.empty(self.size_A_diff)
        self.fft_output_len = self.video.shape[0] - self.batchSize

        self.FPNc_video = None
        self.flag_thread_FPNc = True
        self.object_update_progressBar = object_update_progressBar
        self.threadpool = QThreadPool()
        self.signals = WorkerSignals()
示例#15
0
    def __init__(self, video, list_range, FPN_flag=False, mode_FPN='mFPN', select_correction_axis=1, n_jobs=None,
                 inter_flag_parallel_active=False, max_iterations=10, FFT_widith=1, mode='mode_temporal'):
        """
        This class measures the noise floor for various batch sizes.

        Parameters
        ----------
        video: NDArray
            The video is 3D-numpy (number of frames, width, height).

        list_range: list
            list os all batch size that DRA should be calculated for them.

        FPN_flag: bool
            This flag activates the fixed pattern noise correction function in case define as true.

        mode_FPN: {‘cpFPN’, ‘mFPN’, ‘wFPN’, 'fFPN'}, optional
            Flag that defines method of FPNc.

            * `mFPN`: Median fixed pattern noise correction
            * `cpFPN`: Median fixed pattern noise correction
            * `wFPN`: Wavelet FPNc
            * `fFPN`: FFT2D_Wavelet FPNc

        select_correction_axis: int (0/1), 'Both'
            This parameter is used only when FPN_flag is True, otherwise it will be ignored.

            * `0`: FPN will be applied row-wise.
            * `1`: FPN will be applied column-wise.
            * `'Both'`: FPN will be applied on two axis.

        max_iterations: int
            This parameter is used when fFPT is selected that defines the total number of filtering iterations.

        FFT_widith: int
            This parameter is used when fFPT is selected that defines the frequency mask's width.
        """

        CPUConfigurations.__init__(self)
        PrintColors.__init__(self)

        self.video = video
        self.max_iterations = max_iterations
        self.FFT_widith = FFT_widith
        self.FPN_flag = FPN_flag
        self.select_correction_axis = select_correction_axis
        self.inter_flag_parallel_active = inter_flag_parallel_active
        self.mode_FPN = mode_FPN
        self.thr_shot_noise = None
        self.list_range = list_range
        if self.parallel_active and self.inter_flag_parallel_active:
            if n_jobs is not None:
                self.n_jobs = n_jobs
                print("\nThe number of usage CPU cores are {}!".format(n_jobs))

            self.mean = Parallel(n_jobs=self.n_jobs, backend=self.backend, verbose=0)(delayed(self.best_radius_kernel)(i_, flag_parallel=True, mode=mode) for i_ in range(len(self.list_range)))
        else:
            print(f"{self.WARNING}\nThe noise floor is running without parallel loop!{self.ENDC}")

            self.mean = []
            for i_ in range(len(self.list_range)):
                self.mean.append(self.best_radius_kernel(i_, flag_parallel=True, mode=mode))