ROI Analysis Tools

ROI Analyzer

class simba.roi_tools.ROI_analyzer.ROIAnalyzer(config_path, data_path=None, detailed_bout_data=False, calculate_distances=False, threshold=0.0, body_parts=None)[source]

Bases: simba.mixins.config_reader.ConfigReader, simba.mixins.feature_extraction_mixin.FeatureExtractionMixin

Analyze movements, entries, exits, and time-spent-in user-defined ROIs. Results are stored in the ‘project_folder/logs’ directory of the SimBA project.

Parameters
  • config_path (str) – Path to SimBA project config file in Configparser format.

  • data_path (Optional[str]) – Path to folder or file holding the data used to calculate ROI aggregate statistics. If None, then defaults to the project_folder/csv/outlier_corrected_movement_location directory of the SimBA project. Default: None.

  • calculate_distances (Optional[bool]) – If True, then calculate movements aggregate statistics (distances and velocities) inside ROIs. Results are saved in project_folder/logs/ directory. Default: False.

  • detailed_bout_data (Optional[bool]) – If True, saves a file with a row for every entry into each ROI for each animal in each video. Results are saved in project_folder/logs/ directory. Default: False.

  • threshold (Optional[float]) – Float between 0 and 1. Body-part locations detected below this confidence threshold are filtered. Default: 0.0.

  • body_parts (Optional[List[str]]) – List of body-parts to perform ROI analysis on.

Example

>>> test = ROIAnalyzer(config_path = r"/Users/simon/Desktop/envs/simba/troubleshooting/two_black_animals_14bp/project_folder/project_config.ini", calculate_distances=True, detailed_bout_data=True, body_parts=['Nose_1', 'Nose_2'], threshold=0.0)
>>> test.run()
>>> test.save()

ROI Classification Calculator - Single Core

class simba.roi_tools.roi_clf_calculator.ROIClfCalculator(config_path, bp_names, save_path=None, data_paths=None, roi_coordinates_path=None, clf_names=None, roi_names=None, clf_time=True, started_bout_cnt=True, ended_bout_cnt=True, bout_table=False, transpose=False, verbose=True)[source]

Bases: simba.mixins.config_reader.ConfigReader

Compute aggregate statistics of classification results within user-defined ROIs. Results are stored in project_folder/logs directory of the SimBA project.

Parameters
  • config_path (Union[str, os.PathLike]) – path to SimBA project config file in Configparser format

  • bp_names (List[str]) – List of body-parts to use as proxy for animal locations.

  • save_path (Optional[Union[str, os.PathLike]]) – Optional location where to store the results in CSV format. If None, then results are stored in logs folder of SImBA project.

  • data_paths (Optional[List[Union[str, os.PathLike]]]) – Optional list of data files to analyze. If None, then all file sin the machine_results directory is analyzed.

  • clf_names (Optional[List[str]]) – Optional List of classifiers to analyze. If None, then all classifiers in SimBA project are analyzed.

  • roi_names (Optional[List[str]]) – Optional list of ROI names to analyze. If None, then all ROI names are analyzed.

  • clf_time (bool) – If True, computes aggregate time of each classifier in each ROI. Deafult True.

  • started_bout_cnt (bool) – If True, computes started bout counts of each classifier in each ROI. Deafult True.

  • ended_bout_cnt (bool) – If True, computes ended bout counts of each classifier in each ROI. Deafult True.

Example

>>> analyzer = ROIClfCalculator(config_path=r"D:    roubleshooting\mitra\project_folder\project_config.ini", bp_names=('nose',), clf_names=('straub_tail',))
>>> analyzer.run()
>>> analyzer.save()

ROI Classification Calculator - Multiprocess

class simba.roi_tools.roi_clf_calculator_mp.ROIClfCalculatorMultiprocess(config_path, bp_names, save_path=None, data_paths=None, roi_coordinates_path=None, clf_names=None, roi_names=None, clf_time=True, started_bout_cnt=True, ended_bout_cnt=True, bout_table=False, transpose=False, verbose=True, core_cnt=- 1)[source]

Bases: simba.mixins.config_reader.ConfigReader

Compute aggregate statistics of classification results within user-defined ROIs. Results are stored in project_folder/logs directory of the SimBA project.

See also

For single core process, see simba.roi_tools.roi_clf_calculator.ROIClfCalculator()

Parameters
  • config_path (Union[str, os.PathLike]) – path to SimBA project config file in Configparser format

  • bp_names (List[str]) – List of body-parts to use as proxy for animal locations.

  • save_path (Optional[Union[str, os.PathLike]]) – Optional location where to store the results in CSV format. If None, then results are stored in logs folder of SImBA project.

  • data_paths (Optional[List[Union[str, os.PathLike]]]) – Optional list of data files to analyze. If None, then all file sin the machine_results directory is analyzed.

  • clf_names (Optional[List[str]]) – Optional List of classifiers to analyze. If None, then all classifiers in SimBA project are analyzed.

  • roi_names (Optional[List[str]]) – Optional list of ROI names to analyze. If None, then all ROI names are analyzed.

  • clf_time (bool) – If True, computes aggregate time of each classifier in each ROI. Deafult True.

  • started_bout_cnt (bool) – If True, computes started bout counts of each classifier in each ROI. Deafult True.

  • ended_bout_cnt (bool) – If True, computes ended bout counts of each classifier in each ROI. Deafult True.

Example

>>> analyzer = ROIClfCalculatorMultiprocess(config_path=r"D:/troubleshooting/maplight_ri/project_folder/project_config.ini", bp_names=['resident_NOSE'], clf_names=['attack'], clf_time=True, started_bout_cnt=True, ended_bout_cnt=False, bout_table=True, transpose=True, core_cnt=20)
>>> analyzer.run()
>>> analyzer.save()

ROI Movement Analyzer - Single Core

class simba.roi_tools.roi_aggregate_statistics_analyzer.ROIAggregateStatisticsAnalyzer(config_path, data_path=None, threshold=0.0, body_parts=None, detailed_bout_data=False, calculate_distances=False, total_time=True, entry_counts=True, first_entry_time=False, last_entry_time=False, mean_bout_time=False, outside_rois=False, transpose=False, include_fps=False, include_video_length=False, include_px_per_mm=False, verbose=True, detailed_bout_data_save_path=None, save_path=None)[source]

Bases: simba.mixins.config_reader.ConfigReader, simba.mixins.feature_extraction_mixin.FeatureExtractionMixin

Analyzes region-of-interest (ROI) data from video tracking experiments.

This class computes various statistics related to body-part movements inside defined ROIs, including entry counts, total time spent, and bout durations.

Parameters
  • os.PathLike) (config_path (str |) – Path to the configuration file.

  • optional) (save_path (str | os.PathLike,) – Path(s) to the data files.

  • (float) (threshold) – Probability threshold for body-part inclusion.

  • optional) – List of body parts to analyze.

  • (bool) (verbose) – Whether to compute detailed bout data.

  • (bool) – Whether to compute distances traveled.

  • (bool) – Whether to calculate total time spent in ROIs.

  • (bool) – Whether to count entries into ROIs.

  • (bool) – Whether to record the first entry time.

  • (bool) – If checked, SimBA will treat all areas NOT covered by a ROI drawing as a single additional ROI and compute the chosen metrics for this, single, ROI.

  • (bool) – Whether to record the last entry time.

  • (bool) – Whether to compute mean bout duration.

  • (bool) – Whether to transpose the final results.

  • (bool) – Whether to include video FPS in the results.

  • (bool) – Whether to include video length in the results.

  • (bool) – Whether to include pixel-to-millimeter conversion factor in the results.

  • (bool) – Whether to print verbose output during processing.

  • optional) – Path to save detailed bout data.

  • optional) – Path to save summary statistics.

