コード例 #1
0
    def detect_spots(self):
        # sigma
        sigma_z, sigma_xy, sigma_xy = detection.get_sigma(self.voxel_size_z,
                                                          self.voxel_size_xy,
                                                          self.psf_z, self.psf_xy)

        sigma = (sigma_z, sigma_xy, sigma_xy)

        # LoG filter
        rna_log = stack.log_filter(self.rna, sigma)

        # local maximum detection
        mask = detection.local_maximum_detection(rna_log, min_distance=sigma)

        # thresholding
        threshold = detection.automated_threshold_setting(rna_log, mask)
        spots, _ = detection.spots_thresholding(rna_log, mask, threshold)

        #note radius
        (radius_z, radius_xy, radius_xy) = detection.get_radius(self.voxel_size_z,
                                                                self.voxel_size_xy,
                                                                self.psf_z, self.psf_xy)
        self.sigma_z = sigma_z
        self.sigma_xy = sigma_xy
        self.radius_z = radius_z
        self.radius_xy = radius_xy
        self.threshold = threshold
        self.spots = spots
        plot.plot_detection(self.rna_mip, self.spots, radius=self.radius_xy,
                            framesize=(10, 8), contrast=True, show=False,
                            path_output=f'{self.plotdir}/{self.fov_name}spots',
                            ext='png')
コード例 #2
0
    def detect_spots(self, showplot=False):
        # sigma
        sigma_z, sigma_yx, sigma_yx = detection.get_sigma(
            self.voxel_size_z, self.voxel_size_yx, self.psf_z, self.psf_yx)

        sigma = (sigma_z, sigma_yx, sigma_yx)

        # LoG filter
        rna_log = stack.log_filter(self.rna, sigma)

        # local maximum detection
        mask = detection.local_maximum_detection(rna_log, min_distance=sigma)

        if self.manual_threshold is not None:
            spots, _ = detection.spots_thresholding(rna_log, mask,
                                                    self.manual_threshold)
            self.threshold = self.manual_threshold
            self.threshold_type = 'manual'

        else:
            # thresholding
            threshold = detection.automated_threshold_setting(rna_log, mask)
            spots, _ = detection.spots_thresholding(rna_log, mask, threshold)
            self.threshold = threshold
            self.threshold_type = 'auto'

        #note radius
        (radius_z, radius_yx,
         radius_yx) = detection.get_radius(self.voxel_size_z,
                                           self.voxel_size_yx, self.psf_z,
                                           self.psf_yx)
        self.sigma_z = sigma_z
        self.sigma_yx = sigma_yx
        self.radius_z = radius_z
        self.radius_yx = radius_yx
        self.rna_log = rna_log
        self.mask = mask
        self.spots = spots
        if showplot:
            plot.plot_detection(
                self.rna_mip,
                self.spots,
                radius=self.radius_yx,
                framesize=(10, 8),
                contrast=True,
                show=self.show,
                path_output=f'{self.plotdir}/{self.fov_name}spots',
                ext='png')
コード例 #3
0
    # start analysis
    experience = get_metadata_directory(experience_directory)
    filename_base = generate_filename_base(experience)
    generator = images_generator(base_directory, experience_directory)

    nb_images = 0
    for i, image in enumerate(generator):
        filename = filename_base + "_" + str(i)
        print("\t", image.shape, image.dtype, filename)

        # cyt
        cyt = image[0, 1, :, :, :]

        # get sigma
        sigma_z, sigma_yx = detection.get_sigma(resolution_z=300,
                                                resolution_yx=103,
                                                psf_z=350, psf_yx=150)
        sigma_log = (sigma_z, sigma_yx, sigma_yx)
        sigma_background = (sigma_z*5, sigma_yx*5, sigma_yx*5)

        # LoG filter
        cyt_filtered_log = stack.log_filter(cyt, sigma_log, keep_dtype=True)
        path = os.path.join(output_directory_log, filename + ".tiff")
        stack.save_image(cyt_filtered_log, path)

        # background filter
        cyt_filtered_background = stack.remove_background_gaussian(
            image=cyt, sigma=sigma_background)
        path = os.path.join(output_directory_background, filename + ".tiff")
        stack.save_image(cyt_filtered_background, path)
