Index
omero_annotate_ai.processing
#
Image and file processing functionality.
generate_patch_coordinates(image_shape: Tuple[int, int], patch_size: List[int], n_patches: int, random_patch: bool = True) -> Tuple[List[Tuple[int, int]], Tuple[int, int]]
#
Generate non-overlapping patch coordinates for an image.
CRUCIAL: Ensures patches do not overlap when generating multiple patches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_shape
|
Tuple[int, int]
|
(height, width) of the image |
required |
patch_size
|
List[int]
|
(height, width) of patches |
required |
n_patches
|
int
|
Number of patches to generate |
required |
random_patch
|
bool
|
Whether to generate random patches or grid-based patches |
True
|
Returns:
| Type | Description |
|---|---|
List[Tuple[int, int]]
|
Tuple containing: |
Tuple[int, int]
|
|
Tuple[List[Tuple[int, int]], Tuple[int, int]]
|
|
Source code in src/omero_annotate_ai/processing/image_functions.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
label_to_rois(label_img, z_slice, channel, timepoint, is_volumetric=False, patch_offset=None)
#
Convert a 2D or 3D label image to OMERO ROI shapes
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label_img
|
ndarray
|
2D labeled image or 3D labeled stack |
required |
z_slice
|
int or list
|
Z-slice index or list/range of Z indices |
required |
channel
|
int
|
Channel index |
required |
timepoint
|
int
|
Time point index |
required |
is_volumetric
|
bool
|
Whether the label image is 3D volumetric data |
False
|
patch_offset
|
Optional (x,y) offset for placing ROIs in a larger image |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
List of OMERO shape objects |
Source code in src/omero_annotate_ai/processing/image_functions.py
mask_to_contour(mask)
#
Converts a binary mask to a list of ROI coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
ndarray
|
binary mask |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
list of ROI coordinates |
Source code in src/omero_annotate_ai/processing/image_functions.py
prepare_bia_data_from_table(conn: Any, table_id: int, output_dir: Union[str, Path], config: Optional['AnnotationConfig'] = None, clean_existing: bool = False) -> Dict[str, Any]
#
Download the data referenced by an OMERO annotation table for a BIA export.
Loads the table, rebuilds the annotation records from it (each carries a unique
annotation_id) and writes, for every row that is processed and has a
label_id:
{output_dir}/annotation_input/{annotation_id}.tif- the image plane, patch or volume{output_dir}/annotation_output/{annotation_id}_mask.tif- the mask FileAnnotation
which is the layout :meth:AnnotationConfig.save_bia_package copies from. Set
config.output.output_directory = output_dir afterwards and package it.
Images are written at their native dtype - no 8-bit rescaling.
Rows that are unprocessed, or processed but carry no mask, are counted and skipped with a warning. Individual fetch failures are warned about and skipped too; only a missing/empty table is fatal.
On return, config.annotations holds only the exported records - the ones whose
image and mask both reached the disk. save_bia_package derives the BIA file lists
from every annotation in the config, so leaving a skipped row in place would list a
file that was never downloaded in the submission manifest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Any
|
OMERO connection ( |
required |
table_id
|
int
|
OMERO ID of the annotation table ( |
required |
output_dir
|
Union[str, Path]
|
Directory to write the |
required |
config
|
Optional['AnnotationConfig']
|
Annotation config, mutated in place: its |
None
|
clean_existing
|
bool
|
Remove existing |
False
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with |
Dict[str, Any]
|
and |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the table cannot be loaded or is empty. |
Source code in src/omero_annotate_ai/processing/bia_data.py
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | |
prepare_training_data_from_table(conn: Any, table_id: int, output_dir: Union[str, Path], training_name: str = 'micro_sam_training', validation_split: float = 0.2, clean_existing: bool = True, tmp_dir: Optional[Union[str, Path]] = None, verbose: bool = False, label_channel: Optional[int] = None, training_channels: Optional[List[int]] = None, upload_annotation_input: bool = False) -> Dict[str, Any]
#
Prepare training data from OMERO annotation table.
Downloads images and labels from OMERO based on annotation table data, splits into training/validation sets, and organizes into directory structure suitable for micro-SAM training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Any
|
OMERO connection object |
required |
table_id
|
int
|
ID of the annotation table in OMERO |
required |
output_dir
|
Union[str, Path]
|
Directory to store training data |
required |
training_name
|
str
|
Name for the training session (used in directory naming) |
'micro_sam_training'
|
validation_split
|
float
|
Fraction of data to use for validation (0.0-1.0) if not already defined in the table |
0.2
|
clean_existing
|
bool
|
Whether to clean existing output directories |
True
|
tmp_dir
|
Optional[Union[str, Path]]
|
Temporary directory for downloads (optional) |
None
|
verbose
|
bool
|
If True, show detailed debug information in console output |
False
|
label_channel
|
Optional[int]
|
Optional channel index for label/segmentation images. If provided and different from training_channels, downloads label channel images to *_annotation_input directories alongside the training data. |
None
|
training_channels
|
Optional[List[int]]
|
Optional list of channel indices for training input images. If different from label_channel, downloads from these channels for train_input and val_input. Currently uses first channel if multiple specified. |
None
|
upload_annotation_input
|
bool
|
If True and using separate channels, uploads the annotation-channel images back to OMERO as file annotations. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with paths to created directories: |
Dict[str, Any]
|
{ 'base_dir': Path to base output directory, 'train_input': Path to training images, 'train_label': Path to training labels (segmentation masks), 'train_annotation_input': Path to annotation-channel images (separate channels only), 'val_input': Path to validation images, 'val_label': Path to validation labels (segmentation masks), 'val_annotation_input': Path to annotation-channel validation images (separate channels only), 'stats': Statistics about the prepared data |
Dict[str, Any]
|
} |
Raises:
| Type | Description |
|---|---|
ValueError
|
If table not found or invalid parameters |
ImportError
|
If required dependencies missing |
Source code in src/omero_annotate_ai/processing/training_functions.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | |
process_label_plane(label_plane, z_slice, channel, timepoint, x_offset=0, y_offset=0)
#
Process a single 2D label plane to generate OMERO shapes with optional offset
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label_plane
|
2D label plane (numpy array) |
required | |
z_slice
|
Z-slice index |
required | |
channel
|
Channel index |
required | |
timepoint
|
Time point index |
required | |
x_offset
|
X offset for contour coordinates (default: 0) |
0
|
|
y_offset
|
Y offset for contour coordinates (default: 0) |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
List of OMERO shapes |
Source code in src/omero_annotate_ai/processing/image_functions.py
reorganize_local_data_for_training(config: AnnotationConfig, annotation_dir: Union[str, Path], output_dir: Optional[Union[str, Path]] = None, file_mode: Literal['copy', 'move', 'symlink'] = 'copy', clean_existing: bool = True, include_test: Optional[bool] = None, verbose: bool = False) -> Dict[str, Any]
#
Reorganize locally-stored annotation data into the training layout.
Works entirely offline - no OMERO connection required. Reads the annotation phase's folders (annotation_input/, model_input/, annotation_output/) and writes the training layout (train_input/, train_label/, val_input/, val_label/).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
AnnotationConfig
|
AnnotationConfig with populated annotations (carries the category) |
required |
annotation_dir
|
Union[str, Path]
|
Directory containing the annotation phase's output |
required |
output_dir
|
Optional[Union[str, Path]]
|
Target directory. Must NOT be inside annotation_dir - cleaning the
training layout there would delete the source images. Defaults to the sibling
|
None
|
file_mode
|
Literal['copy', 'move', 'symlink']
|
"copy" (default), "move", or "symlink". Symlinks fall back to a copy where they are unavailable (e.g. Windows without Developer Mode). |
'copy'
|
clean_existing
|
bool
|
Remove the training folders before writing |
True
|
include_test
|
Optional[bool]
|
Write a test split. None (default) auto-detects from the annotations. |
None
|
verbose
|
bool
|
Show detailed progress |
False
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with the created directories and statistics. Keys include base_dir, |
Dict[str, Any]
|
train_input, train_label, val_input, val_label and stats. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If config has no processed annotations, or output_dir is inside annotation_dir |
FileNotFoundError
|
If annotation_dir does not exist |
Source code in src/omero_annotate_ai/processing/training_functions.py
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 | |
run_training(training_config: Dict[str, Any], framework: str = 'microsam') -> Dict[str, Any]
#
Execute training with framework-specific implementation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
training_config
|
Dict[str, Any]
|
Configuration dictionary from setup_training() |
required |
framework
|
str
|
Training framework to use ("microsam", future: "cellpose", etc.) |
'microsam'
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary containing training results and model paths |
Raises:
| Type | Description |
|---|---|
ValueError
|
If framework is not supported |
ImportError
|
If required framework packages are not available |
Source code in src/omero_annotate_ai/processing/training_utils.py
setup_training(training_result: Dict[str, Any], model_name: str = '', model_type: str = 'vit_b_lm', epochs: int = 50, n_iterations: Optional[int] = None, batch_size: int = 2, learning_rate: float = 1e-05, patch_shape: Union[Tuple[int, int], Tuple[int, int, int]] = (512, 512), n_objects_per_batch: int = 25, save_every: int = 1000, validate_every: int = 500, **kwargs) -> Dict[str, Any]
#
Setup training configuration from training_result dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
training_result
|
Dict[str, Any]
|
Dictionary from prepare_training_data_from_table() |
required |
model_name
|
str
|
Name for the training session/model |
''
|
model_type
|
str
|
SAM model variant ("vit_b", "vit_l", "vit_h") |
'vit_b_lm'
|
epochs
|
int
|
Number of training epochs (primary training parameter) |
50
|
n_iterations
|
Optional[int]
|
Number of training iterations (calculated from epochs if None) |
None
|
batch_size
|
int
|
Training batch size |
2
|
learning_rate
|
float
|
Learning rate for training |
1e-05
|
patch_shape
|
Union[Tuple[int, int], Tuple[int, int, int]]
|
Input patch dimensions (height, width) or (slices, height, width) |
(512, 512)
|
n_objects_per_batch
|
int
|
Number of objects per batch for sampling |
25
|
save_every
|
int
|
Save checkpoint every N iterations |
1000
|
validate_every
|
int
|
Run validation every N iterations |
500
|
**kwargs
|
Framework-specific parameters |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary containing all training configuration and paths |
Raises:
| Type | Description |
|---|---|
ValueError
|
If training_result is missing required keys |
FileNotFoundError
|
If training directories don't exist |
Source code in src/omero_annotate_ai/processing/training_utils.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | |
validate_table_schema(df: pd.DataFrame, logger=None) -> None
#
Validate that the table has the required columns and basic data integrity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame from OMERO table |
required |
logger
|
Optional logger instance for logging messages |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If required columns are missing or data integrity issues found |