Example

>>> analyzer = ROIAggregateStatisticsAnalyzer(config_path=r"C:      roubleshooting\mitra\project_folder\project_config.ini", body_parts=['Center'], first_entry_time=True, threshold=0.0, calculate_distances=True, transpose=False, detailed_bout_data=True)
>>> analyzer.run()
>>> analyzer.save()

ROI Movement Analyzer - Multiprocess

class simba.roi_tools.roi_aggregate_stats_mp.ROIAggregateStatisticsAnalyzerMultiprocess(config_path, data_path=None, threshold=0.0, body_parts=None, detailed_bout_data=False, calculate_distances=False, total_time=True, entry_counts=True, first_entry_time=False, last_entry_time=False, mean_bout_time=False, outside_rois=False, transpose=False, include_fps=False, include_video_length=False, include_px_per_mm=False, verbose=True, detailed_bout_data_save_path=None, save_path=None, core_cnt=- 1)[source]

Bases: simba.mixins.config_reader.ConfigReader, simba.mixins.feature_extraction_mixin.FeatureExtractionMixin

Analyzes region-of-interest (ROI) data from video tracking experiments.

This class computes various statistics related to body-part movements inside defined ROIs, including entry counts, total time spent, and bout durations.

Parameters
  • os.PathLike) (config_path (str |) – Path to the configuration file.

  • optional) (save_path (str | os.PathLike,) – Path(s) to the data files.

  • (float) (threshold) – Probability threshold for body-part inclusion.

  • optional) – List of body parts to analyze.

  • (bool) (transpose) – Whether to compute detailed bout data.

  • (bool) – Whether to compute distances traveled.

  • (bool) – Whether to calculate total time spent in ROIs.

  • (bool) – Whether to count entries into ROIs.

  • (bool) – Whether to record the first entry time.

  • (bool) – If checked, SimBA will treat all areas NOT covered by a ROI drawing as a single additional ROI and compute the chosen metrics for this, single, ROI.

  • (bool) – Whether to record the last entry time.

  • (bool) – Whether to compute mean bout duration.

  • (bool) – Whether to transpose the final results.

  • optional) – Path to save detailed bout data.

  • optional) – Path to save summary statistics.

Example

>>> analyzer = ROIAggregateStatisticsAnalyzerMultiprocess(config_path=r"C:/troubleshooting/mitra/project_folder/project_config.ini", body_parts=['Center'], first_entry_time=True, threshold=0.0, calculate_distances=True, transpose=False, detailed_bout_data=True)
>>> analyzer.run()
>>> analyzer.save()

ROI Feature Analyzer

class simba.roi_tools.ROI_feature_analyzer.ROIFeatureCreator(config_path, body_parts, data_path=None, append_data=False)[source]

Bases: simba.mixins.config_reader.ConfigReader, simba.mixins.feature_extraction_mixin.FeatureExtractionMixin

Compute features based on the relationships between the location of the animals and the location of user-defined ROIs. This includes the distance to the ROIs, if the animals are inside the ROIs, and if the animals are directing towards the ROIs (if viable)

Parameters
  • config_path (Union[str, os.PathLike]) – Path to SimBA project config file in Configparser format.

  • body_parts (List[str]) – List of the body-parts to use as proxy for animal location(s).

  • data_path (Optional[Union[str, os.PathLike]]) – Path to folder or file holding the data used to calculate ROI aggregate statistics. If None, then defaults to the project_folder/csv/outlier_corrected_movement_location directory of the SimBA project. Default: None.

  • append_data (Optional[bool]) – If True, adds the features to the data in the project_folder/csv/features_extracted directory. Else, the data is held in memory.

Example

>>> roi_featurizer = ROIFeatureCreator(config_path='/Users/simon/Desktop/envs/simba/troubleshooting/two_black_animals_14bp/project_folder/project_config.ini', body_parts=['Nose_1', 'Nose_2'])
>>> roi_featurizer.run()
>>> roi_featurizer.save()
>>> roi_featurizer = ROIFeatureCreator(config_path=r"C:     roubleshooting\spontenous_alternation\project_folder\project_config.ini", body_parts=['nose'], data_path=r"C:   roubleshooting\spontenous_alternation\project_folder\csv\outlier_corrected_movement_location\F1 HAB.csv", append_data=True)
>>> roi_featurizer.run()
>>> roi_featurizer.save()

ROI Directing Analyzer

class simba.roi_tools.ROI_directing_analyzer.DirectingROIAnalyzer(config_path, data_path=None, roi_coordinates_path=None, detailed_table=True, agg_stats=True, transpose_agg_stats=False, left_ear_name=None, right_ear_name=None, nose_name=None)[source]

Bases: simba.mixins.config_reader.ConfigReader, simba.mixins.feature_extraction_mixin.FeatureExtractionMixin

Compute aggregate statistics for animals directing towards ROIs.

Parameters
  • config_path (str) – Path to SimBA project config file in Configparser format

  • data_path (Optional[Union[str, os.PathLike]]) – Path to folder or file holding the data used to calculate ROI aggregate statistics. If None, then defaults to the project_folder/csv/outlier_corrected_movement_location directory of the SimBA project. Default: None.

Example

>>> test = DirectingROIAnalyzer(config_path='/Users/simon/Desktop/envs/simba/troubleshooting/two_black_animals_14bp/project_folder/project_config.ini')
>>> test.run()
>>> test.save()
class simba.roi_tools.ROI_directing_analyzer.DirectingROIAnalyzer(config_path, data_path=None, roi_coordinates_path=None, detailed_table=True, agg_stats=True, transpose_agg_stats=False, left_ear_name=None, right_ear_name=None, nose_name=None)[source]

Bases: simba.mixins.config_reader.ConfigReader, simba.mixins.feature_extraction_mixin.FeatureExtractionMixin

Compute aggregate statistics for animals directing towards ROIs.

Parameters
  • config_path (str) – Path to SimBA project config file in Configparser format

  • data_path (Optional[Union[str, os.PathLike]]) – Path to folder or file holding the data used to calculate ROI aggregate statistics. If None, then defaults to the project_folder/csv/outlier_corrected_movement_location directory of the SimBA project. Default: None.

Example

>>> test = DirectingROIAnalyzer(config_path='/Users/simon/Desktop/envs/simba/troubleshooting/two_black_animals_14bp/project_folder/project_config.ini')
>>> test.run()
>>> test.save()

ROI Time-Bin Calculator

class simba.roi_tools.roi_time_bins_analyzer.ROITimebinAnalyzer(config_path, bin_size, data_path=None, threshold=0.0, body_parts=None, detailed_bout_data=False, calculate_distances=False, total_time=True, entry_counts=True, first_entry_time=False, last_entry_time=False, transpose=False, outside_rois=False, verbose=True, include_fps=False, include_video_length=False, include_px_per_mm=False, include_time_stamps=False, detailed_bout_data_save_path=None, save_path=None)[source]

Bases: simba.mixins.config_reader.ConfigReader

Analyzes region-of-interest (ROI) data from video tracking experiments conditioned on time-bin.

This class computes various statistics related to body-part movements inside defined ROIs, including entry counts, total time spent, and bout durations.