コード例 #4
0
def image_processing_function(image_loc, config):
    # Read the image into a numpy array of format ZCYX
    if isinstance(image_loc, str):
        image_name = pathlib.Path(image_loc).stem
        image = tifffile.imread(image_loc)
    else:
        # Establish connection with OMERO and actually connect
        conn = omero.gateway.BlitzGateway(
            host="omero1.bioch.ox.ac.uk",
            port=4064,
            # group=config["OMERO_group"],
            username=config["OMERO_user"],
            passwd=config["password"],
        )
        conn.connect()
        conn.SERVICE_OPTS.setOmeroGroup(-1)
        # Create a thread to keep the connection alive
        ka_thread = threading.Thread(target=keep_connection_alive,
                                     args=(conn, ))
        ka_thread.daemon = True
        ka_thread.start()
        # Derive image and its name
        image_name = pathlib.Path(image_loc[0]).stem
        remote_image = conn.getObject("Image", image_loc[1])
        image = np.array(
            list(remote_image.getPrimaryPixels().getPlanes([
                (z, c, 0) for z in range(0, remote_image.getSizeZ())
                for c in range(0, remote_image.getSizeC())
            ])))
        image = image.reshape(
            image.shape[0] // remote_image.getSizeC(),
            remote_image.getSizeC(),
            image.shape[1],
            image.shape[2],
        )

    # segment with cellpose
    seg_img = np.max(image[:, config["seg_ch"], :, :], 0)
    if config["cp_search_string"] in image_name:
        seg_img = np.clip(seg_img, 0, config["cp_clip"])
    seg_img = scipy.ndimage.median_filter(seg_img,
                                          size=config["median_filter"])
    model = models.Cellpose(gpu=config["gpu"], model_type="cyto")
    channels = [0, 0]  # greyscale segmentation
    masks = model.eval(
        seg_img,
        channels=channels,
        diameter=config["diameter"],
        do_3D=config["do_3D"],
        flow_threshold=config["flow_threshold"],
        cellprob_threshold=config["cellprob_threshold"],
    )[0]

    # Calculate PSF
    psf_z, psf_yx = calculate_psf(
        config["voxel_size_z"],
        config["voxel_size_yx"],
        config["ex"],
        config["em"],
        config["NA"],
        config["RI"],
        config["microscope"],
    )
    sigma = detection.get_sigma(config["voxel_size_z"],
                                config["voxel_size_yx"], psf_z, psf_yx)

    for image_channel in config["channels"]:
        # detect spots
        rna = image[:, image_channel, :, :]
        # subtract background
        rna_no_bg = []
        for z in rna:
            z_no_bg = subtract_background(z, config["bg_radius"])
            rna_no_bg.append(z_no_bg)
        rna = np.array(rna_no_bg)

        # LoG filter
        rna_log = stack.log_filter(rna, sigma)

        # local maximum detection
        mask = detection.local_maximum_detection(rna_log, min_distance=sigma)

        # tresholding
        if image_channel == config["smFISH_ch1"]:
            threshold = config["smFISH_ch1_thresh"]
        elif image_channel == config["smFISH_ch2"]:
            threshold = config["smFISH_ch2_thresh"]
        else:
            print("smFISH channel and threshold not correctly defined!")

        spots, _ = detection.spots_thresholding(rna_log, mask, threshold)

        # detect and decompose clusters
        spots_post_decomposition = detection.decompose_cluster(
            rna,
            spots,
            config["voxel_size_z"],
            config["voxel_size_yx"],
            psf_z,
            psf_yx,
            alpha=config["alpha"],  # impacts number of spots per cluster
            beta=config["beta"],  # impacts the number of detected clusters
        )[0]

        # separate spots from clusters
        spots_post_clustering, foci = detection.detect_foci(
            spots_post_decomposition,
            config["voxel_size_z"],
            config["voxel_size_yx"],
            config["bf_radius"],
            config["nb_min_spots"],
        )

        # extract cell level results
        image_contrasted = stack.rescale(rna, channel_to_stretch=0)
        image_contrasted = stack.maximum_projection(image_contrasted)
        rna_mip = stack.maximum_projection(rna)

        fov_results = stack.extract_cell(
            cell_label=masks.astype(np.int64),
            ndim=3,
            rna_coord=spots_post_clustering,
            others_coord={"foci": foci},
            image=image_contrasted,
            others_image={"smfish": rna_mip},
        )

        # save bigfish results
        for i, cell_results in enumerate(fov_results):
            output_path = pathlib.Path(config["output_dir"]).joinpath(
                f"{image_name}_ch{image_channel + 1}_results_cell_{i}.npz")
            stack.save_cell_extracted(cell_results, str(output_path))

        # save reference spot for each image
        # (Using undenoised image! not from denoised!)
        reference_spot_undenoised = detection.build_reference_spot(
            rna,
            spots,
            config["voxel_size_z"],
            config["voxel_size_yx"],
            psf_z,
            psf_yx,
            alpha=config["alpha"],
        )
        spot_output_path = pathlib.Path(config["output_refspot_dir"]).joinpath(
            f"{image_name}_reference_spot_ch{image_channel + 1}")
        stack.save_image(reference_spot_undenoised, str(spot_output_path),
                         "tif")

    # Close the OMERO connection
    conn.close()