### Install PartSeg with pip Source: https://github.com/4dnucleome/partseg/blob/develop/Readme.md Install PartSeg from PyPI or directly from the GitHub repository using pip. The first command installs the package with all extras; the second installs the latest development version from the repository. ```bash pip install PartSeg[all] ``` ```bash pip install git+https://github.com/4DNucleome/PartSeg.git ``` -------------------------------- ### Install PartSeg and Download Neuron Types Data Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Installs the PartSeg package and downloads the neuron types training data from the web via urllib. Then extracts the data from a zip file into the current directory. The execution flow is first the installation, then the data download. ```Python # install PartSeg from PartSegCore.roi_info import ROIInfo !pip install PartSeg # download data import urllib.request import zipfile zip_file_path, _ = urllib.request.urlretrieve("https://bokota.pl/typy_neuronow2.zip") with open(zip_file_path, "rb") as ff: z_file = zipfile.ZipFile(ff) z_file.extractall() ``` -------------------------------- ### Setup PartSeg Analysis Environment Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Imports necessary libraries for the analysis: numerical computing (numpy), image processing (SimpleITK), plotting (matplotlib), and PartSeg modules for loading analysis metadata, algorithm selections, measurements, convex fill, mask metadata and I/O functions. Includes commented placeholder for PartSeg plugins registration. ```Python import os from collections import defaultdict from glob import glob from math import pi import numpy as np import SimpleITK as sitk from matplotlib import pyplot as plt from PartSegCore.analysis import load_metadata as load_analysis_metadata from PartSegCore.analysis.algorithm_description import AnalysisAlgorithmSelection from PartSegCore.analysis.measurement_calculation import Diameter, Volume from PartSegCore.convex_fill import convex_fill from PartSegCore.mask import load_metadata as load_mask_metadata from PartSegCore.mask.algorithm_description import MaskAlgorithmSelection from PartSegCore.mask.io_functions import load_stack_segmentation, save_components from PartSegCore.segmentation.segmentation_algorithm import ThresholdAlgorithm from PartSegCore.universal_const import Units from PartSegImage.image import Image from PartSegImage.image_reader import TiffImageReader # import PartSeg.plugins # PartSeg.plugins.register() # Load PartSeg plugins ``` -------------------------------- ### Setup measurement with load_analysis_metadata Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Loads measurement configuration from a JSON file and prints its string representation. Use when setting up measurement for neuron types. The loaded object is used later to calculate measurements. ```python neuron_measurment_description = load_analysis_metadata(os.path.join(data_path, "neuron_types_measurment.json")) print(str(neuron_measurment_description["neuron_types"])) measurment_object = neuron_measurment_description["neuron_types"] ``` -------------------------------- ### Install PartSeg with conda or mamba Source: https://github.com/4dnucleome/partseg/blob/develop/Readme.md Install PartSeg from conda-forge using either conda or mamba. Mamba is noted as faster than conda. ```bash conda install -c conda-forge partseg ``` ```bash mamba install -c conda-forge partseg ``` -------------------------------- ### Setup neuron segmentation algorithm with load_analysis_metadata Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Loads neuron segmentation parameters from a JSON file and initializes the segmentation algorithm. Use when setting up neuron type segmentation inside a larger algorithm. Requires the PartSegCore analysis metadata loader and the AnalysisAlgorithmSelection registry. ```python neuron_segmentation_description = load_analysis_metadata(os.path.join(data_path, "neuron_types_segmentation.json")) neuron_segmentation_profile = neuron_segmentation_description["neuron_types"] NeuronAlgoritm = AnalysisAlgorithmSelection[neuron_segmentation_profile.algorithm] neuron_segment = NeuronAlgoritm() neuron_segment.set_parameters(neuron_segmentation_profile.values) ``` -------------------------------- ### Error message when building PyOpenGL-accelerate without developer tools Source: https://github.com/4dnucleome/partseg/wiki/Instalation-troubleshoot This error appears during installation when Microsoft C++ Build Tools are missing. It indicates that the PyOpenGL-accelerate wheel is not available for Python 3.9 and the build fails. Install the build tools or use a pre-built wheel to resolve. ```text building 'OpenGL_accelerate.wrapper' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ---------------------------------------- ERROR: Failed building wheel for PyOpenGL-accelerate ``` -------------------------------- ### Create segmentation algorithm and set parameters Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Create a segmentation algorithm instance either directly (ThresholdAlgorithm) or by selecting from MaskAlgorithmSelection based on the loaded metadata. Set the image and then choose one of the parameter sets (parameters1 or parameters2) to use. ```python segment = ThresholdAlgorithm() segment.set_image(image) # Choose on of this line segment.set_parameters(parameters1) segment.set_parameters(parameters2) ``` ```python # or Algorithm = MaskAlgorithmSelection[segmentation_description.algorithm] segment = Algorithm() segment.set_image(image) # Choose on of this line segment.set_parameters(parameters1) segment.set_parameters(parameters2) ``` -------------------------------- ### Import add_labels and default labels Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Imports the add_labels function and the default sitk label colors, then creates a numpy array of default labels for overlay rendering. ```python from PartSegCore.color_image import add_labels from PartSegCore.color_image.base_colors import sitk_labels default_labels = np.array(sitk_labels, dtype=np.uint8) ``` -------------------------------- ### Interactive preview of all layers with tifffile.imshow Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Builds a colored stack for all layers and displays it interactively with tifffile.imshow. This optional approach allows changing the displayed layer interactively. ```python import tifffile from PartSegCore.color_image import default_colormap_dict colormaps_list = [default_colormap_dict.get(x, None) for x in ["red", "green", "blue", None]] colored_stack = [] for i in range(image_app.layers): layer = image_app.get_data_by_axis(t=0, z=i) colored_image = color_image_fun(layer, colors=colormaps_list, min_max=image_app.get_ranges()) add_labels(colored_image, segmentation_app[i], 1, True, 2, components_to_show, default_labels) colored_stack.append(colored_image) colored_array = np.stack(colored_stack) tifffile.imshow(colored_array) plt.show() ``` -------------------------------- ### Load existing segmentation from file Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Load an existing segmentation from a .seg file using load_stack_segmentation. The segmentation mask is obtained from project_tuple.roi_info.roi. ```python project_tuple = load_stack_segmentation(os.path.join(data_path, "DMSO_120min_2_4.seg")) segmentation = project_tuple.roi_info.roi ``` -------------------------------- ### Save neuron components by type to directories Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Saves components of each neuron type into separate directories under save_path (DMSO_120min_2_1). Uses save_components with ROIInfo(segmentation) and creates directories with os.makedirs(exist_ok=True). ```python save_path = os.path.join(data_path, "DMSO_120min_2_1") for key, value in neuron_type_dict.items(): dir_path = os.path.join(save_path, key) os.makedirs(dir_path, exist_ok=True) save_components(image, value, dir_path, ROIInfo(segmentation)) ``` -------------------------------- ### Load or define segmentation parameters Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Load segmentation parameters from a JSON file using load_mask_metadata, or define them manually as a dictionary. The manual parameters include channel, threshold, minimum_size, close_holes, smooth_border, noise_filtering, side_connection, and use_convex. ```python segmentation_description = load_mask_metadata(os.path.join(data_path, "segment_data.json")) parameters1 = segmentation_description.values ``` ```python from PartSegCore.segmentation.noise_filtering import DimensionType parameters2 = { "channel": 3, "threshold": {"name": "Manual", "values": {"threshold": 19000}}, "minimum_size": 8000, "close_holes": True, "close_holes_size": 200, "smooth_border": {"name": "None", "values": {}}, "noise_filtering": {"name": "Gauss", "values": {"dimension_type": DimensionType.Layer, "radius": 1.0}}, "side_connection": False, "use_convex": True, } ``` -------------------------------- ### Load image and segmentation data Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Loads the image and segmentation data from files using TiffImageReader and load_stack_segmentation, then extracts the ROI segmentation array. ```python image_app = TiffImageReader.read_image(os.path.join(data_path, "DMSO_120min_2_1.lsm")) project_tuple_app = load_stack_segmentation(os.path.join(data_path, "DMSO_120min_2_1.seg")) segmentation_app = project_tuple_app.roi_info.roi ``` -------------------------------- ### Read image with TiffImageReader Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Read an image file (e.g., .lsm) using TiffImageReader.read_image. The image is used as input for segmentation algorithms. ```python image = TiffImageReader.read_image(os.path.join(data_path, "DMSO_120min_2_4.lsm")) ``` -------------------------------- ### Run segmentation calculation Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Run the segmentation calculation with the configured algorithm and parameters. The result's roi attribute contains the segmentation mask. ```python result = segment.calculation_run(print) segmentation = result.roi ``` -------------------------------- ### Classify neurons by marker presence using channel percentiles Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Classifies each good neuron into granular, pyramidal, inhibitory, or unexpected based on red and green channel percentiles (75th) and a threshold of 7000. Uses sitk.BinaryContour and sitk.BinaryDilate with radius (3,9,9) to account for voxel size 210x70x70nm. Channels are numbered from 0. ```python neuron_type_dict = defaultdict(list) good_neurons = set(good_neurons) for component_number in range(1, segmentation.max() + 1): if component_number not in good_neurons: continue current_component_area = segmentation == component_number value_red = np.percentile(image.get_channel(0)[0][current_component_area], 75) # radius is 3, 9, 9 because voxel size is 210x70x70nm and voxel size is in pixels, not physicla units dilate_sitk = sitk.BinaryContour(sitk.GetImageFromArray(current_component_area.astype(np.uint8))) dilate_mask = sitk.GetArrayFromImage(sitk.BinaryDilate(dilate_sitk, (3, 9, 9))) # dilate_mask = dilate(current_component_area, (3, 9, 9), False) # slower than two above lines but combined with next gave same result dilate_mask[current_component_area] = 0 value_green = np.percentile(image.get_channel(1)[0][current_component_area], 75) # print(component_number, value_red, value_green) if value_red > 7000: if value_green > 7000: neuron_type_dict["granular"].append(component_number) continue else: neuron_type_dict["unexpected"].append(component_number) continue elif value_green > 7000: neuron_type_dict["pyramidal"].append(component_number) continue neuron_type_dict["inhibitory"].append(component_number) print(neuron_type_dict) ``` -------------------------------- ### Preview a single segmentation layer with matplotlib Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Displays a single 2D layer of the segmentation overlaid on the colored image using matplotlib. It selects layer 28, builds a colormap list for red, green, blue, and None, then calls add_labels to draw the segmentation boundaries. ```python from PartSegCore.color_image import default_colormap_dict layer_num = 28 layer = image_app.get_data_by_axis(t=0, z=layer_num) components_to_show = np.ones(segmentation_app.max() + 1, dtype=np.uint8) colormaps_list = [default_colormap_dict.get(x, None) for x in ["red", "green", "blue", None]] colored_image = color_image_fun(layer, colors=colormaps_list, min_max=image_app.get_ranges()) add_labels(colored_image, segmentation_app[layer_num], 1, True, 2, components_to_show, default_labels) plt.figure(figsize=(9, 9)) plt.imshow(colored_image) plt.show() # plt.imshow(result.segmentation[layer_num]) ``` -------------------------------- ### Save stack segmentation to PartSeg mask with ThresholdAlgorithm Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Use this snippet to save a stack segmentation result as a PartSeg mask file (.seg) for easy preview. The first block imports required PartSeg modules and the second block iterates over .lsm files, applies a threshold segmentation, and saves each result with the .seg extension. Ensure the variables 'data_path', 'parameters', and 'empty' are defined before running. ```python import os from glob import glob from PartSegCore.mask.io_functions import MaskProjectTuple, SaveROI from PartSegCore.segmentation.segmentation_algorithm import ThresholdAlgorithm from PartSegImage.image_reader import TiffImageReader ``` ```python for file_path in glob(os.path.join(data_path, "*.lsm")): print("process", os.path.basename(file_path)) segment = ThresholdAlgorithm() segment.set_parameters(parameters) image = TiffImageReader.read_image(file_path) segment.set_image(image) result = segment.calculation_run(empty) segmentation = result.roi seg_tup = MaskProjectTuple(image.file_path, image, None, ROIInfo(segmentation), selected_components=[]) save_path = os.path.splitext(file_path)[0] + ".seg" SaveROI.save(save_path, seg_tup, {"relative_path": True}) ``` -------------------------------- ### Define color_image_fun for channel coloring Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Defines a helper function that converts a list of image layers into a colored RGB image using per-channel colormaps and value ranges. It skips channels whose colormap is None and returns an 8-bit unsigned integer array. ```python from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap, Normalize def color_image_fun(data, colors, min_max): res = [] for i, cmap_base in enumerate(colors): if cmap_base is None: continue cmap = ListedColormap(cmap_base.map(np.linspace(0, 1, 255))) res.append(cmap(Normalize(min_max[i][0], min_max[i][1])(data[i]))) return (np.amax(res, axis=0) * 255).astype(np.uint8) ``` -------------------------------- ### Set Path to Neuron Types Data Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Defines the path to the extracted neuron types data folder. This is the next step after downloading and extracting the data. ```Python data_path = "typy_neuronow2" ``` -------------------------------- ### Define neuron filtering, classification, and segmentation functions Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Defines three functions: get_good_neurons filters segmentation components that touch borders or have a sphericity ratio above 4.5; classify_neurons assigns each good component to a neuron type based on red/green channel percentiles (threshold 7000) and removes the 'unexpected' category; segmentation_function orchestrates reading a TIFF image, running a segmentation algorithm, applying convex fill, classifying neurons, and cutting out each neuron image. The code uses sitk.BinaryContour and sitk.BinaryDilate with kernel (3,9,9) to compute a dilated mask, and relies on image.spacing for voxel size. ```python def get_good_neurons(image: Image, segmentation: np.ndarray): good_neurons = [] # remove time axis segmentation = segmentation[0] for component_number in range(1, segmentation.max() + 1): current_component_area = segmentation == component_number # checking if touch borders coords = np.nonzero(current_component_area) if np.min(coords) == 0: continue touch = any( np.max(axis_cords) == max_size - 1 for axis_cords, max_size in zip(coords, current_component_area.shape, strict=True) ) if touch: continue diameter = Diameter.calculate_property(current_component_area, voxel_size=image.spacing, result_scalar=1) volume = Volume.calculate_property(current_component_area, voxel_size=image.spacing, result_scalar=1) # calculate # print(component_number, (4/3 * pi * (diameter/2)**3)/volume, diameter) if (4 / 3 * pi * (diameter / 2) ** 3) / volume > 4.5: continue good_neurons.append(component_number) print(f"filtered {segmentation.max() - len(good_neurons)}") return set(good_neurons) def classify_neurons(image: Image, segmentation: np.ndarray, good_neurons: set): neuron_type_dict = defaultdict(list) # remove time axis segmentation = segmentation[0] for component_number in range(1, segmentation.max() + 1): if component_number not in good_neurons: continue current_component_area = segmentation == component_number value_red = np.percentile(image.get_channel(0)[0][current_component_area], 75) # radius is 3, 9, 9 because voxel size is 210x70x70nm and voxel size is in pixels, not physicla units dilate_sitk = sitk.BinaryContour(sitk.GetImageFromArray(current_component_area.astype(np.uint8))) dilate_mask = sitk.GetArrayFromImage(sitk.BinaryDilate(dilate_sitk, (3, 9, 9))) # dilate_mask = dilate(current_component_area, (3, 9 ,9), False) # slower than two above lines but combined with next gave same result dilate_mask[current_component_area] = 0 value_green = np.percentile(image.get_channel(1)[0][current_component_area], 75) # print(component_number, value_red, value_green, np.percentile(image.get_channel(1)[current_component_area], 50)) if value_red > 7000: if value_green > 7000: neuron_type_dict["granular"].append(component_number) else: neuron_type_dict["unexpected"].append(component_number) continue if value_green > 7000: neuron_type_dict["pyramidal"].append(component_number) continue neuron_type_dict["inhibitory"].append(component_number) if "unexpected" in neuron_type_dict: items = len(neuron_type_dict["unexpected"]) print(f"deleted {items} neurons {neuron_type_dict['unexpected']}") del neuron_type_dict["unexpected"] # print(neuron_type_dict) return neuron_type_dict def segmentation_function(path_to_file, segment_object): def empty(_x, _y): pass image = TiffImageReader.read_image(path_to_file) segment_object.set_image(image) result = segment_object.calculation_run(empty) segmentation = result.roi good_neurons = get_good_neurons(image, segmentation) segmentation = convex_fill(segmentation) classified_neurons = classify_neurons(image, segmentation, good_neurons) nucleus_dict = defaultdict(list) for neuron_type, compenents_list in classified_neurons.items(): for component_number in compenents_list: im = image.cut_image(segmentation == component_number, replace_mask=True) nucleus_dict[neuron_type].append((component_number, im)) return nucleus_dict ``` -------------------------------- ### CollapseCheckbox Source: https://github.com/4dnucleome/partseg/blob/develop/docs/common_gui/collapse_checkbox.rst The CollapseCheckbox class provides functionality to manage hide elements with add and remove operations. ```APIDOC ## CollapseCheckbox Class ### Description A checkbox component that can hide and show associated elements. ### Methods #### add_hide_element - **Signature:** `add_hide_element(...)` - **Description:** Adds a hide element to the checkbox. #### remove_hide_element - **Signature:** `remove_hide_element(...)` - **Description:** Removes a hide element from the checkbox. ### Inherits - Shows inheritance information for the class. ``` -------------------------------- ### Run segmentation and collect measurements per nucleus type Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Iterates over cut neurons, runs the segmentation algorithm on each nucleus, and collects measurement results per nucleus type. The `empty` callback is passed to `calculation_run`; the mask is set to the first time point. Requires `cutted_neurons_dict`, `neuron_segment`, `neuron_segmentation_profile`, `measurment_object`, and `Units` from PartSegCore. ```python def empty(_x, _y): pass measurment_dict = defaultdict(list) for nucleus_group_dict in cutted_neurons_dict.values(): for nucleus_type, nucleus_list in nucleus_group_dict.items(): for _, nucleus in nucleus_list: neuron_segment.set_image(nucleus) neuron_segment.set_mask(nucleus.mask[0]) # do not touch time neuron_segment.set_parameters(neuron_segmentation_profile.values) result = neuron_segment.calculation_run(empty) measurment_dict[nucleus_type].append(measurment_object.calculate(nucleus, 2, result.roi, Units.nm)) ``` -------------------------------- ### Aggregate measurements into mean and std per neuron type Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Aggregates measurement values per neuron type, computing mean and standard deviation for each measurement key. Use after collecting raw measurements in `measurment_dict`. Requires `numpy` as `np` and `defaultdict` from collections. ```python measurment_result = [] for neuron_type, values in measurment_dict.items(): sub_result = defaultdict(list) for value_dict in values: for key, (value, _) in value_dict.items(): sub_result[key].append(value) measurment_result.append((neuron_type, [(name, np.mean(v), np.std(v)) for name, v in sub_result.items()])) ``` -------------------------------- ### Extract nucleus images from stack per neuron type Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Extracts each neuron component as a cut image using image.cut_image with replace_mask=True and stores it in nucleus_dict keyed by neuron type. Note the variable name is nucleus_dict but the loop uses neuron_type_dict. ```python nucleus_dict = defaultdict(list) for neuron_type, compenents_list in neuron_type_dict.items(): for component_number in compenents_list: im = image.cut_image(segmentation == component_number, replace_mask=True) nucleus_dict[neuron_type].append((component_number, im)) ``` -------------------------------- ### Plot measurement results with error bars Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Plots bar charts with error bars for each measurement type, using the aggregated `measurment_result`. Requires `matplotlib.pyplot` as `plt`. The `strict=True` arguments require Python 3.10+. ```python ticks, values = list(zip(*measurment_result, strict=True)) values = list(zip(*values, strict=True)) f, axx = plt.subplots(1, len(values), figsize=(5 * len(values), 5)) for el, ax in zip(values, axx, strict=True): name, mean, std = list(zip(*el, strict=True)) plt.sca(ax) plt.title(name[0]) plt.bar(range(len(ticks)), mean) for i, m, s in zip(range(len(mean)), mean, std, strict=True): plt.plot([i, i], [m - s / 2, m + s / 2], color="black") plt.xticks(range(len(ticks)), ticks) ``` -------------------------------- ### Filter segmentation components by border touch and sphericity Source: https://github.com/4dnucleome/partseg/blob/develop/tutorials/tutorial_neuron_types/Neuron_types_example.ipynb Filters segmentation components by excluding those touching image borders and those with sphericity below a threshold (volume ratio > 4). Uses Diameter and Volume properties with voxel_size from image.spacing and result_scalar 10**6. The threshold 4 is data-dependent; adjust for cell types with irregular shapes. ```python good_neurons = [] for component_number in range(1, segmentation.max() + 1): current_component_area = segmentation == component_number # checking if touch borders coords = np.nonzero(current_component_area) if np.min(coords) == 0: continue touch = False for axis_cords, max_size in zip(coords, current_component_area.shape, strict=True): if np.max(axis_cords) == max_size - 1: touch = True break if touch: continue diameter = Diameter.calculate_property(current_component_area, voxel_size=image.spacing, result_scalar=10**6) volume = Volume.calculate_property(current_component_area, voxel_size=image.spacing, result_scalar=10**6) # calculate shericity # print(component_number, (4/3 * pi * (diameter/2)**3)/volume, diameter) if (4 / 3 * pi * (diameter / 2) ** 3) / volume > 4: continue good_neurons.append(component_number) print(good_neurons) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.