Exemple #1
0
    def analyze_images_in_folder(self,
                                 folder,
                                 generate_zmax=False,
                                 show_result=True,
                                 save_mask=True,
                                 save_excel=True):
        """
        Given the folder, perform general analysis over the images in it.

        Parameters
        ----------
        folder : str
            Path to the folder.
        generate_zmax : bool, optional
            Whether to calcaulate the z-max projection first. The default is False.
        show_result : bool, optional
            If show the machine learning segmentation results. The default is True.
        save_mask : bool, optional
            DESCRIPTION. The default is True.
        save_excel : bool, optional
            DESCRIPTION. The default is True.

        Returns
        -------
        cell_Data : pd.dataframe
            DESCRIPTION.

        """
        flat_cell_counted_in_folder = 0
        total_cells_counted_in_folder = 0

        # If need to do zmax projection first
        if generate_zmax == True:
            ProcessImage.cam_screening_post_processing(folder)
            # Here a new folder for maxProjection is generated inside, change the path
            folder = os.path.join(folder, 'maxProjection')

        # If background images are taken
        if os.path.exists(os.path.join(folder, 'background')):
            # If the background image is taken to substract out
            background_substraction = True

            # Get all the background files names
            background_fileNameList = []
            for file in os.listdir(os.path.join(folder, 'background')):
                if "tif" in file:
                    background_fileNameList.append(
                        os.path.join(folder, 'background', file))

            background_image = ProcessImage.image_stack_calculation(
                background_fileNameList, operation="mean")

        # Get a list of file names
        fileNameList = []
        for file in os.listdir(folder):
            if "tif" in file and "LED" not in file:
                fileNameList.append(file)

        print(fileNameList)

        # Analyse each image
        for image_file_name in fileNameList:
            print(image_file_name)
            Rawimage = imread(os.path.join(folder, image_file_name))

            if background_substraction == True:
                Rawimage = np.abs(Rawimage - background_image)

            # Analyze each image
            # Run the detection on input image.
            MLresults = self.DetectionOnImage(Rawimage,
                                              axis=None,
                                              show_result=show_result)

            if save_mask == True:

                if not os.path.exists(os.path.join(folder, 'ML_masks')):
                    # If the folder is not there, create the folder
                    os.mkdir(os.path.join(folder, 'ML_masks'))

                fig, ax = plt.subplots()
                # Set class_names = [None,None,None,None] to mute class name display.
                visualize.display_instances(
                    Rawimage,
                    MLresults['rois'],
                    MLresults['masks'],
                    MLresults['class_ids'],
                    class_names=[None, None, None, None],
                    ax=ax,
                    centre_coors=MLresults['Centre_coor'],
                    Centre_coor_radius=2,
                    WhiteSpace=(
                        0, 0))  #MLresults['class_ids'],MLresults['scores'],
                # ax.imshow(fig)
                fig.tight_layout()
                # Save the detection Rawimage
                fig_name = os.path.join(
                    folder, 'ML_masks', 'ML_mask_{}.png'.format(
                        image_file_name[0:len(image_file_name) - 4]))
                plt.savefig(fname=fig_name,
                            dpi=200,
                            pad_inches=0.0,
                            bbox_inches='tight')

            if flat_cell_counted_in_folder == 0:
                cell_Data, flat_cell_counted_in_folder, total_cells_counted_in_coord = \
                    ProcessImage.retrieveDataFromML(Rawimage, MLresults, image_file_name, flat_cell_counted_in_folder)
            else:
                Cell_Data_new, flat_cell_counted_in_folder, total_cells_counted_in_coord = \
                    ProcessImage.retrieveDataFromML(Rawimage, MLresults, image_file_name, flat_cell_counted_in_folder)
                if len(Cell_Data_new) > 0:
                    cell_Data = cell_Data.append(Cell_Data_new)
            total_cells_counted_in_folder += total_cells_counted_in_coord

        if save_excel == True:
            # Save to excel
            cell_Data.to_excel(
                os.path.join(
                    folder, 'CellsProperties_{}flat_outof_{}cells.xlsx'.format(
                        flat_cell_counted_in_folder,
                        total_cells_counted_in_folder)))

        return cell_Data