Parameters
  • os.PathLike) (config_path (str |) – Path to the configuration file.

  • optional) (save_path (str | os.PathLike,) – Path(s) to the data files.

  • (float) (threshold) – Probability threshold for body-part inclusion.

  • optional) – List of body parts to analyze.

  • (bool) (transpose) – Whether to compute detailed bout data.

  • (bool) – Whether to compute distances traveled.

  • (bool) – Whether to calculate total time spent in ROIs.

  • (bool) – Whether to count entries into ROIs.

  • (bool) – Whether to record the first entry time.

  • (bool) – Whether to include time bin start times, start frame, end time and end frame in output.

  • (bool) – If checked, SimBA will treat all areas NOT covered by a ROI drawing as a single additional ROI and compute the chosen metrics for this, single, ROI.

  • (bool) – Whether to record the last entry time.

  • (bool) – Whether to transpose the final results.

  • optional) – Path to save detailed bout data.

  • optional) – Path to save summary statistics.

Example

>>> test = ROITimebinAnalyzer(config_path=r"C:      roubleshooting\mitra\project_folder\project_config.ini", bin_size=61, body_parts=['Nose'], detailed_bout_data=True, calculate_distances=True, transpose=True)
>>> test.run()
>>> test.save()

ROI Time-Bin Calculator (Legacy)

class simba.roi_tools.ROI_time_bin_calculator.ROITimebinCalculator(config_path, bin_length, body_parts, data_path=None, threshold=0.0, movement=False)[source]

Bases: simba.mixins.config_reader.ConfigReader

Compute how much time and how many entries animals are making into user-defined ROIs within user-defined time bins. Also compute the average velocity and distance moved within user-defined ROIs split by time-bins.

Results are stored in the project_folder/logs directory of the SimBA project.

Parameters
  • config_path (Union[str, os.PathLike]) – path to SimBA project config file in Configparser format

  • bin_length (float) – length of time bins in seconds.

  • body_parts (List[str]) – List of body-parts to use as proxy of animal locations.

  • threshold (float) – Filter pose-estimation data detected below defined threshold.

  • movement (Optional[bool]) – If True, compute the distances and velocities within time-bins. Default False.

Example

>>> calculator = ROITimebinCalculator(config_path=r"/Users/simon/Desktop/envs/simba/troubleshooting/two_black_animals_14bp/project_folder/project_config.ini", bin_length=1.0, body_parts=['Nose_1'], threshold=0.00, movement=True)
>>> calculator.run()
>>> calculator.save()

ROI Size Standardizer

class simba.roi_tools.ROI_size_standardizer.ROISizeStandardizer(config_path, reference_video)[source]

Bases: simba.mixins.config_reader.ConfigReader, simba.mixins.feature_extraction_mixin.FeatureExtractionMixin

Standardize ROI sizes according to a reference video.

Note

Example: You select a “baseline” video, say that this baseline video has a pixel per millimeter of 10. Say there are a further two videos in the project with ROIs, and these videos has pixels per millimeter of 9 and 11. At runtime, the area of the rectangles, circles and polygons in the two additional videos get their ROI areas increased/decreased with 10% while the baseline video ROIs are unchanged.

