radioviz.tools.autocrop_tool
Autocrop tool implementation for automatic region detection and cropping.
This module provides functionality for automatically detecting regions in images and cropping them based on segmentation algorithms. It includes UI components for configuring segmentation parameters, visualizing detected regions, and performing the actual cropping operation.
The tool uses Otsu’s thresholding algorithm combined with region labeling to identify areas of interest in images. Users can configure various parameters such as threshold scaling, minimum region area, and padding to fine-tune the segmentation process.
Module Attributes
Type alias for the segmented area store. |
Functions
|
Performs segmentation and returns a list of padded RectangleExtent. |
|
Build the derived image label for a crop. |
|
Worker function to crop images based on regions. |
Classes
Tool class representing the autocrop functionality. |
|
|
Controller class for managing the autocrop tool workflow. |
|
Dialog window for configuring autocrop parameters and viewing results. |
|
Session class for managing the autocrop tool workflow. |
|
Enumeration of possible states for the autocrop tool session. |
|
Represents a request for image segmentation with specified parameters. |
|
Data class representing a segmented area in an image. |
|
Table model for displaying segmented areas. |
- class radioviz.tools.autocrop_tool.AutocropTool[source]
Bases:
Tool[AutocropToolController]Tool class representing the autocrop functionality.
This class defines the autocrop tool with its unique identifier, name, and description for integration into the tool system.
- create_controller(ctx: ToolContext) AutocropToolController[source]
Create a controller instance for this tool.
- Parameters:
ctx (ToolContext) – Tool context containing application services
- Returns:
New controller instance
- Return type:
- description: str = 'A tool to perform region cropping based on simple segmentation'
Description of what the tool does.
- name: str = 'Autocrop'
Human-readable name of the tool.
- overlays_to_be_registered: list[OverlaySpec] = [OverlaySpec(overlay_type='crop-with-label', overlay_role=<OverlayRole.Permanent: 'permanent'>, renderer=<function draw_crop_overlay>), OverlaySpec(overlay_type='crop-with-label', overlay_role=<OverlayRole.Highlight: 'highlight'>, renderer=<function draw_highlight_crop_overlay>)]
Overlays spec to be registered
- tool_id: str = 'autocrop'
Unique identifier for the autocrop tool.
- class radioviz.tools.autocrop_tool.AutocropToolController(tool_ctx: ToolContext, tool: Tool[AutocropToolController])[source]
Bases:
ToolController[ImageWindowController,AutocropToolSession]Controller class for managing the autocrop tool workflow.
This controller handles the interaction between the tool and its sessions, manages the tool’s state, and provides the necessary interfaces for user interactions.
Initialize the autocrop tool controller.
- Parameters:
tool_ctx (ToolContext) – Tool context containing application services
tool (Tool) – The autocrop tool instance
- _check_for_overlay(new_window_controller: SubWindowController[Any] | None) bool[source]
Check if the given window controller has an overlay that can be displayed.
This method verifies whether the provided window controller represents a derived image with ROI information that can be used to create an overlay on the original image. It checks the image origin, derivation details, and references the parent image to ensure the overlay can be properly established.
- Parameters:
new_window_controller (SubWindowController) – The window controller to check for overlay capability
- Returns:
True if the window controller can support an overlay, False otherwise
- Return type:
bool
- _check_for_shown_overlays(new_window_controller: SubWindowController[Any] | None) bool[source]
Check if there are any visible crop overlays in the given window controller.
This method examines the overlay manager of the specified window controller to determine if there are any crop overlays in the ‘autocrop’ group that are currently visible. This is used to enable or disable actions related to overlay visibility.
- Parameters:
new_window_controller (SubWindowController) – The window controller to check for visible overlays
- Returns:
True if there are visible crop overlays, False otherwise
- Return type:
bool
- _on_active_image_changed(new_window_controller: SubWindowController[Any] | None) None[source]
Handle changes to the active image window.
This method updates the tool’s ability to start based on whether the current window is an image window.
- Parameters:
new_window_controller (SubWindowController) – The new active window controller
- static _overlay_label_for(window_controller: ImageWindowController) str[source]
Return the overlay label for a derived crop window.
- Parameters:
window_controller (ImageWindowController) – The derived image window controller.
- Returns:
The short overlay label to use.
- Return type:
str
- _update_crop_overlay() None[source]
Update the overlay label when a cropped image window name changes.
This internal method is connected to the state changed signal of cropped image windows. It checks if the window is a derived image and updates the corresponding overlay label on the original image if it exists.
The method compares the current window name with the overlay label and updates it if they differ, ensuring that the overlay reflects the most recent name of the cropped image window.
- create_dock(parent_window: QWidget) None[source]
Create a dock widget for the tool.
- Parameters:
parent_window (QWidget) – Parent widget for the dock
- Returns:
None
- create_session(window_controller: ImageWindowController) AutocropToolSession[source]
Create a new autocrop tool session.
- Parameters:
window_controller (ImageWindowController) – Controller for the image window
- Returns:
New autocrop tool session
- Return type:
- hide_all_crops_overlays() None[source]
Hide all crop overlays in the active window.
This method retrieves all overlays associated with the ‘autocrop’ group from the active image window and hides any that are currently visible. It also updates the enable state of the corresponding action descriptor.
The method first checks if there is an active window, then gets all crop overlays from the window’s overlay manager. For each visible overlay, it sets the visibility to False. Finally, it updates the can_crop_overlay_be_hidden action descriptor to False.
Get the menu specifications for the tool.
- Returns:
List of menu specifications
- Return type:
List[ToolMenuSpec]
- on_autocrop_start() None[source]
Handle the start of the autocrop procedure.
This method activates the tool controller to begin the autocrop workflow.
- on_overlay_request() None[source]
Handle request to show or hide ROI overlay on the original image.
This method checks if the active image is a derived image with ROI information, and either creates a new overlay or toggles the visibility of an existing one on the original image window. The overlay displays the cropping region with a label.
The method retrieves the ROI from the active image’s derivation information, gets the target image window, and manages the overlay creation or visibility toggle based on whether the overlay already exists.
- procedure_can_start
Action descriptor for determining if the procedure can start.
- procedure_start_enable
Signal emitted to enable/disable the procedure start action.
- class radioviz.tools.autocrop_tool.AutocropToolDialog(tool_session: AutocropToolSession, parent: QWidget | None = None)[source]
Bases:
QDialogDialog window for configuring autocrop parameters and viewing results.
This dialog allows users to configure segmentation parameters, view the original image, and interact with detected regions through a table view. It provides controls for previewing segmentation results and initiating the cropping process.
Initialize the autocrop tool dialog.
- Parameters:
tool_session (AutocropToolSession) – The associated tool session
parent (QWidget) – Parent widget
- _on_downscale_ready(image: ndarray) None[source]
Handle completion of image downscaling.
- Parameters:
image (numpy.ndarray) – Downscaled image
- closeEvent(event: QCloseEvent) None[source]
Handle window close events.
- Parameters:
event (QCloseEvent) – Close event
- do_cropping() None[source]
Perform the final cropping operation.
This method initiates the cropping process with the configured parameters.
- downscale_image() None[source]
Downscale the image according to the selected factor.
This method uses the downscale_image service to resize the image.
- full_view() None[source]
Show the full image view.
This method resets the canvas view to show the entire image.
- get_image() None[source]
Retrieve and display the image for processing.
This method checks if image scaling is needed and displays the appropriate version of the image in the canvas.
- keyPressEvent(event: QKeyEvent) None[source]
Handle key press events.
- Parameters:
event (QKeyEvent) – Key press event
- normalize_view(x1: float, x2: float, y1: float, y2: float) tuple[float, float, float, float][source]
Normalize view coordinates to image boundaries.
- Parameters:
x1 (float) – Minimum x coordinate
x2 (float) – Maximum x coordinate
y1 (float) – Minimum y coordinate
y2 (float) – Maximum y coordinate
- Returns:
Normalized coordinates
- Return type:
tuple[float, float, float, float]
- on_add_crop_button_clicked() None[source]
Handle addition of manual crop selection.
This method initiates the manual crop selection mode.
- on_can_add_crop(enable: bool) None[source]
Enable or disable the add crop button.
- Parameters:
enable (bool) – Whether to enable the button
- on_can_remove_crop(enable: bool) None[source]
Enable or disable the remove crop button.
- Parameters:
enable (bool) – Whether to enable the button
- on_item_selected(selected: QItemSelection, deselected: QItemSelection) None[source]
Handle selection of items in the table view.
- Parameters:
selected (QItemSelection) – Selected indexes
deselected (QItemSelection) – Deselected indexes
- on_parameters_changed() None[source]
Handle changes to segmentation parameters.
This method updates the tool session with the current parameter values.
- on_remove_crop_button_clicked() None[source]
Handle removal of selected crop region.
This method removes the currently selected crop region from the session.
- on_scale_factor_change() None[source]
Handle change in downscale factor.
This method updates the displayed image when the downscale factor changes.
- plot() None[source]
Plot the current image in the canvas.
This method displays the image in the matplotlib canvas.
- preview() None[source]
Preview the segmentation results.
This method triggers the segmentation process with current parameters and displays the results.
- reject() None[source]
Handle rejection of the dialog.
This method handles the case where the user cancels the operation.
- zoom_view(bbox: RectangleExtent) None[source]
Zoom the view to show a specific bounding box.
- Parameters:
bbox (RectangleExtent) – Bounding box to zoom to
- class radioviz.tools.autocrop_tool.AutocropToolSession(tool_controller: AutocropToolController, window_controller: ImageWindowController)[source]
Bases:
BaseToolSession[AutocropToolController,ImageWindowController]Session class for managing the autocrop tool workflow.
This class manages the complete workflow of the autocrop tool including parameter configuration, segmentation, region editing, and image cropping.
Initialize the autocrop tool session.
- Parameters:
tool_controller (AutocropToolController) – The associated tool controller
window_controller (ImageWindowController) – The image window controller
- _activate_selector(selector: RectangleSelector) None[source]
Internal method to activate a selector.
- Parameters:
selector (RectangleSelector) – Selector to activate
- _do_cropping() None[source]
Perform the actual cropping operation.
This method initiates the cropping worker with the current image data and defined crop regions, then handles the results when they’re ready.
- _on_crops_ready(crops: list[CropResult]) None[source]
Handle completion of cropping operation.
This method processes the cropped images and opens them in new windows.
- Parameters:
crops (list[CropResult]) – List of cropped image results
- _start_segmentation(for_crop: bool) None[source]
Start the segmentation process.
- Parameters:
for_crop (bool) – Whether to prepare for cropping
- _start_segmentation_worker() None[source]
Start the segmentation worker thread.
This method creates and starts the segmentation worker with appropriate signal connections.
- _sync_crop(item: SegmentedAreaData) None[source]
Synchronize crop data with its visual representation.
This internal method ensures that the text overlay and visual elements of a segmented area are properly updated and re-added to the overlay manager.
- Parameters:
item (SegmentedAreaData) – The segmented area data to synchronize
- activate_selector(selector: RectangleSelector) None[source]
Activate a selector.
- Parameters:
selector (RectangleSelector) – Selector to activate
- add_new_item(extents: RectangleExtent) None[source]
Add a new crop region to the session.
This method creates a new segmented area data object and its associated visual elements (selector and overlay).
- Parameters:
extents (RectangleExtent) – The bounding box coordinates for the new crop region
- cancel_manual_new_crop() None[source]
Cancel the current manual crop selection.
This method discards the temporary selector and returns to the previous session state.
- cleanup() None[source]
Clean up resources and reset session state.
This method resets the tool session to its idle state by clearing all stored regions, resetting services, and updating the session mode.
- empty_store() None[source]
Clear all stored segmentation results and their associated visual elements.
This method removes all selectors and overlays from the canvas and resets the internal storage of segmentation results.
- finalize_manual_crop_definition(eclick: MouseEvent, erelease: MouseEvent) None[source]
Finalize the definition of a manually selected crop region.
This method processes the user-defined rectangle and adds it to the session as a new crop region.
- Parameters:
eclick (MouseEvent) – Mouse click event
erelease (MouseEvent) – Mouse release event
- has_crops() bool[source]
Check if there are any defined crop regions.
- Returns:
True if crops exist, False otherwise
- Return type:
bool
- on_cancel(reason: str) None[source]
Handle cancellation of the tool session.
- Parameters:
reason (str) – Reason for cancellation
- on_finish() None[source]
Finish the tool session.
This method cleans up resources when the session ends.
- on_segmentation_finished(bboxs: list[RectangleExtent]) None[source]
Handle completion of segmentation.
- Parameters:
bboxs (list[RectangleExtent]) – List of detected bounding boxes
- on_selector_change(click: MouseEvent, release: MouseEvent) None[source]
Handle changes to selector positions.
- Parameters:
click (MouseEvent) – Click event
release (MouseEvent) – Release event
- on_selector_mouse_press_event(event: MouseEvent) None[source]
Handle mouse press events on selectors.
- Parameters:
event (MouseEvent) – Mouse event
- on_selector_mouse_release_event(event: MouseEvent) None[source]
Handle mouse release events on selectors.
- Parameters:
event (MouseEvent) – Mouse event
- on_start() None[source]
Start the tool session.
This method initializes the dialog window and sets up connections.
- remove_selected_crop() None[source]
Remove the currently selected crop region.
This method removes the selected crop region from both the storage and the visual representation on the canvas.
- request_cropping() None[source]
Request to initiate the cropping process.
If no crop regions have been defined, this method starts segmentation to detect regions. Otherwise, it proceeds directly to cropping.
- request_preview() None[source]
Request a preview of the segmentation results.
This method starts the segmentation process without actually cropping.
- reset_services() None[source]
Reset color and item counter services.
This method resets the color service to its initial state and resets the item counter for generating new names.
- start_manual_crop_selection() None[source]
Initiate manual crop selection mode.
This method prepares the interface for manually defining crop regions by creating a new rectangle selector.
- update_editable_fields(data: SegmentedAreaData, index: int = 0) None[source]
Handle updates to editable fields in the segmented area store.
This method synchronizes changes made to segmented area data with the corresponding visual elements on the canvas and keeps derived labels aligned with user-provided crop names.
- Parameters:
data (SegmentedAreaData) – The segmented area data that was updated
index (int) – The index of the updated item in the store
- add_crop_enable
Signal emitted when add crop button state changes.
- can_add
Action descriptor for add crop capability.
- can_remove
Action descriptor for remove crop capability.
- no_scale_max_shape = (1024, 1024)
Maximum shape for images that don’t require scaling.
- remove_crop_enable
Signal emitted when remove crop button state changes.
- class radioviz.tools.autocrop_tool.AutocropToolSessionMode(*values)[source]
Bases:
StrEnumEnumeration of possible states for the autocrop tool session.
This enum defines the different modes the tool session can be in during the cropping workflow.
- static _generate_next_value_(name, start, count, last_values)
Return the lower-cased version of the member name.
- Adding = 'ADD_EXTRA'
Session is adding new manual crop regions.
- Cropping = 'CROPPING'
Session is performing the actual cropping operation.
- Editing = 'EDITING'
Session is editing existing selections.
- Idle = 'IDLE'
Session is idle, waiting for user action.
- Ready = 'READY'
Session is ready to proceed with cropping.
- Segmenting = 'SEGMENTING'
Session is currently performing segmentation.
- class radioviz.tools.autocrop_tool.SegmentationRequest(session_id: UUID, image: ndarray, threshold_factor: float, downscale_factor: int, remove_borders: bool, min_region_area: int, extra_padding: int)[source]
Bases:
objectRepresents a request for image segmentation with specified parameters.
This dataclass holds all the necessary parameters for performing image segmentation including the image data, threshold settings, and processing options.
- downscale_factor: int
Factor by which the image is downscaled before processing.
- extra_padding: int
Additional padding to add around detected regions.
- image: ndarray
Input image array for segmentation.
- min_region_area: int
Minimum area threshold for regions to be considered.
- remove_borders: bool
Whether to remove border-connected regions.
- session_id: UUID
Unique identifier for the segmentation session.
- threshold_factor: float
Factor to multiply with Otsu threshold for binary conversion.
- class radioviz.tools.autocrop_tool.SegmentedAreaData(name: str, derived_label: str, color: Color, bbox: RectangleExtent, downscale_factor: int, area_id: UUID | None = None)[source]
Bases:
objectData class representing a segmented area in an image.
This class holds information about a cropped region including its name, derived label, color, bounding box, and associated visual elements.
Initialize a segmented area data object.
- Parameters:
name (str) – Name of the segment
derived_label (str) – Label to use for derived image windows
color (Color) – Color for visualization
bbox (RectangleExtent) – Bounding box coordinates
downscale_factor (int) – Factor used for image downscaling
area_id (Optional[UUID]) – Unique identifier for the segment
- class radioviz.tools.autocrop_tool.SegmentedAreaTableModel(store: ItemStore[SegmentedAreaData], parent: QObject | None = None)[source]
Bases:
ItemModelTable model for displaying segmented areas.
This model provides data for the table view showing detected regions.
Initialize the segmented area table model.
- Parameters:
store (SegmentedAreaStore) – Store containing segmented areas
parent (QObject) – Parent object
- data_for(item: SegmentedAreaData, column: int, role: int = ItemDataRole.DisplayRole) Any[source]
Get data for a specific cell in the table.
- Parameters:
item (SegmentedAreaData) – The segmented area item
column (int) – Column index
role (Qt.ItemDataRole) – Item role
- Returns:
Data for the cell
- Return type:
Any
- flags(index: QModelIndex | QPersistentModelIndex, /) ItemFlag[source]
Return the item flags for the given index.
This method determines the behavior and properties of cells in the table view, such as whether they are selectable, editable, or enabled.
- Parameters:
index (QModelIndex) – Index of the item in the model
- Returns:
Item flags indicating the behavior of the cell
- Return type:
Qt.ItemFlag
- set_data_for(item: SegmentedAreaData, column: int, value: Any, role: int = ItemDataRole.DisplayRole) bool[source]
Set data for a specific item in the model.
This method handles updating the data for a segmented area item, particularly when the name column is edited.
- Parameters:
item (SegmentedAreaData) – The segmented area data item to update
column (int) – Column index of the data to update
value (Any) – New value to set
role (Qt.ItemDataRole) – Item role for the data
- Returns:
True if the data was successfully set, False otherwise
- Return type:
bool
- radioviz.tools.autocrop_tool.autocrop_segmentation_worker(request: SegmentationRequest) Generator[int, None, list[RectangleExtent]][source]
Performs segmentation and returns a list of padded RectangleExtent.
This worker function performs image segmentation using Otsu thresholding, region labeling, and filtering based on minimum area requirements. It yields progress updates during execution.
- Parameters:
request (SegmentationRequest) – Segmentation request parameters
- Returns:
List of padded rectangle extents representing detected regions
- Return type:
list[RectangleExtent]
- radioviz.tools.autocrop_tool.build_derived_label(base_name: str, crop_name: str, fallback_label: str | None = None) str[source]
Build the derived image label for a crop.
The default autocrop behaviour names regions
crop-<n>; those map to derived image labels with the-autocrop-<n>suffix before the extension. Custom names are appended verbatim (prefixed with a dash) to the base image name. Blank or whitespace-only names fall back tofallback_labelwhen provided; otherwise the default-autocropsuffix is used.- Parameters:
base_name (str) – Original image filename used as base for derived images
crop_name (str) – The user-visible crop name
fallback_label (str | None) – Existing derived label to preserve for empty names
- Returns:
Derived image label including extension
- Return type:
str
- radioviz.tools.autocrop_tool.crop_worker(image: ndarray, regions: list[SegmentedAreaData], scale: int) list[CropResult][source]
Worker function to crop images based on regions.
This function processes multiple regions and generates cropped images for each.
- Parameters:
image (numpy.ndarray) – Input image to crop
regions (list[SegmentedAreaData]) – List of segmented areas to crop
scale (int) – Scale factor for coordinates
- Returns:
List of crop results
- Return type:
list[CropResult]
- radioviz.tools.autocrop_tool.SegmentedAreaStore
Type alias for the segmented area store.
alias of
ItemStore[SegmentedAreaData]