Exemple #2
0
    def analyze_images_in_folder(
        self,
        folder,
        generate_zmax=False,
        show_result=True,
        save_mask=True,
        save_excel=True,
    ):
        """
        Given the folder, perform general analysis over the images in it.

        Parameters
        ----------
        folder : str
            Path to the folder.
        generate_zmax : bool, optional
            Whether to calcaulate the z-max projection first. The default is False.
        show_result : bool, optional
            If show the machine learning segmentation results. The default is True.
        save_mask : bool, optional
            DESCRIPTION. The default is True.
        save_excel : bool, optional
            DESCRIPTION. The default is True.

        Returns
        -------
        cell_Data : pd.dataframe
            DESCRIPTION.

        """
        flat_cell_counted_in_folder = 0
        total_cells_counted_in_folder = 0
        background_substraction = False
        root_folder = folder

        # If need to do zmax projection first
        if generate_zmax == True:
            ProcessImage.cam_screening_post_processing(root_folder)
            # Here a new folder for maxProjection is generated inside, change the path
            folder = os.path.join(root_folder, "maxProjection")

        # If background images are taken
        if os.path.exists(os.path.join(root_folder, "background")):
            # If the background image is taken to substract out
            background_substraction = True
            print("Run background substraction.")

            # Get all the background files names
            background_fileNameList = []
            for file in os.listdir(os.path.join(root_folder, "background")):
                if "calculated background" not in file:
                    if "tif" in file or "TIF" in file:
                        background_fileNameList.append(
                            os.path.join(root_folder, "background", file))

            # Average over multiple images
            background_image = ProcessImage.image_stack_calculation(
                background_fileNameList, operation="mean")

            # # Smooth the image
            # background_image = ProcessImage.average_filtering(
            #     background_image, filter_side_length = 25)

            # Save the individual file.
            with skimtiff.TiffWriter(
                    os.path.join(root_folder, "background",
                                 "calculated background.tif"),
                    imagej=True,
            ) as tif:
                tif.save(background_image.astype(np.uint16), compress=0)

        # Get a list of file names
        fileNameList = []
        for file in os.listdir(folder):
            if "tif" in file and "LED" not in file:
                fileNameList.append(file)

        print(fileNameList)

        # Analyse each image
        for image_file_name in fileNameList:
            print(image_file_name)
            Rawimage = imread(os.path.join(folder, image_file_name))

            if background_substraction == True:
                Rawimage = np.abs(Rawimage - background_image).astype(
                    np.uint16)

                camera_dark_level = 100

                # # Normalize to the illumination intensity
                # Rawimage = np.uint16(Rawimage \
                #         / ((background_image - camera_dark_level)\
                #            /(np.amin(background_image) - camera_dark_level)))

            # Analyze each image
            # Run the detection on input image.
            MLresults = self.DetectionOnImage(Rawimage,
                                              axis=None,
                                              show_result=show_result)

            if save_mask == True:

                if not os.path.exists(os.path.join(folder, "ML_masks")):
                    # If the folder is not there, create the folder
                    os.mkdir(os.path.join(folder, "ML_masks"))

                fig, ax = plt.subplots()
                # Set class_names = [None,None,None,None] to mute class name display.
                visualize.display_instances(
                    Rawimage,
                    MLresults["rois"],
                    MLresults["masks"],
                    MLresults["class_ids"],
                    class_names=[None, None, None, None],
                    ax=ax,
                    centre_coors=MLresults["Centre_coor"],
                    Centre_coor_radius=2,
                    WhiteSpace=(0, 0),
                )  # MLresults['class_ids'],MLresults['scores'],
                # ax.imshow(fig)
                fig.tight_layout()
                # Save the detection Rawimage
                fig_name = os.path.join(
                    folder,
                    "ML_masks",
                    "ML_mask_{}.png".format(
                        image_file_name[0:len(image_file_name) - 4]),
                )
                plt.savefig(fname=fig_name,
                            dpi=200,
                            pad_inches=0.0,
                            bbox_inches="tight")

            if flat_cell_counted_in_folder == 0:
                (
                    cell_Data,
                    flat_cell_counted_in_folder,
                    total_cells_counted_in_coord,
                ) = ProcessImage.retrieveDataFromML(
                    Rawimage, MLresults, image_file_name,
                    flat_cell_counted_in_folder)
            else:
                (
                    Cell_Data_new,
                    flat_cell_counted_in_folder,
                    total_cells_counted_in_coord,
                ) = ProcessImage.retrieveDataFromML(
                    Rawimage, MLresults, image_file_name,
                    flat_cell_counted_in_folder)
                if len(Cell_Data_new) > 0:
                    cell_Data = cell_Data.append(Cell_Data_new)
            total_cells_counted_in_folder += total_cells_counted_in_coord

        if save_excel == True:
            # Save to excel
            cell_Data.to_excel(
                os.path.join(
                    folder,
                    "CellsProperties_{}flat_outof_{}cells.xlsx".format(
                        flat_cell_counted_in_folder,
                        total_cells_counted_in_folder),
                ))

        return cell_Data