API Reference
This document provides detailed API documentation for extending Granny with new analysis modules and interfaces.
Core Classes
Analysis Base Class
- class Analysis
Abstract base class for all analysis modules.
All custom analyses must inherit from this class and implement the abstract methods.
Location:
Granny/Analyses/Analysis.pyClass Attributes:
- __analysis_name__: str
Machine-readable name for the analysis. Used in CLI
--analysisargument.Example:
"segmentation","starch","blush"
Instance Attributes:
- in_params: Dict[str, Value]
Dictionary of input parameters. Keys are parameter names, values are Value objects.
- compatibility: Dict[str, Dict[str, str]]
Mapping of compatible analyses. Format:
{ "other_analysis_name": { "my_param": "their_return_value" } }
- metadata: List[Value]
List of metadata values automatically added to all analyses: -
dt- Analysis date/time -id- Unique analysis identifier (UUID) -path- Current directory path
Methods:
- __init__()
Initialize the analysis. Must call
super().__init__()first.Subclasses should: - Initialize instance variables - Define input parameters using Value objects - Set default values for parameters - Register parameters with
addInParam()
- addInParam(*params: Value) None
Add one or more input parameters to the analysis.
- Parameters
params (Value) – Variable number of Value objects to register
Example:
threshold = IntValue("th", "threshold", "Detection threshold") self.addInParam(threshold)
- getInParams() Dict[str, Value]
Get all input parameters.
- Returns
Dictionary of parameter names to Value objects
- Return type
Dict[str, Value]
- resetInParams() None
Clear all input parameters. Used when re-configuring an analysis instance.
- addRetValue(*values: Value) None
Add one or more return values that other analyses can use.
- Parameters
values (Value) – Variable number of Value objects
- getRetValues() Dict[str, Value]
Get all return values.
- Returns
Dictionary of return value names to Value objects
- Return type
Dict[str, Value]
- resetRetValues() None
Clear all return values.
- abstract performAnalysis() List[Image]
ABSTRACT: Perform the analysis on input images.
This method must be implemented by all subclasses.
- Returns
List of processed Image objects
- Return type
List[Image]
Implementation guidelines:
Load images from
input_imagesparameterProcess each image
Create result Image objects with results
Add metadata to result images
Save results (images and CSV)
Return list of result images
GrannyUI Base Class
- class GrannyUI
Abstract base class for user interfaces.
Location:
Granny/Interfaces/UI/GrannyUI.pyConstructor:
- __init__(parser: ArgumentParser)
Initialize the interface.
- Parameters
parser (argparse.ArgumentParser) – ArgumentParser instance for command-line arguments
Instance Attributes:
- parser: ArgumentParser
The argparse ArgumentParser instance used for handling command-line arguments.
Abstract Methods:
- abstract run() None
ABSTRACT: Execute the interface.
This method is called to start the interface and must be implemented by all subclasses.
Typical implementation: 1. Parse command-line arguments 2. Get user input (CLI args, GUI forms, web requests, etc.) 3. Instantiate selected analysis 4. Set analysis parameters from user input 5. Call
analysis.performAnalysis()6. Handle/display results
- abstract addProgramArgs() None
ABSTRACT: Add interface-specific arguments to the argument parser.
This method is called during initialization to set up command-line arguments that the interface needs.
Example:
def addProgramArgs(self): grp = self.parser.add_argument_group("My Interface Args") grp.add_argument("--my-option", type=str, help="...")
Value Classes
All Value classes inherit from the abstract Value base class and provide type-safe parameter handling.
Location: Granny/Models/Values/
Value Base Class
- class Value
Abstract base class for all parameter value types.
Location:
Granny/Models/Values/Value.pyConstructor:
- __init__(name: str, label: str, help: str)
- Parameters
name – Machine-readable parameter name
label – Human-readable label (used for CLI arguments)
help – Help text describing the parameter
Attributes:
- name: str
Machine-readable name for the value.
- label: str
Human-readable label. Becomes CLI argument:
--{label}
- help: str
Help text displayed to users.
- type: Type
Python type of the value (int, float, str, etc.).
- value: Any
The current value.
- is_set: bool
Whether the user has set this value.
- required: bool
Whether this parameter is required.
Methods:
- abstract validate(value: Any) bool
Validate that the value meets constraints. Must be implemented by subclasses.
- getName() str
Get the machine-readable name.
- getLabel() str
Get the human-readable label (used for CLI args).
- getHelp() str
Get the help text.
- getType() Type
Get the Python type of this value.
- setType(type: Type) None
Set the Python type.
- setValue(value: Any) None
Set the value. Calls
validate()first.
- getValue() Any
Get the current value.
- isSet() bool
Check if the user has set this value.
- setIsRequired(is_required: bool) None
Set whether this parameter is required.
- getIsRequired() bool
Check if this parameter is required.
IntValue
- class IntValue(Value)
Integer parameter type with min/max constraints.
Location:
Granny/Models/Values/IntValue.pyAdditional Methods:
- setMin(min_val: int) None
Set minimum allowed value.
- getMin() int
Get minimum allowed value.
- setMax(max_val: int) None
Set maximum allowed value.
- getMax() int
Get maximum allowed value.
Example:
threshold = IntValue("th", "threshold", "Detection threshold (0-255)") threshold.setMin(0) threshold.setMax(255) threshold.setValue(128) threshold.setIsRequired(False)
FloatValue
- class FloatValue(Value)
Floating-point parameter type with min/max constraints.
Location:
Granny/Models/Values/FloatValue.pyAdditional Methods:
- setMin(min_val: float) None
Set minimum allowed value.
- getMin() float
Get minimum allowed value.
- setMax(max_val: float) None
Set maximum allowed value.
- getMax() float
Get maximum allowed value.
Example:
alpha = FloatValue("alpha", "mask_alpha", "Mask transparency (0.0-1.0)") alpha.setMin(0.0) alpha.setMax(1.0) alpha.setValue(0.5)
StringValue
- class StringValue(Value)
String parameter type.
Location:
Granny/Models/Values/StringValue.pyExample:
model = StringValue("model", "model", "Model name or path") model.setValue("pome_fruit-v1_0")
BoolValue
- class BoolValue(Value)
Boolean flag parameter type.
Location:
Granny/Models/Values/BoolValue.pyExample:
debug = BoolValue("debug", "debug", "Enable debug mode") debug.setValue(False)
FileNameValue
- class FileNameValue(Value)
File path parameter type. Validates that path is a file or a valid model name.
Location:
Granny/Models/Values/FileNameValue.pyExample:
input_file = FileNameValue("input", "input_file", "Path to input file") input_file.setValue("/path/to/file.jpg")
FileDirValue
- class FileDirValue(Value)
Directory path parameter type. Creates directory if it doesn’t exist.
Location:
Granny/Models/Values/FileDirValue.pyExample:
output = FileDirValue("out", "output", "Output directory") output.setValue("./results/analysis") # Directory will be created
ImageListValue
- class ImageListValue(Value)
Image list/directory parameter type. Represents a directory containing images.
Location:
Granny/Models/Values/ImageListValue.pyExample:
input_images = ImageListValue( "input", "input", "Directory containing input images" ) input_images.setIsRequired(True) input_images.setValue("./demo/images")
MetaDataValue
- class MetaDataValue(Value)
Metadata storage parameter type. Used for results directories and metadata.
Location:
Granny/Models/Values/MetaDataValue.pyExample:
results = MetaDataValue( "results", "results", "Results output directory" ) results.setValue("./results/analysis_2024-01-01")
Image Classes
Image
- class Image
Base class for images in Granny.
Location:
Granny/Models/Images/Image.pyMethods:
- setImageFile(image_file: ImageFile) None
Set the ImageFile object containing the actual image data.
- getFileName() str
Get the image filename.
- addMetadata(metadata: List[dict]) None
Add metadata to the image.
- Parameters
metadata – List of metadata dictionaries with “name” and “value” keys
- getMetadata() List[dict]
Get all metadata attached to this image.
RGBImage
- class RGBImage(Image)
RGB color image type.
Location:
Granny/Models/Images/RGBImage.pyThis is the most common image type used in Granny analyses.
Example:
result_image = RGBImage() result_file = RGBImageFile() result_file.setImage(processed_array) result_file.setFileName("result.jpg") result_file.setFilePath("./output") result_image.setImageFile(result_file) result_image.addMetadata([{"name": "score", "value": 95.5}])
ImageFile Classes
ImageFile
- class ImageFile
Base class for image file handlers.
Location:
Granny/Models/IO/ImageIO.pyMethods:
- setImage(image: NDArray) None
Set the image data as a NumPy array.
- getImage() NDArray
Get the image data as a NumPy array.
- setFileName(name: str) None
Set the filename.
- getFileName() str
Get the filename.
- setFilePath(path: str) None
Set the directory path.
- getFilePath() str
Get the directory path.
RGBImageFile
- class RGBImageFile(ImageFile)
RGB image file handler. Uses OpenCV for loading/saving.
Location:
Granny/Models/IO/RGBImageFile.pyAutomatically handles image I/O in BGR format (OpenCV convention).
I/O Classes
ImageIO
- class ImageIO
Handles loading and saving of images.
Location:
Granny/Models/IO/ImageIO.pyMethods:
Scheduler Class
Scheduler
- class Scheduler
Manages dependencies between analyses and executes them in correct order.
Location:
Granny/Interfaces/Scheduler/Scheduler.pyUses a directed acyclic graph (DAG) with topological sorting to handle analysis dependencies.
Methods:
- __init__()
Initialize the scheduler.
- add_analysis(analysis: Analysis, dependencies: List[Analysis]) None
Add an analysis with its dependencies.
- Parameters
analysis – Analysis to add
dependencies – List of Analysis objects this analysis depends on
Example:
scheduler = Scheduler() segmentation = Segmentation() starch = StarchArea() scheduler.add_analysis(segmentation, []) scheduler.add_analysis(starch, [segmentation])
- schedule() List[Any]
Execute all analyses in dependency order.
- Returns
List of results from all analyses
Utility Functions
Analysis Discovery
To discover all available analyses:
from Granny.Analyses.Analysis import Analysis
# Get all analysis classes
analyses = Analysis.__subclasses__()
# Get analysis by name
for cls in analyses:
if cls.__analysis_name__ == "segmentation":
analysis = cls()
break
Parameter Introspection
To inspect parameters of an analysis:
analysis = StarchArea()
params = analysis.getInParams()
for param_name, param_obj in params.items():
print(f"Parameter: {param_obj.getLabel()}")
print(f" Type: {param_obj.getType()}")
print(f" Default: {param_obj.getValue()}")
print(f" Required: {param_obj.getIsRequired()}")
print(f" Help: {param_obj.getHelp()}")
if hasattr(param_obj, 'getMin'):
print(f" Range: {param_obj.getMin()} - {param_obj.getMax()}")
Common Patterns
Loading and Processing Images
from Granny.Models.IO.ImageIO import ImageIO
from Granny.Models.IO.RGBImageFile import RGBImageFile
# Load images
imageIO = ImageIO()
images = imageIO.load("./input", RGBImageFile)
# Process each image
for image in images:
img_array = image.getImageFile().getImage() # Get NumPy array
# Process img_array with OpenCV/NumPy
result_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
Creating Result Images
from Granny.Models.Images.RGBImage import RGBImage
from Granny.Models.IO.RGBImageFile import RGBImageFile
# Create result image
result_image = RGBImage()
result_file = RGBImageFile()
result_file.setImage(processed_array)
result_file.setFileName("output.jpg")
result_file.setFilePath("./results")
result_image.setImageFile(result_file)
# Add metadata
result_image.addMetadata([
{"name": "score", "value": 85.5},
{"name": "threshold", "value": 128}
])
result_image.addMetadata(self.metadata) # Add standard metadata
# Save
imageIO.save([result_image])
Setting Analysis Parameters
# Get parameters
params = analysis.getInParams()
# Clear and reset
analysis.resetInParams()
# Set each parameter
for param in params.values():
label = param.getLabel()
if label in user_values:
param.setValue(user_values[label])
# else: uses default value
analysis.addInParam(param)
Type Annotations
For better type checking, use these type hints:
from typing import List, Dict, Any, Optional
from numpy.typing import NDArray
from Granny.Models.Images.Image import Image
from Granny.Models.Values.Value import Value
def performAnalysis(self) -> List[Image]:
...
def getInParams(self) -> Dict[str, Value]:
...
def process_image(self, img: NDArray) -> NDArray:
...
See Also
Adding a New Analysis Module - Step-by-step guide for creating analyses
Adding a New Interface - Step-by-step guide for creating interfaces
Complete Example Analysis - Complete working example