Parameters
  • os.PathLike] (str Union[str,) – path to SimBA project config file in Configparser format.

  • reference_video (str) – Name of baseline video without extension, e.g., Video_1.

Example

>>> test = ROISizeStandardizer(config_path='/Users/simon/Desktop/envs/troubleshooting/DLC_2_Black_animals/project_folder/project_config.ini', reference_video='Together_1')
>>> test.run()
>>> test.save()

ROI Visualization

ROI Plotter - Single Core

class simba.plotting.roi_plotter.ROIPlotter(config_path, video_path, body_parts, outside_roi=False, threshold=0.0, verbose=True, show_animal_name=False, show_body_part=True, show_bbox=False, data_path=None, save_path=None, bp_colors=None, bp_sizes=None, border_bg_clr=(0, 0, 0))[source]

Bases: simba.mixins.config_reader.ConfigReader

Visualize the ROI data (number of entries/exits, time-spent in ROIs etc).

See also

Use simba.plotting.ROI_plotter_mp.ROIPlotMultiprocess() for improved run-time.

ROIPlot 1
param Union[str, os.PathLike] config_path

Path to SimBA project config file in Configparser format.

param Union[str, os.PathLike] video_path

Path to video file to create ROI visualizations for.

param List[str] body_parts

List of the body-parts to use as proxy for animal locations.

param bool outside_roi

If True, SimBA will treat all areas NOT covered by a ROI drawing as a single additional ROI and visualize the stats for this single ROI. Default: False.

param float threshold

Float between 0 and 1. Body-part locations detected below this confidence threshold are filtered. Default: 0.0.

param Optional[bool] verbose

If True, print progress messages during video creation. Default: True.

param bool show_animal_name

If True, display animal names on the video frames. Default: False.

param bool show_body_part

If True, display body-part locations as circles on the video frames. Default: True.

param Optional[Union[str, os.PathLike]] data_path

Optional path to the pose-estimation data. If None, then locates file in outlier_corrected_movement_location directory. Default: None.

param Optional[Union[str, os.PathLike]] save_path

Optional path to where to save video. If None, then saves it in frames/output/roi_analysis directory of SimBA project. Default: None.

param Optional[List[Tuple[int, int, int]]] bp_colors

Optional list of tuples of same length as body_parts representing the colors of the body-parts in RGB format. Defaults to None and colors are automatically chosen. Default: None.

param Optional[List[Union[int]]] bp_sizes

Optional list of integers representing the sizes of the pose estimated body-part location circles. Defaults to None and size is automatically inferred. Default: None.

param Tuple[int, int, int] border_bg_clr

RGB tuple representing the background color of the border area where statistics are displayed. Default: (0, 0, 0).

example

>>> test = ROIPlotter(config_path=r'/Users/simon/Desktop/envs/simba/troubleshooting/mouse_open_field/project_folder/project_config.ini',
>>>                video_path="/Users/simon/Desktop/envs/simba/troubleshooting/mouse_open_field/project_folder/videos/SI_DAY3_308_CD1_PRESENT.mp4",
>>>                body_parts=['Nose'],
>>>                show_body_part=True,
>>>                show_animal_name=True)
>>> test.run()
example II

>>> test = ROIPlotter(config_path=r"C:      roubleshooting\mitra\project_folder\project_config.ini",
>>>               video_path=r"C:   roubleshooting\mitra\project_folder
ideosŁ_MA142_Gi_Saline_0513.mp4”,
>>>               body_parts=['Nose'],
>>>               show_body_part=True,
>>>               show_animal_name=False)
>>> test.run()

ROI Plotter - Multiprocess

class simba.plotting.roi_plotter_mp.ROIPlotMultiprocess(config_path, video_path, body_parts, threshold=0.0, core_cnt=- 1, verbose=True, outside_roi=False, show_body_part=True, font=None, show_animal_name=False, bbox=None, print_timer='seconds', border_bg_clr=(0, 0, 0), data_path=None, save_path=None, bp_colors=None, bp_sizes=None, gpu=False)[source]

Bases: simba.mixins.config_reader.ConfigReader, simba.mixins.plotting_mixin.PlottingMixin

Visualize the ROI data (number of entries/exits, time-spent in ROIs) using multiprocessing for improved performance.

Roi visualize ROIPlot 1
Parameters
  • config_path (Union[str, os.PathLike]) – Path to SimBA project config file in Configparser format.

  • video_path (Union[str, os.PathLike]) – Path to video file to create ROI visualizations for.

  • body_parts (List[str]) – List of the body-parts to use as proxy for animal locations.

  • threshold (float) – Float between 0 and 1. Body-part locations detected below this confidence threshold are filtered. Default: 0.0.

  • core_cnt (int) – Number of cores to use for multiprocessing. Default: -1 (uses all available cores).

  • verbose (bool) – If True, print progress messages during video creation. Default: True.

  • outside_roi (bool) – If True, SimBA will treat all areas NOT covered by a ROI drawing as a single additional ROI and visualize the stats for this single ROI. Default: False.

  • show_body_part (bool) – If True, display body-part locations as circles on the video frames. Default: True.

  • show_animal_name (bool) – If True, display animal names on the video frames. Default: False.

  • bbox (Optional[Literal['axis-aligned', 'animal-aligned']]) – If not None, draw bounding boxes around each animal. 'axis-aligned' = rectangle aligned with video axes; 'animal-aligned' = minimum rotated rectangle aligned with the animal’s orientation. Default: None (no bounding boxes).

  • print_timer (Literal['seconds', 'hh:mm:ss.ssss']) – Timer format for behavior/ROI counters shown in the border panel. 'seconds' = numeric seconds, 'hh:mm:ss.ssss' = clock-style timestamp with fractional seconds. Default: 'seconds'.

  • border_bg_clr (Tuple[int, int, int]) – RGB tuple representing the background color of the border area where statistics are displayed. Default: (0, 0, 0).

  • data_path (Optional[Union[str, os.PathLike]]) – Optional path to the pose-estimation data. If None, then locates file in outlier_corrected_movement_location directory. Default: None.

  • save_path (Optional[Union[str, os.PathLike]]) – Optional path to where to save video. If None, then saves it in frames/output/roi_analysis directory of SimBA project. Default: None.

  • bp_colors (Optional[List[Tuple[int, int, int]]]) – Optional list of tuples of same length as body_parts representing the colors of the body-parts in RGB format. Defaults to None and colors are automatically chosen. Default: None.

  • bp_sizes (Optional[List[Union[int]]]) – Optional list of integers representing the sizes of the pose estimated body-part location circles. Defaults to None and size is automatically inferred. Default: None.

  • gpu (bool) – If True, use GPU acceleration for video concatenation. Default: False.

Example

>>> test = ROIPlotMultiprocess(config_path=r'/Users/simon/Desktop/envs/simba/troubleshooting/mouse_open_field/project_folder/project_config.ini',
>>>                            video_path="/Users/simon/Desktop/envs/simba/troubleshooting/mouse_open_field/project_folder/videos/SI_DAY3_308_CD1_PRESENT.mp4",
>>>                            core_cnt=7,
>>>                            body_parts=['Nose'],
>>>                            show_body_part=True,
>>>                            show_animal_name=False)
>>> test.run()

ROI Feature Visualizer - Single Core

class simba.plotting.ROI_feature_visualizer.ROIfeatureVisualizer(config_path, video_path, body_parts, style_attr)[source]

Bases: simba.mixins.config_reader.ConfigReader

Visualizing features that depend on the relationships between the location of the animals and user-defined ROIs. E.g., distances to centroids of ROIs, if animals are directing towards ROIs, and if animals are within ROIs.

Note

For improved run-time, see simba.ROI_feature_visualizer_mp.ROIfeatureVisualizerMultiprocess() for multiprocess class. Tutorials.

Roi visualize ROIfeature Visualizer 1 ROIfeature Visualizer 2
Parameters
  • config_path (Union[str, os.PathLike]) – Path to SimBA project config file in Configparser format

  • video_path (Union[str, os.PathLike]) – Path to video file to overlay ROI features on.

  • body_parts (List[str]) – List of body-parts to use as proxy for animal location(s).

  • style_attr (Dict[str, Any]) – User-defined styles (sizes, colors etc.)

Example

>>> style_attr = {'roi_centers': True, 'roi_ear_tags': True, 'directionality': True, 'directionality_style': 'funnel', 'border_color': (0, 0, 0), 'pose_estimation': True, 'animal_names': True}
>>> test = ROIfeatureVisualizer(config_path='/Users/simon/Desktop/envs/simba/troubleshooting/RAT_NOR/project_folder/project_config.ini', video_path='/Users/simon/Desktop/envs/simba/troubleshooting/RAT_NOR/project_folder/videos/2022-06-20_NOB_DOT_4.mp4', style_attr=style_attr, body_parts=['Nose'])
>>> test.run()

ROI Feature Visualizer - Multiprocess

class simba.plotting.ROI_feature_visualizer_mp.ROIfeatureVisualizerMultiprocess(config_path, video_path, body_parts, show_roi_centers=True, show_roi_eartags=False, show_animal_names=False, font=None, border_bg_clr=(0, 0, 0), direction=None, time_slice=None, bbox=None, roi_coordinates_path=None, show_pose=True, core_cnt=- 1, gpu=False)[source]

Bases: simba.mixins.config_reader.ConfigReader

Visualize features that depend on the relationships between the location of the animals and user-defined ROIs. E.g., distances to centroids of ROIs, cumulative time spent in ROIs, if animals are directing towards ROIs etc. Uses multiprocessing for faster rendering.

Parameters
  • config_path (Union[str, os.PathLike]) – Path to SimBA project config file in Configparser format.

  • video_path (Union[str, os.PathLike]) – Path to video file to overlay ROI features on.

  • body_parts (List[str]) – List of body-parts to use as proxy for animal location(s). One per animal.

  • show_roi_centers (bool) – If True, draw the center point of each ROI on the video. Default True.

  • show_roi_eartags (bool) – If True, draw ear-tag labels on ROI shapes. Default False.

  • show_animal_names (bool) – If True, display animal names on the video. Default False.

  • font (Optional[str]) – Name of a SimBA-bundled font (in simba/assets/fonts, e.g. 'Poppins Regular') used for the ROI feature text drawn in the border panel. If None, a default cv2 font is used. Default None.

  • border_bg_clr (Tuple[int, int, int]) – RGB tuple for the background color of the border panel where ROI stats are shown. Default (0, 0, 0).

  • direction (Optional[Literal['funnel', 'lines']]) – If not None, draw directionality (animal directing towards ROI). 'funnel' or 'lines' style. Default None (no directionality).

  • time_slice (Optional[Dict[str, str]]) – Optional time window to render, given as {'start_time': 'HH:MM:SS', 'end_time': 'HH:MM:SS'}. If None, the full video is rendered. Default None.

  • bbox (Optional[Literal['axis-aligned', 'animal-aligned']]) – If not None, draw bounding boxes around each animal. 'axis-aligned' = rectangle aligned with video axes; 'animal-aligned' = minimum rotated rectangle. Default None (no bounding boxes).

  • roi_coordinates_path (Optional[Union[str, os.PathLike]]) – Optional path to ROI definitions file. If None, uses project default from config. Default None.

  • show_pose (bool) – If True, draw pose-estimation keypoints (circles) on the video. Default True.

  • core_cnt (int) – Number of CPU cores for multiprocessing. -1 uses all available. Default -1.

  • gpu (bool) – If True, use GPU for video concatenation when available. Default False.

Note

Tutorials. See simba.ROI_feature_visualizer.ROIfeatureVisualizer() for single process class. Would be slower but potentially more reliable.

ROIfeature Visualizer 1 ROIfeature Visualizer 2
Example

>>> test = ROIfeatureVisualizerMultiprocess(config_path='/Users/simon/Desktop/envs/simba/troubleshooting/spontenous_alternation/project_folder/project_config.ini',
...     video_path='/Users/simon/Desktop/envs/simba/troubleshooting/spontenous_alternation/project_folder/videos/NOR ENCODING FExMP8.mp4',
...     body_parts=['Center'],
...     show_roi_centers=True,
...     show_roi_eartags=False,
...     direction='funnel',
...     show_pose=True,
...     show_animal_names=True,
...     font='Poppins Regular',
...     core_cnt=-1)
>>> test.run()

ROI Directing Visualizer

class simba.plotting.roi_directing_visualizer.DirectingROIVisualizer(config_path, video_path, direction_style='lines', direction_color=(0, 0, 255), direction_thickness=None, circle_size=None, show_pose=True, show_roi_centers=True, show_animal_names=False, border_bg_clr=(0, 0, 0), time_slice=None, roi_coordinates_path=None, left_ear_name=None, right_ear_name=None, nose_name=None, core_cnt=- 1, gpu=False, verbose=True)[source]

Bases: simba.mixins.config_reader.ConfigReader, simba.mixins.plotting_mixin.PlottingMixin

Visualize when animals are directing towards ROIs. Draws the ROIs on the video frames, overlays pose-estimation body-parts, and draws directing lines (funnel or line style) from the animal eye midpoint to the ROI when the animal is directing towards the ROI. A text panel shows the directing boolean for each animal-ROI combination per frame. Uses multiprocessing.

Parameters
  • config_path (Union[str, os.PathLike]) – Path to SimBA project config file in Configparser format.

  • video_path (Union[str, os.PathLike]) – Path to video file to overlay directing visualization on.

  • direction_style (Literal['funnel', 'lines']) – Style of direction line. Default ‘funnel’.

  • direction_color (Tuple[int, int, int]) – BGR color of the directing line. Default (0, 0, 255) (red).

  • direction_thickness (Optional[int]) – Thickness of the directing line (used for ‘lines’ style). If None, computed automatically based on video resolution. Default None.

  • circle_size (Optional[int]) – Size of the pose-estimation keypoint circles. If None, computed automatically based on video resolution. Default None.

  • show_pose (bool) – If True, draw pose-estimation keypoints on the video. Default True.

  • show_roi_centers (bool) – If True, draw the center of each ROI. Default True.

  • show_animal_names (bool) – If True, display animal names on the video. Default False.

  • border_bg_clr (Tuple[int, int, int]) – BGR color for the text panel background. Default (0, 0, 0).

  • time_slice (Optional[Dict[str, str]]) – Optional dict with ‘start_time’ and ‘end_time’ keys (HH:MM:SS format) to visualize a sub-clip. Default None.

  • roi_coordinates_path (Optional[Union[str, os.PathLike]]) – Optional path to ROI definitions file. If None, uses the project default. Default None.

  • left_ear_name (Optional[str]) – Optional custom left ear body-part name. Default None.

  • right_ear_name (Optional[str]) – Optional custom right ear body-part name. Default None.

  • nose_name (Optional[str]) – Optional custom nose body-part name. Default None.

  • core_cnt (int) – Number of CPU cores for multiprocessing. -1 uses all available. Default -1.

  • gpu (bool) – If True, use GPU for video concatenation when available. Default False.

  • verbose (bool) – If True, print progress messages during visualization. Default True.

Example

>>> viz = DirectingROIVisualizer(config_path='/path/to/project_config.ini',
...                              video_path='/path/to/video.mp4',
...                              direction_style='funnel',
...                              show_pose=True,
...                              core_cnt=4)
>>> viz.run()

ROI GUI Tools

ROI GUI

class simba.roi_tools.roi_ui.ROI_ui(video_path, config_path=None, roi_coordinates_path=None, pose_path=None, video_dir=None, roi_table_popup=None)[source]

Bases: simba.roi_tools.roi_ui_mixin.ROI_mixin, simba.mixins.config_reader.ConfigReader

Main entry-point for drawing ROIs on videos.

Note

See ROI tutorial on GitHub or ReadTheDocs

param Union[str, os.PathLike] video_path

Path to the video file to draw ROIs on.

param Optional[Union[str, os.PathLike]] config_path

Path to the SimBA project config INI file. If None, then roi_coordinates_path and video_dir must be provided.

param Optional[Union[str, os.PathLike]] roi_coordinates_path

Path to an existing ROI definitions HDF5 file. Used when config_path is None.

param Optional[Union[str, os.PathLike]] pose_path

Path to pose-estimation data file. If provided, pose landmarks are overlaid on the video frame in the ROI interface.

param Optional[Union[str, os.PathLike]] video_dir

Directory containing project videos. Used to enable copying ROIs from other videos. Required when config_path is None.

param Optional[Any] roi_table_popup

Reference to the parent ROI table popup window. If provided, refresh_window() is called on close.

example

>>> ROI_ui(config_path=r"C: roubleshooting\mouse_open_field\project_folder\project_config.ini", video_path=r"C:     roubleshooting\mouse_open_field\project_folder
ideosVideo1.mp4”)
>>> ROI_ui(config_path=r"/mnt/c/troubleshooting/mouse_open_field/project_folder/project_config.ini", video_path=r"/mnt/c/troubleshooting/mouse_open_field/project_folder/videos/Video1.mp4")

ROI GUI Mixin

class simba.roi_tools.roi_ui_mixin.ROI_mixin(video_path, img_idx, main_frm, config_path=None, pose_data=None, animal_cnt=None, roi_coordinates_path=None)[source]

Bases: simba.mixins.config_reader.ConfigReader

ROI Ruler

class simba.roi_tools.roi_ruler.ROIRuler(img_window, thickness=None, second_thickness=None, clr=None, second_clr=None, tolerance=10, px_per_mm=None, info_label=None, img_scale_factor=1.0)[source]

Bases: object

Interactive Tkinter-based ruler tool for measuring distances on ROI images.

Parameters
  • img_window (Toplevel) – Tkinter Toplevel window containing an image label named ‘img_lbl’.

  • thickness (Optional[int]) – Thickness of the main line in pixels. If None, automatically calculated based on image size using optimal circle size ratio. Default None.

  • second_thickness (Optional[int]) – Thickness of the outline line in pixels. If None, set to 2x the main line thickness. Default None.

  • clr (Optional[Tuple[int, int, int]]) – RGB color tuple (R, G, B) for the main line. If None, uses default text color from TextOptions. Default None.

  • second_clr (Optional[Tuple[int, int, int]]) – RGB color tuple (R, G, B) for the outline line. If None, no outline is drawn. Default None.

  • tolerance (int) – Maximum distance in pixels from a line endpoint to detect a click for moving it. Also minimum line length required to register the line. Default 10.

  • px_per_mm (Optional[float]) – Pixels per millimeter conversion factor. If provided, calculates line length in millimeters. Must be > 0. Default None.

  • info_label (Optional[SimBALabel]) – Optional Tkinter label to display line length information. If provided, automatically updates with “RULER LENGTH: X mm, Y pixels” when line is drawn. Default None.

ROI GUI Utils

simba.roi_tools.roi_utils.change_roi_dict_video_name(roi_dict, video_name)[source]
simba.roi_tools.roi_utils.create_circle_entry(circle_selector, video_name, shape_name, clr_name, clr_bgr, thickness, ear_tag_size, px_conversion_factor)[source]
simba.roi_tools.roi_utils.create_duplicated_circle_entry(shape_entry, jump_size)[source]
simba.roi_tools.roi_utils.create_duplicated_polygon_entry(shape_entry, jump_size)[source]
simba.roi_tools.roi_utils.create_duplicated_rectangle_entry(shape_entry, jump_size)[source]
simba.roi_tools.roi_utils.create_polygon_entry(polygon_selector, video_name, shape_name, clr_name, clr_bgr, thickness, ear_tag_size, px_conversion_factor)[source]
simba.roi_tools.roi_utils.create_rectangle_entry(rectangle_selector, video_name, shape_name, clr_name, clr_bgr, thickness, ear_tag_size, px_conversion_factor)[source]
simba.roi_tools.roi_utils.get_circle_df_headers()[source]
simba.roi_tools.roi_utils.get_ear_tags_for_rectangle(center, width, height)[source]

Knowing the center, width, and height of rectangle, return its vertices.

Get ear tags for rectangle
Parameters
  • center (Tuple[int, int]) – The center x and y coordinates of the rectangle

  • width (int) – The width of the rectangle in pixels.

  • height (Tuple[int, int]) – The width of the rectangle in pixels.

Returns

Dictionary holding the name of the tag as key and coordinates as value.

Return type

Dict[str, Union[int, Tuple[int, int]]]

simba.roi_tools.roi_utils.get_half_circle_vertices(center, radius, direction, n_points=50)[source]

Generates vertices for a half-circle with a given radius and direction, centered at a specific point.

Get half circle vertices
Parameters
  • center (Tuple[int, int]) – A tuple (x, y) representing the center coordinates of the half-circle. Must contain exactly two numeric values.

  • radius (int) – The radius of the half-circle. Must be a positive integer.

  • direction (Literal['NORTH', 'SOUTH', 'WEST', 'EAST', 'NORTH-EAST', 'NORTH-WEST', 'SOUTH-EAST', 'SOUTH-WEST']) – The direction in which the half-circle is oriented (the side the curved arc faces).

  • n_points (Optional[int]) – The number of vertices used to approximate the half-circle. Defaults to 50.

Returns

A tuple containing vertices as array and dict.

Return type

Tuple[np.ndarray, Dict[str, Tuple[int, int]]]

simba.roi_tools.roi_utils.get_image_from_label(tk_lbl)[source]

Given a tkinter label with an image, retrieve image in array format

simba.roi_tools.roi_utils.get_polygon_df_headers()[source]
simba.roi_tools.roi_utils.get_pose_for_roi_ui(pose_path, video_path)[source]
simba.roi_tools.roi_utils.get_rectangle_df_headers()[source]
simba.roi_tools.roi_utils.get_roi_data(roi_path, video_name)[source]

Helper to read in ROI data from disk

simba.roi_tools.roi_utils.get_roi_data_for_video_name(roi_path, video_name)[source]
simba.roi_tools.roi_utils.get_roi_df_from_dict(roi_dict, video_name_nesting=False)[source]

Helper create DataFrames from a shape dictionary.

If nesting is True, then the roi_dict has video name, and shape name keys.

simba.roi_tools.roi_utils.get_roi_dict_from_dfs(rectangle_df, circle_df, polygon_df, video_name_nesting=False)[source]

Helper create dict from a shape dataframes.

simba.roi_tools.roi_utils.get_triangle_vertices(center, side_length, direction)[source]

Find equilateral triangle vertices knowing the center, direction and length side.

Get triangle vertices
Parameters
  • center (Tuple[int, int]) – A tuple (x, y) representing the center coordinates of the hexagon. Must contain exactly two numeric values.

  • side_length (int) – The length of each of the three sides in pixels.

  • direction (int) – The direction to point the vertices.

Returns

2-part tuple containing vertices as array and dict.

Return type

Tuple[np.ndarray, Dict[str, Tuple[int, int]]]

simba.roi_tools.roi_utils.get_vertices_hexagon(center, radius)[source]

Generates the vertices of a regular hexagon centered at a given point with a specified radius.

Get vertices hexagon
Parameters
  • center (Tuple[int, int]) – A tuple (x, y) representing the center coordinates of the hexagon. Must contain exactly two numeric values.

  • radius (int) – The radius of the hexagon, which represents the distance from the center to any of the vertices. Must be a positive integer.

Returns

A tuple containing vertices as array and dict.

Return type

Tuple[np.ndarray, Dict[str, Tuple[int, int]]]

simba.roi_tools.roi_utils.get_video_roi_data_from_dict(roi_dict, video_name)[source]
simba.roi_tools.roi_utils.insert_gridlines_on_roi_img(img, grid, color, thickness)[source]

Draw the outlines of a set of grid polygons onto an image.

Each polygon’s exterior is drawn as a closed polyline; useful for overlaying a tiling grid on an ROI frame.

Insert gridlines on roi img
Parameters
  • img (np.ndarray) – The image to draw on, as a (height, width, 3) BGR array.

  • grid (List[Polygon]) – A list of Shapely polygons whose exteriors are drawn. If None or empty, the image is returned unchanged.

  • color (Tuple[int, int, int]) – The BGR color of the gridlines.

  • thickness (int) – The line thickness in pixels.

Returns

The image with the gridlines drawn on it.

Return type

np.ndarray

simba.roi_tools.roi_utils.multiply_ROIs(filename, config_path=None, roi_coordinates_path=None, videos_dir=None)[source]

Reproduce ROIs in one video to all other videos in SimBA project.

param Union[str, os.PathLike] config_path

Path to SimBA project config file.

param Union[str, os.PathLike] filename

Path to video in project for which ROIs should be duplicated in the other videos in the project

return

None. The results are stored in the /project_folder/logs/measures\ROI_definitions.h5 of the SimBA project

example

>>> multiply_ROIs(config_path=r"C:  roubleshooting\mitra\project_folder\project_config.ini", filename=r"C:  roubleshooting\mitra\project_folder

ideosŁ_MA142_Gi_CNO_0514.mp4”)

simba.roi_tools.roi_utils.reset_video_ROIs(config_path, filename)[source]

Delete drawn ROIs for a single video in a SimBA project.

param Union[str, os.PathLike] config_path

Path to SimBA project config file.

param Union[str, os.PathLike] filename

Path to video in project for which ROIs should be duplicated in the other videos in the project

return

None. The results are stored in the /project_folder/logs/measures\ROI_definitions.h5 of the SimBA project

example

>>> reset_video_ROIs(config_path=r"C:       roubleshooting\mitra\project_folder\project_config.ini", filename=r"C:  roubleshooting\mitra\project_folder

ideosŁ_MA142_Gi_CNO_0514.mp4”)

simba.roi_tools.roi_utils.set_roi_metric_sizes(roi_dict, px_conversion_factor)[source]

Helper to update the metric attributes of a shape dictionary.

ROI Shape Selectors

ROI Rectangle Selector

class simba.roi_tools.roi_selector_polygon_tkinter.ROISelectorPolygon(img_window, thickness=10, vertice_size=2, clr=(147, 20, 255), tolerance=2)[source]

Bases: object

Class for selecting a polygonal region of interest (ROI) within an image or video frame. The selected region vertices are stored in self: polygon_vertices.

Parameters
  • img_window (Toplevel) – The Tkinter window where the image is displayed.

  • thickness (int) – Thickness of the polygon edges.

  • vertice_size (int) – Size of the vertices drawn.

  • clr (Tuple[int, int, int]) – RGB color for the polygon.

Example

ROI Circle Selector

class simba.roi_tools.roi_selector_circle_tkinter.ROISelectorCircle(img_window, thickness=10, clr=(147, 20, 255))[source]

Bases: object

A class to allow users to interactively select a Region of Interest (ROI) circle from an image displayed in a Tkinter window.

Parameters
  • img_window (Toplevel) – The Tkinter Toplevel window containing the image.

  • thickness (int) – The thickness of the ROI selection circle.

  • clr (Tuple[int, int, int]) – The color of the ROI circle rectangle in RGB format.

Example

ROI Polygon Selector

class simba.roi_tools.roi_selector_polygon_tkinter.ROISelectorPolygon(img_window, thickness=10, vertice_size=2, clr=(147, 20, 255), tolerance=2)[source]

Bases: object

Class for selecting a polygonal region of interest (ROI) within an image or video frame. The selected region vertices are stored in self: polygon_vertices.

Parameters
  • img_window (Toplevel) – The Tkinter window where the image is displayed.

  • thickness (int) – Thickness of the polygon edges.

  • vertice_size (int) – Size of the vertices drawn.

  • clr (Tuple[int, int, int]) – RGB color for the polygon.

Example

ROI Rectangle Selector (Tkinter)

class simba.roi_tools.roi_selector_rectangle_tkinter.ROISelector(img_window, thickness=10, clr=(147, 20, 255))[source]

Bases: object

A class to allow users to interactively select a Region of Interest (ROI) rectangle from an image displayed in a Tkinter window.

See also

For OpenCV based method, see simba.video_processors.roi_selector.ROISelector()

Parameters
  • (Toplevel) (img_window) – The Tkinter Toplevel window containing the image.

  • (int) (thickness) – The thickness of the ROI selection rectangle.

  • int]) (clr (Tuple[int, int,) – The color of the ROI selection rectangle in RGB format.

Example

ROI Interactive Bufferer

class simba.roi_tools.interactive_roi_bufferer.InteractiveROIBufferer(img_window, original_img, roi_dict, buffer_mm, px_per_mm, settings=None, hex_grid=None, rectangle_grid=None)[source]

Bases: object

Interactive Tkinter-based tool for buffering (expanding or shrinking) ROI shapes by specified metric millimeter by clicking on their tags.

Parameters
  • img_window (Toplevel) – Tkinter Toplevel window containing an image label named ‘img_lbl’ displaying the ROI image.

  • original_img (np.ndarray) – Original image as a numpy array in BGR format. Used as the base for redrawing ROIs.

  • roi_dict (dict) – Dictionary containing ROI definitions. Keys are ROI names (str), values are dictionaries with ROI properties including ‘Shape_type’, ‘Tags’, ‘Color BGR’, ‘Thickness’, ‘Ear_tag_size’, etc. Expected shape types: ‘Rectangle’, ‘Circle’, or ‘Polygon’.

  • buffer_mm (int) – Buffer distance in millimeters. Positive values expand the shape, negative values shrink it.

  • px_per_mm (float) – Pixels per millimeter conversion factor. Used to convert buffer_mm to pixels. Must be > 0.

  • settings (Optional[dict]) – Optional dictionary of ROI settings. If None, uses default ROI_SETTINGS values. Default None.

  • hex_grid (Optional[List[Polygon]]) – Optional list of Shapely Polygon objects representing a hexagon grid overlay. Default None.

  • rectangle_grid (Optional[List[Polygon]]) – Optional list of Shapely Polygon objects representing a rectangle grid overlay. Default None.

ROI Interactive Modifiers

ROI Interactive Modifier UI (Tkinter)

class simba.roi_tools.interactive_roi_modifier_tkinter.InteractiveROIModifier(img_window, original_img, roi_dict, settings=None, hex_grid=None, rectangle_grid=None)[source]

Bases: object

Interactive Tkinter-based GUI tool for modifying ROI (Region of Interest) shapes by clicking, dragging, and keyboard controls.

This class provides an interactive Tkinter interface for modifying existing ROI shapes (rectangles, circles, and polygons) through mouse and keyboard interactions. Users can resize, reposition, and reshape ROIs by clicking and dragging control points (tags/vertices), or by using arrow keys for fine-grained adjustments. The tool supports optional grid overlays for alignment assistance and updates the ROI dictionary in-place during interactions.

Note

  • The img_window must contain a Tkinter Label widget with the name ‘img_lbl’ that displays the image.

  • For rectangles: Click and drag corner tags, edge tags (top, bottom, left, right), or center tag to modify the shape.

  • For circles: Click and drag the center tag to move the circle, or the border tag to resize the radius.

  • For polygons: Click and drag individual vertex tags to reshape the polygon, or the center tag to move the entire polygon.

  • After selecting a tag, arrow keys can be used for pixel-precise adjustments (sensitivity controlled by settings).

  • All modifications are constrained to stay within the image boundaries.

  • The modified ROI dictionary is updated in-place during interactions.

See also

For an OpenCV-based version, see simba.roi_tools.interactive_modifier_ui.InteractiveROIModifier. For creating new ROIs from scratch, see simba.roi_tools.roi_selector_polygon_tkinter.ROISelectorPolygonTkinter() and simba.roi_tools.roi_selector_circle_tkinter.ROISelectorCircleTkinter().

Parameters
  • img_window (Toplevel) – Tkinter Toplevel window containing a Label widget named ‘img_lbl’ that displays the image with ROIs.

  • original_img (np.ndarray) – NumPy array representing the original, unmodified image without ROIs. Used as base for redrawing. Shape should be (height, width, channels) in BGR format.

  • roi_dict (dict) – Dictionary containing ROI definitions. Each key is an ROI name, and each value is a dictionary with shape-specific keys (e.g., ‘Shape_type’, ‘Name’, ‘Tags’, ‘Color BGR’, ‘Thickness’, etc.). Must include ‘Tags’ dictionary with control point coordinates for each ROI.

  • settings (Optional[dict]) – Optional dictionary of ROI display settings. If None, uses default settings from ROI_SETTINGS. Can include keys like ‘ROI_SELECT_CLR’, ‘LINE_TYPE’, ‘KEYBOARD_SENSITIVITY’, ‘OVERLAY_GRID_COLOR’.

  • hex_grid (Optional[List[Polygon]]) – Optional list of Shapely Polygon objects representing a hexagonal grid overlay. Gridlines will be drawn on the image for alignment assistance.

  • rectangle_grid (Optional[List[Polygon]]) – Optional list of Shapely Polygon objects representing a rectangular grid overlay. Gridlines will be drawn on the image for alignment assistance.

Example

>>> from tkinter import Toplevel, Label
>>> import cv2
>>> import numpy as np
>>> from simba.roi_tools.interactive_roi_modifier_tkinter import InteractiveROIModifier
>>> from simba.utils.enums import ROI_SETTINGS
>>> from PIL import Image, ImageTk
>>> # Load an image
>>> original_img = cv2.imread('path/to/image.jpg')
>>> img = original_img.copy()
>>> # Define a rectangle ROI
>>> rectangle_roi = {
...     'Shape_type': ROI_SETTINGS.RECTANGLE.value,
...     'Name': 'My_rectangle',
...     'Color BGR': (0, 0, 255),
...     'Thickness': 7,
...     'topLeftX': 100,
...     'topLeftY': 100,
...     'Bottom_right_X': 250,
...     'Bottom_right_Y': 250,
...     'Tags': {
...         'Top left tag': (100, 100),
...         'Bottom right tag': (250, 250),
...         'Center tag': (175, 175)
...     },
...     'Ear_tag_size': 15
... }
>>> roi_dict = {'My_rectangle': rectangle_roi}
>>> # Draw ROIs on image (using PlottingMixin or similar)
>>> # ... (drawing code here) ...
>>> # Create Tkinter window with image label
>>> root = Toplevel()
>>> root.title('DEFINE SHAPE')
>>> img_lbl = Label(root, name='img_lbl')
>>> img_lbl.pack()
>>> # Convert and display image
>>> img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
>>> pil_image = Image.fromarray(img_rgb)
>>> tk_image = ImageTk.PhotoImage(pil_image)
>>> img_lbl.configure(image=tk_image)
>>> img_lbl.image = tk_image
>>> # Create and initialize the interactive modifier
>>> modifier = InteractiveROIModifier(
...     img_window=root,
...     original_img=original_img,
...     roi_dict=roi_dict
... )
>>> root.mainloop()
>>> # After closing the window, roi_dict will contain the modified ROI coordinates

ROI Interactive Modifier UI - Legacy (OpenCV)

class simba.roi_tools.interactive_modifier_ui.InteractiveROIModifier(window_name, roi_dict, img, orginal_img, settings=None, tkinter_window=True, hex_grid=None, rectangle_grid=None)[source]

Bases: object

Interactive GUI tool for modifying ROI (Region of Interest) shapes by clicking and dragging.

This class provides an interactive interface for modifying existing ROI shapes (rectangles, circles, and polygons) by clicking and dragging control points (tags/vertices). Users can resize, reposition, and reshape ROIs through mouse interactions. The tool supports both OpenCV windows and Tkinter windows, and can display optional grid overlays for alignment assistance.

Note

  • For rectangles: Click and drag corner tags, edge tags (top, bottom, left, right), or center tag to modify the shape.

  • For circles: Click and drag the center tag to move the circle, or the border tag to resize the radius.

  • For polygons: Click and drag individual vertex tags to reshape the polygon, or the center tag to move the entire polygon.

  • All modifications are constrained to stay within the image boundaries.

  • The modified ROI dictionary is updated in-place during interactions.

See also

For creating new ROIs from scratch, see simba.roi_tools.roi_selector_polygon_tkinter.ROISelectorPolygonTkinter() and simba.roi_tools.roi_selector_circle_tkinter.ROISelectorCircleTkinter().

Parameters
  • window_name (str) – Name of the OpenCV window to display the interactive ROI editor.

  • roi_dict (dict) – Dictionary containing ROI definitions. Each key is an ROI name, and each value is a dictionary with shape-specific keys (e.g., ‘Shape_type’, ‘Name’, ‘Tags’, ‘Color BGR’, ‘Thickness’, etc.). Must include ‘Tags’ dictionary with control point coordinates for each ROI.

  • img (np.ndarray) – NumPy array representing the image with ROIs already drawn. Shape should be (height, width, channels).

  • orginal_img (np.ndarray) – NumPy array representing the original, unmodified image without ROIs. Used as base for redrawing. Shape should match img.

  • settings (Optional[dict]) – Optional dictionary of ROI display settings. If None, uses default settings from ROI_SETTINGS.

  • tkinter_window (bool) – If True, displays the interface in a Tkinter window. If False, uses OpenCV window. Default: True.

  • hex_grid (Optional[List[Polygon]]) – Optional list of Shapely Polygon objects representing a hexagonal grid overlay. Gridlines will be drawn on the image for alignment assistance.

  • rectangle_grid (Optional[List[Polygon]]) – Optional list of Shapely Polygon objects representing a rectangular grid overlay. Gridlines will be drawn on the image for alignment assistance.

Example

>>> import cv2
>>> import numpy as np
>>> from simba.roi_tools.interactive_modifier_ui import InteractiveROIModifier
>>> from simba.utils.enums import ROI_SETTINGS
>>> # Load an image
>>> img = cv2.imread('path/to/image.jpg')
>>> original_img = img.copy()
>>> # Define a rectangle ROI
>>> rectangle_roi = {
...     'Shape_type': ROI_SETTINGS.RECTANGLE.value,
...     'Name': 'My_rectangle',
...     'Color BGR': (0, 0, 255),
...     'Thickness': 7,
...     'topLeftX': 100,
...     'topLeftY': 100,
...     'Bottom_right_X': 250,
...     'Bottom_right_Y': 250,
...     'Tags': {
...         'Top left tag': (100, 100),
...         'Bottom right tag': (250, 250),
...         'Center tag': (175, 175)
...     },
...     'Ear_tag_size': 15
... }
>>> roi_dict = {'My_rectangle': rectangle_roi}
>>> # Draw ROIs on image
>>> # ... (drawing code here) ...
>>> # Create and run the interactive modifier
>>> modifier = InteractiveROIModifier(
...     window_name='DEFINE SHAPE',
...     roi_dict=roi_dict,
...     img=img,
...     orginal_img=original_img,
...     tkinter_window=False
... )
>>> modifier.run()
>>> # After closing the window, roi_dict will contain the modified ROI coordinates

ROI Data Import/Export

ROI CSV Importer

class simba.roi_tools.import_roi_csvs.ROIDefinitionsCSVImporter(config_path, rectangles_path=None, circles_path=None, polygon_path=None, append=False)[source]

Bases: simba.mixins.config_reader.ConfigReader

Import ROI definitions from CSV files into SimBA H5 format.

Converts human-readable CSV files containing ROI definitions (rectangles, circles, and/or polygons) into SimBA’s native H5 format for use in ROI analysis workflows. At least one CSV file path (rectangles, circles, or polygons) must be provided.

Note

ROI CSV files can be created from existing SimBA H5 ROI definitions using simba.utils.data.convert_roi_definitions().

param Union[str, os.PathLike] config_path

Path to SimBA project config file in Configparser format.

param Optional[Union[str, os.PathLike]] rectangles_path

Path to CSV file containing rectangle ROI definitions. If None, no rectangles will be imported.

param Optional[Union[str, os.PathLike]] circles_path

Path to CSV file containing circle ROI definitions. If None, no circles will be imported.

param Optional[Union[str, os.PathLike]] polygon_path

Path to CSV file containing polygon ROI definitions. If None, no polygons will be imported.

param bool append

If True, append ROI definitions to existing ROI_definitions.h5 file. If False, overwrite existing file. Default: False.

example

>>> importer = ROIDefinitionsCSVImporter(
...     config_path=r"project_folder/project_config.ini",
...     rectangles_path=r"logs/measures/rectangles_20251122110043.csv",
...     circles_path=r"logs/measures/circles_20251122110043.csv",
...     polygon_path=r"logs/measures/polygons_20251122110043.csv",
...     append=False
... )
>>> importer.run()
example

>>> importer = ROIDefinitionsCSVImporter(
...     config_path=r"C:    roubleshooting\mouse_open_field\project_folder\project_config.ini",
...     circles_path=r"C:   roubleshooting\mouse_open_field\project_folder\logs\measures\circles_20251122110043.csv",
...     rectangles_path=r"C:        roubleshooting\mouse_open_field\project_folder\logs\measures
ectangles_20251122110043.csv”,

… polygon_path=r”C: roubleshootingmouse_open_fieldproject_folderlogsmeasurespolygons_20251122110043.csv” … ) >>> importer.run()