radioviz.tools.align_image_tool
Align-image tool implementation.
This tool provides functionality for aligning images to a user-defined line. Users can draw a reference line on an image and rotate the image so that the line becomes horizontal or vertical. The tool supports both creating a new aligned image and applying the alignment in-place.
The module implements the following components:
AlignImageTool- Main tool entry pointAlignImageToolController- Controller handling tool logicAlignImageToolSession- Session managing the alignment workflowAlignImageDialog- UI dialog for alignment configurationalign_image_worker()- Background worker for image rotationcalculate_alignment_angle()- Utility for computing rotation angleslargest_valid_rectangle()- Utility for finding valid crop regions
Added in version 1.0.0.
Module Attributes
List of interpolation method labels paired with their order values. |
Functions
|
Rotate an image in a background thread according to alignment parameters. |
|
Compute the rotation angle needed to align line_geometry. |
|
Find the largest axis-aligned rectangle containing only valid pixels. |
Classes
|
Modal dialog for configuring image alignment parameters. |
|
Parameters required to compute image alignment. |
|
Output payload of the image alignment worker. |
Tool entry point for aligning images to a user-defined line. |
|
|
Controller for image alignment to a user-defined line. |
|
Session driving the align-image workflow for a single active image. |
- class radioviz.tools.align_image_tool.AlignImageDialog(parent: QDialog | None = None)[source]
Bases:
QDialogModal dialog for configuring image alignment parameters.
This dialog provides a user interface for selecting alignment options including the target orientation (horizontal or vertical), output mode (new image or in-place), interpolation method, and extension handling for rotated image boundaries.
The dialog is non-modal (modeless) to allow users to interact with the image canvas while the dialog is open.
- Variables:
align_horizontal (QRadioButton) – Radio button for horizontal alignment.
align_vertical (QRadioButton) – Radio button for vertical alignment.
output_new_image (QRadioButton) – Radio button for creating a new aligned image.
output_in_place (QRadioButton) – Radio button for applying alignment in-place.
interpolation_combo (QComboBox) – Combo box for selecting interpolation order.
extension_combo (QComboBox) – Combo box for selecting extension mode.
fill_value_spin (QDoubleSpinBox) – Spin box for specifying fill value.
ok_button (QPushButton) – Button to confirm alignment operation.
cancel_button (QPushButton) – Button to cancel the operation.
- _on_extension_changed() None[source]
Handle changes to the extension mode selection.
This method enables or disables the fill value spin box based on whether the user selected ‘fill_value’ or ‘crop_valid’ mode.
- class radioviz.tools.align_image_tool.AlignImageRequest(image: ndarray, line_geometry: LineGeometry, align_mode: str, interpolation_order: int, extension_mode: str, fill_value: float)[source]
Bases:
objectParameters required to compute image alignment.
This immutable dataclass encapsulates all the parameters needed to perform an image alignment operation. It is used to pass configuration from the session to the background worker.
- Variables:
image (np.ndarray) – The input image to be aligned, represented as a numpy array.
line_geometry (LineGeometry) – The geometry of the user-defined reference line.
align_mode (str) – Desired alignment direction; either
'horizontal'or'vertical'.interpolation_order (int) – Order of interpolation for image rotation (0-5).
extension_mode (str) – How to handle image extensions; either
'fill_value'or'crop_valid'.fill_value (float) – Value to use for filling extended regions when extension_mode is
'fill_value'.
- class radioviz.tools.align_image_tool.AlignImageResult(image: ndarray, angle_deg: float, crop_rect: tuple[int, int, int, int] | None)[source]
Bases:
objectOutput payload of the image alignment worker.
This immutable dataclass contains the result of an image alignment operation, including the rotated image and metadata about the transformation applied.
- Variables:
image (np.ndarray) – The aligned output image as a numpy array.
angle_deg (float) – The rotation angle applied in degrees. Positive values indicate counter-clockwise rotation.
crop_rect (tuple[int, int, int, int] | None) – The crop rectangle applied to the image when extension_mode is
'crop_valid', given as(x0, x1, y0, y1)coordinates. None if no cropping was performed.
- class radioviz.tools.align_image_tool.AlignImageTool[source]
Bases:
Tool[AlignImageToolController]Tool entry point for aligning images to a user-defined line.
This tool provides functionality for rotating images so that a user-defined line becomes horizontal or vertical. It follows the tool lifecycle pattern by creating a controller when activated and managing the alignment workflow through sessions.
The tool integrates with the main application menu under the Transform category and provides both modal dialog-based configuration and interactive line drawing on the image canvas.
- Variables:
id (uuid.UUID) – Unique identifier for this tool instance.
tool_id (str) – String identifier used for tool registration and lookup.
name (str) – Human-readable name displayed in menus and dialogs.
description (str) – Brief description of the tool’s functionality.
_controller (Optional[AlignImageToolController]) – The controller instance created by this tool.
Initialize the align image tool.
This constructor initializes the tool and sets up the controller reference to None until create_controller is called.
- create_controller(ctx: ToolContext) AlignImageToolController[source]
Create and return the tool controller.
This method is called when the tool is activated. It creates an AlignImageToolController that manages the tool’s business logic.
- Parameters:
ctx (ToolContext) – The tool context providing access to application services.
- Returns:
The created tool controller.
- Return type:
- description: str = 'Rotate an image to align a feature to horizontal or vertical.'
Tooltip or description
- name: str = 'Align Image'
Human-readable name
- tool_id: str = 'alignline'
Unique identifier of the tool
- class radioviz.tools.align_image_tool.AlignImageToolController(tool_ctx: ToolContext, tool: Tool[AlignImageToolController])[source]
Bases:
ToolController[ImageWindowController,AlignImageToolSession]Controller for image alignment to a user-defined line.
This controller manages the image alignment tool, handling the creation of alignment sessions, dependency tracking for in-place modifications, and committing alignment results. It follows the layered architecture by coordinating between the tool session and the image window controller.
The controller provides signals and action descriptors for enabling/disabling the tool menu entry based on whether an image is currently active.
- Variables:
active_session (Optional[AlignImageToolSession]) – The currently active alignment session, if any.
procedure_can_start (ActionDescriptor) – Action descriptor controlling whether the alignment procedure can be started.
Initialize the alignment tool controller.
- Parameters:
tool_ctx (ToolContext) – The tool context providing access to application services.
tool (Tool) – The tool instance that owns this controller.
- _create_new_image(image_controller: ImageWindowController, request: AlignImageRequest, result: AlignImageResult) None[source]
Create a new image window with the aligned image.
This method creates a new ImageWindowController with the aligned image data and appropriate source metadata, then emits a request to create a new window.
- Parameters:
image_controller (ImageWindowController) – The original image controller.
request (AlignImageRequest) – The original alignment request parameters.
result (AlignImageResult) – The alignment result containing the rotated image.
- _dependent_derived_images(image_controller: ImageWindowController) list[ImageWindowController][source]
Find all derived images that depend on the given image.
This method searches through the window manager’s window list to find all image windows that were derived from the given image controller.
- Parameters:
image_controller (ImageWindowController) – The image controller to find dependents for.
- Returns:
List of derived image controllers that depend on the given image.
- Return type:
list[ImageWindowController]
- _invalidate_dependencies(image_controller: ImageWindowController) None[source]
Invalidate and close all items that depend on the given image.
This method is called when an in-place alignment is performed. It notifies other tools and closes derived image windows that depend on the modified image.
- Parameters:
image_controller (ImageWindowController) – The image controller whose dependencies should be invalidated.
- _on_active_image_changed(new_window_controller: SubWindowController[Any] | None) None[source]
Handle changes to the active image controller.
This method is called when the active image window changes. It updates the procedure_can_start action based on whether the new active window is an image window controller.
- Parameters:
new_window_controller (SubWindowController) – The newly active sub-window controller.
- commit_result(image_controller: ImageWindowController, request: AlignImageRequest, result: AlignImageResult, output_mode: str) None[source]
Commit the alignment result to the image controller.
This method handles both creating a new aligned image and applying the alignment in-place. For in-place operations, it also invalidates any dependent items.
- Parameters:
image_controller (ImageWindowController) – The image controller to commit the result to.
request (AlignImageRequest) – The original alignment request parameters.
result (AlignImageResult) – The alignment result containing the rotated image.
output_mode (str) – The output mode, either
'new_image'or'in_place'.
- count_inplace_dependencies(image_controller: ImageWindowController) int[source]
Count the number of items that depend on the given image.
This method is used to warn users before performing an in-place alignment that would invalidate dependent items.
- Parameters:
image_controller (ImageWindowController) – The image controller to check dependencies for.
- Returns:
The total count of dependent items.
- Return type:
int
- create_dock(parent_window: QWidget) None[source]
Create a dock widget for this tool.
This tool does not use a dock widget, so this method returns None.
- Parameters:
parent_window – The parent window to attach the dock to.
- Returns:
None, as this tool does not use a dock.
- create_session(window_controller: ImageWindowController) AlignImageToolSession[source]
Create a new alignment session for the given window controller.
- Parameters:
window_controller (SubWindowController) – The window controller to create a session for.
- Returns:
A new AlignImageToolSession instance.
- Return type:
- inplace_dependency_summary(image_controller: ImageWindowController) str[source]
Generate a summary of items that depend on the given image.
This method creates a human-readable summary of all items that would be affected by an in-place alignment operation.
- Parameters:
image_controller (ImageWindowController) – The image controller to get dependencies for.
- Returns:
A formatted string summarizing the dependent items.
- Return type:
str
Get the menu specifications for this tool.
- Returns:
List of menu specifications defining the tool’s menu entries.
- Return type:
List[ToolMenuSpec]
- class radioviz.tools.align_image_tool.AlignImageToolSession(tool_controller: AlignImageToolController, window_controller: ImageWindowController)[source]
Bases:
BaseToolSession[AlignImageToolController,ImageWindowController]Session driving the align-image workflow for a single active image.
This session class manages the complete alignment workflow, including the configuration dialog, the line selector for defining the reference line, and the background worker that performs the rotation. It also handles cleanup of UI elements and error reporting.
The session follows the tool session lifecycle: it is created when the tool is activated, started via
on_start(), and cleaned up viaon_finish()oron_cancel().- Variables:
dialog_window (Optional[AlignImageDialog]) – The alignment configuration dialog instance.
line_selector (Optional[LineSelector]) – The interactive line selector for defining the reference line.
Initialize a new alignment tool session.
- Parameters:
tool_controller (AlignImageToolController) – The tool controller that owns this session.
window_controller (ImageWindowController) – The image window controller to operate on.
- Raises:
TypeError – If window_controller is not an ImageWindowController.
- _close_dialog() None[source]
Close the alignment configuration dialog.
This method closes and clears the reference to the dialog window.
- _on_confirmed() None[source]
Handle dialog confirmation event.
This method is called when the user clicks OK in the alignment dialog. It creates the alignment request, checks for dependencies if in-place mode is selected, and starts the background worker for image rotation.
- _on_error(error: Exception) None[source]
Handle errors from the alignment worker.
This method is called when the background worker encounters an error. It displays an error message and cancels the session.
- Parameters:
error (Exception) – The exception that was raised by the worker.
- _on_result_ready(result: AlignImageResult) None[source]
Handle successful completion of the alignment worker.
This method is called when the background worker successfully completes the image rotation. It commits the result to the controller and finishes the session.
- Parameters:
result (AlignImageResult) – The alignment result containing the rotated image and metadata.
- _on_selector_canceled() None[source]
Handle line selector cancellation event.
This callback is triggered when the user cancels the line selector operation. It disables the OK button in the dialog.
- _on_selector_created() None[source]
Handle line selector creation event.
This callback is triggered when the user successfully creates a line selector on the image. It enables the OK button in the dialog to allow the user to proceed with the alignment.
- _teardown_line_selector() None[source]
Clean up the line selector.
This method removes the line selector from the canvas and disconnects its signals to prevent memory leaks.
- on_cancel(reason: str) None[source]
Cancel the alignment session.
This method is called when the session is cancelled. It cleans up the line selector and closes the dialog.
- Parameters:
reason (str) – The reason for cancellation.
- radioviz.tools.align_image_tool._cast_like_input(rotated: ndarray, dtype: dtype) ndarray[source]
Cast rotated image data back to the original input dtype.
This function ensures that the rotated image data is converted to the specified dtype while preserving reasonable value ranges. For integer types, values are rounded to the nearest integer and clipped to the valid range for that type to prevent overflow.
- Parameters:
rotated (np.ndarray) – Rotated image data to be cast.
dtype (np.dtype) – Desired output data type (typically the original image dtype).
- Returns:
Image data cast to the specified dtype. For integer types, values are rounded and clipped to the valid range. Float types are cast directly.
- Return type:
np.ndarray
- radioviz.tools.align_image_tool.align_image_worker(request: AlignImageRequest) AlignImageResult[source]
Rotate an image in a background thread according to alignment parameters.
This function is decorated with
@thread_workerto execute the image rotation operation in a separate thread, keeping the UI responsive during potentially expensive transformations. It handles the complete alignment workflow including angle calculation, rotation, optional cropping, and dtype conversion.- Parameters:
request (AlignImageRequest) – Parameters required to compute image alignment.
- Returns:
Result of the alignment containing the rotated image, the applied rotation angle in degrees, and optional crop rectangle coordinates.
- Return type:
- radioviz.tools.align_image_tool.calculate_alignment_angle(line_geometry: LineGeometry, align_mode: str) float[source]
Compute the rotation angle needed to align line_geometry.
The selector geometry is expressed in image coordinates (x to the right, y to the bottom). The function preserves line direction: opposite selector directions produce angles differing by 180 degrees.
- Parameters:
line_geometry (LineGeometry) – The line geometry to be aligned.
align_mode (str) – Desired alignment mode; either
'horizontal'or'vertical'.
- Returns:
Rotation angle in degrees. Positive values rotate the image counter-clockwise, negative values rotate clockwise.
- Return type:
float
- radioviz.tools.align_image_tool.largest_valid_rectangle(mask: ndarray) tuple[int, int, int, int] | None[source]
Find the largest axis-aligned rectangle containing only valid pixels.
This function uses a histogram-based algorithm to efficiently find the largest rectangle in a binary mask where all pixels are True (valid). The algorithm runs in O(n*m) time for an n x m mask.
- Parameters:
mask (np.ndarray) – 2D boolean mask where True indicates valid pixels.
- Returns:
Tuple of rectangle coordinates
(x0, x1, y0, y1)defining the largest valid rectangle, or None if no valid area exists.- Return type:
tuple[int, int, int, int] | None
- Raises:
ValueError – If mask is not a 2-dimensional array.
- radioviz.tools.align_image_tool.INTERPOLATION_LABELS: list[tuple[str, int]] = [('Nearest-neighbor', 0), ('Bi-linear', 1), ('Bi-quadratic', 2), ('Bi-cubic', 3), ('Bi-quartic', 4), ('Bi-quintic', 5)]
List of interpolation method labels paired with their order values.
This module-level variable provides a mapping between human-readable interpolation method names and their corresponding order values used by scikit-image’s rotation function.
- Variables:
int]] (list[tuple[str,) – List of tuples containing (label, order) pairs.