# UI Support

{% hint style="info" %}
This API Reference is based on DeGirum Tools version 1.2.0.
{% endhint %}

## UI Support Module Overview <a href="#ui-support-module-overview" id="ui-support-module-overview"></a>

This module provides a comprehensive set of utilities for user interface operations, including image display, text rendering, progress tracking, and performance monitoring. It supports both traditional GUI environments and Jupyter notebooks.

Key Features

* **Image Display**: Show images in GUI windows or Jupyter notebooks
* **Text Rendering**: Draw text with customizable fonts, colors, and positions
* **Progress Tracking**: Display progress bars with speed and percentage
* **Performance Monitoring**: Measure and display FPS
* **Environment Detection**: Auto-detect and adapt to different display environments
* **Color Utilities**: Convert between color spaces and compute complementary colors

Typical Usage

1. Use `Display` class for showing images in any environment
2. Draw text on images with `put_text()`
3. Track progress with `Progress` class
4. Monitor performance with `FPSMeter`
5. Stack images with `stack_images()`

Integration Notes

* Works in both GUI and Jupyter notebook environments
* Automatically detects and adapts to the display environment
* Supports both OpenCV and PIL image formats
* Handles video files in Jupyter notebooks
* Provides consistent interface across different platforms

Key Classes

* `Display`: Main class for showing images and videos
* `Progress`: Progress bar with speed and percentage display
* `FPSMeter`: Frames per second measurement
* `Timer`: Simple timing utility
* `stdoutRedirector`: Context manager for redirecting stdout

Configuration Options

* Font settings (face, scale, thickness)
* Color schemes (RGB/BGR)
* Progress bar appearance
* Display window properties

## Functions <a href="#functions" id="functions"></a>

#### deduce\_text\_color(bg\_color) <a href="#deduce_text_color" id="deduce_text_color"></a>

`deduce_text_color(bg_color)`

Return a readable text color.

Chooses black or white based on the luminance of `bg_color` so that text remains legible.

Parameters:

| Name       | Type    | Description                               | Default    |
| ---------- | ------- | ----------------------------------------- | ---------- |
| `bg_color` | `tuple` | Background color as an `(R, G, B)` tuple. | *required* |

Returns:

| Type                   | Description                                |
| ---------------------- | ------------------------------------------ |
| `Tuple[int, int, int]` | `(R, G, B)` value for black or white text. |

#### color\_complement(color) <a href="#color_complement" id="color_complement"></a>

`color_complement(color)`

Return the complement of an RGB color.

Parameters:

| Name    | Type            | Description                     | Default    |
| ------- | --------------- | ------------------------------- | ---------- |
| `color` | `tuple \| list` | Color specified as `(R, G, B)`. | *required* |

Returns:

| Type                   | Description                                |
| ---------------------- | ------------------------------------------ |
| `Tuple[int, int, int]` | Complementary color in `(R, G, B)` format. |

#### rgb\_to\_bgr(color) <a href="#rgb_to_bgr" id="rgb_to_bgr"></a>

`rgb_to_bgr(color)`

Convert an RGB color tuple to BGR.

Parameters:

| Name    | Type    | Description                  | Default    |
| ------- | ------- | ---------------------------- | ---------- |
| `color` | `tuple` | Color in `(R, G, B)` format. | *required* |

Returns:

| Type                   | Description                                      |
| ---------------------- | ------------------------------------------------ |
| `Tuple[int, int, int]` | Color in `(B, R, G)` order for OpenCV functions. |

#### ipython\_display(obj, ...) <a href="#ipython_display" id="ipython_display"></a>

`ipython_display(obj, clear=False, display_id=None)`

Display an object in IPython notebooks.

Parameters:

| Name         | Type            | Description                                                                                                            | Default    |
| ------------ | --------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------- |
| `obj`        | `Any`           | Object to display. Supported types are `PIL.Image`, `numpy.ndarray` images, or a string path/URL to an image or video. | *required* |
| `clear`      | `bool`          | Whether to clear the previous output. Defaults to `False`.                                                             | `False`    |
| `display_id` | `Optional[str]` | Custom display ID to update an existing output.                                                                        | `None`     |

Raises:

| Type        | Description                        |
| ----------- | ---------------------------------- |
| `Exception` | If the object type is unsupported. |

#### put\_text(image, ...) <a href="#put_text" id="put_text"></a>

`put_text(image, label, corner_xy, *, corner_position=CornerPosition.TOP_LEFT, font_color, bg_color=None, font_face=cv2.FONT_HERSHEY_PLAIN, font_scale=1, font_thickness=1, line_spacing=1)`

Draw text on an image with customizable appearance and positioning.

This function draws text on an OpenCV image with support for multi-line text, background colors, and automatic positioning. The text can be placed relative to any corner of the image, and will automatically adjust to stay within image boundaries.

Parameters:

| Name              | Type              | Description                                                                        | Default              |
| ----------------- | ----------------- | ---------------------------------------------------------------------------------- | -------------------- |
| `image`           | `ndarray`         | Input image in OpenCV format (BGR).                                                | *required*           |
| `label`           | `str`             | Text to draw. Can contain newlines for multi-line text.                            | *required*           |
| `corner_xy`       | `tuple`           | Base coordinates (x, y) for text placement.                                        | *required*           |
| `corner_position` | `CornerPosition`  | Position of text relative to corner\_xy. Defaults to TOP\_LEFT.                    | `TOP_LEFT`           |
| `font_color`      | `tuple`           | Text color in RGB format.                                                          | *required*           |
| `bg_color`        | `Optional[tuple]` | Background color in RGB format. If None, no background is drawn. Defaults to None. | `None`               |
| `font_face`       | `int`             | OpenCV font face. Defaults to FONT\_HERSHEY\_PLAIN.                                | `FONT_HERSHEY_PLAIN` |
| `font_scale`      | `float`           | Font size multiplier. Defaults to 1.                                               | `1`                  |
| `font_thickness`  | `int`             | Font thickness in pixels. Defaults to 1.                                           | `1`                  |
| `line_spacing`    | `float`           | Multiplier for line spacing. Defaults to 1.                                        | `1`                  |

Returns:

| Type      | Description                  |
| --------- | ---------------------------- |
| `ndarray` | Image with text drawn on it. |

#### stack\_images(image1, ...) <a href="#stack_images" id="stack_images"></a>

`stack_images(image1, image2, dimension='horizontal', downscale=None, labels=None, font_color=(255, 255, 255))`

Stack two images either horizontally or vertically.

Parameters:

| Name         | Type               | Description                                                 | Default           |
| ------------ | ------------------ | ----------------------------------------------------------- | ----------------- |
| `image1`     | `ndarray \| Image` | First image.                                                | *required*        |
| `image2`     | `ndarray \| Image` | Second image.                                               | *required*        |
| `dimension`  | `str`              | `"horizontal"` or `"vertical"`. Defaults to `"horizontal"`. | `'horizontal'`    |
| `downscale`  | `Optional[float]`  | Scaling factor for both images if less than `1.0`.          | `None`            |
| `labels`     | `Optional[list]`   | Optional text labels for `image1` and `image2`.             | `None`            |
| `font_color` | `tuple`            | RGB color for labels. Defaults to white.                    | `(255, 255, 255)` |

Returns:

| Type                    | Description                                       |
| ----------------------- | ------------------------------------------------- |
| `Union[ndarray, Image]` | Combined image with optional resizing and labels. |

## Classes <a href="#classes" id="classes"></a>

## CornerPosition <a href="#cornerposition" id="cornerposition"></a>

`CornerPosition`

Bases: `Enum`

Enumeration of possible corner positions for text placement.

This enum defines the possible positions where text can be placed relative to a reference point in an image. The AUTO option will automatically choose the best corner based on the reference point's position.

Attributes:

| Name           | Type  | Description                                    |
| -------------- | ----- | ---------------------------------------------- |
| `AUTO`         | `int` | Automatically choose the best corner position. |
| `TOP_LEFT`     | `int` | Place text at the top-left corner.             |
| `TOP_RIGHT`    | `int` | Place text at the top-right corner.            |
| `BOTTOM_LEFT`  | `int` | Place text at the bottom-left corner.          |
| `BOTTOM_RIGHT` | `int` | Place text at the bottom-right corner.         |

## FPSMeter <a href="#fpsmeter" id="fpsmeter"></a>

`FPSMeter`

Frame rate measurement utility.

This class provides functionality to measure and track frames per second (FPS) over a configurable window of time. It's useful for monitoring performance in video processing and real-time applications.

Attributes:

| Name      | Type  | Description                                   |
| --------- | ----- | --------------------------------------------- |
| `avg_len` | `int` | Number of samples to use for FPS calculation. |

### FPSMeter Methods <a href="#fpsmeter-methods" id="fpsmeter-methods"></a>

#### \_\_init\_\_(avg\_len=100) <a href="#init" id="init"></a>

`__init__(avg_len=100)`

Constructor.

Parameters:

| Name      | Type  | Description                                                    | Default |
| --------- | ----- | -------------------------------------------------------------- | ------- |
| `avg_len` | `int` | Number of samples to use for FPS calculation. Defaults to 100. | `100`   |

#### fps <a href="#fps" id="fps"></a>

`fps()`

Return current average FPS.

#### record <a href="#record" id="record"></a>

`record()`

Record timestamp and update average duration.

Returns current average FPS.

#### reset <a href="#reset" id="reset"></a>

`reset()`

Reset accumulators.

## Display <a href="#display" id="display"></a>

`Display`

Display manager for showing images and videos in various environments.

This class provides a unified interface for displaying images and videos in both GUI windows and Jupyter notebooks. It automatically detects the display environment and adapts its behavior accordingly.

Attributes:

| Name          | Type            | Description                                      |
| ------------- | --------------- | ------------------------------------------------ |
| `window_name` | `str`           | Name of the display window in GUI mode.          |
| `show_fps`    | `bool`          | Whether to show FPS counter on displayed images. |
| `width`       | `Optional[int]` | Target width for displayed images.               |
| `height`      | `Optional[int]` | Target height for displayed images.              |

### Attributes <a href="#attributes" id="attributes"></a>

#### window\_name: str <a href="#window_name-str" id="window_name-str"></a>

`window_name: str`

`property`

Get the window name.

Returns:

| Type  | Description                 |
| ----- | --------------------------- |
| `str` | Name of the display window. |

### Display Methods <a href="#display-methods" id="display-methods"></a>

#### \_\_init\_\_(capt='', ...) <a href="#init" id="init"></a>

`__init__(capt='<image>', show_fps=True, w=None, h=None)`

Constructor.

Parameters:

| Name       | Type            | Description                                                            | Default     |
| ---------- | --------------- | ---------------------------------------------------------------------- | ----------- |
| `capt`     | `str`           | Window title. Defaults to "".                                          | `'<image>'` |
| `show_fps` | `bool`          | Whether to show FPS counter. Defaults to True.                         | `True`      |
| `w`        | `Optional[int]` | Initial window width in pixels; None for autoscale. Defaults to None.  | `None`      |
| `h`        | `Optional[int]` | Initial window height in pixels; None for autoscale. Defaults to None. | `None`      |

Raises:

| Type        | Description               |
| ----------- | ------------------------- |
| `Exception` | If window title is empty. |

#### show(img, ...) <a href="#show" id="show"></a>

`show(img, waitkey_delay=1)`

Show image or model result.

Parameters:

| Name            | Type  | Description                                                                                           | Default    |
| --------------- | ----- | ----------------------------------------------------------------------------------------------------- | ---------- |
| `img`           | `Any` | Image to display. Can be a numpy array with valid OpenCV image, PIL image, or model result object.    | *required* |
| `waitkey_delay` | `int` | Delay in ms for waitKey() call. Use 0 to show still images, use 1 for streaming video. Defaults to 1. | `1`        |

#### show\_image(img) <a href="#show_image" id="show_image"></a>

`show_image(img)`

Show still image or model result.

Parameters:

| Name  | Type  | Description                                                                                        | Default    |
| ----- | ----- | -------------------------------------------------------------------------------------------------- | ---------- |
| `img` | `Any` | Image to display. Can be a numpy array with valid OpenCV image, PIL image, or model result object. | *required* |

## Timer <a href="#timer" id="timer"></a>

`Timer`

Simple timer class.

### Timer Methods <a href="#timer-methods" id="timer-methods"></a>

#### \_\_call\_\_ <a href="#call" id="call"></a>

`__call__()`

Get elapsed time since timer creation.

Returns:

| Type    | Description                                        |
| ------- | -------------------------------------------------- |
| `float` | Time elapsed in seconds since object construction. |

#### \_\_init\_\_ <a href="#init" id="init"></a>

`__init__()`

Constructor. Records start time.

## Progress <a href="#progress" id="progress"></a>

`Progress`

Progress bar with speed and percentage display.

This class provides a progress bar that shows completion percentage, speed, and optional messages. It works in both GUI and Jupyter notebook environments.

Attributes:

| Name          | Type            | Description                                          |
| ------------- | --------------- | ---------------------------------------------------- |
| `last_step`   | `Optional[int]` | Total number of steps (None for indeterminate).      |
| `start_step`  | `int`           | Starting step number.                                |
| `bar_len`     | `int`           | Length of the progress bar in characters.            |
| `speed_units` | `str`           | Units to display for speed (e.g., "FPS", "items/s"). |

### Attributes <a href="#attributes" id="attributes"></a>

#### step\_range: Optional\[tuple] <a href="#step_range-optionaltuple" id="step_range-optionaltuple"></a>

`step_range: Optional[tuple]`

`property`

Get start-end step range (if defined).

### Progress Methods <a href="#progress-methods" id="progress-methods"></a>

#### \_\_init\_\_(last\_step=None, ...) <a href="#init" id="init"></a>

`__init__(last_step=None, *, start_step=0, bar_len=15, speed_units='FPS')`

Constructor.

Parameters:

| Name          | Type            | Description                                                             | Default |
| ------------- | --------------- | ----------------------------------------------------------------------- | ------- |
| `last_step`   | `Optional[int]` | Total number of steps (None for indeterminate). Defaults to None.       | `None`  |
| `start_step`  | `int`           | Starting step number. Defaults to 0.                                    | `0`     |
| `bar_len`     | `int`           | Progress bar length in symbols. Defaults to 15.                         | `15`    |
| `speed_units` | `str`           | Units to display for speed (e.g., "FPS", "items/s"). Defaults to "FPS". | `'FPS'` |

#### reset <a href="#reset" id="reset"></a>

`reset()`

Reset the progress bar to its initial state.

This method resets the current step, message, and timing information.

#### step(steps=1, ...) <a href="#step" id="step"></a>

`step(steps=1, *, message=None)`

Update progress by given number of steps.

Parameters:

| Name      | Type            | Description                  | Default |
| --------- | --------------- | ---------------------------- | ------- |
| `steps`   | `int`           | Number of steps to advance.  | `1`     |
| `message` | `Optional[str]` | Optional message to display. | `None`  |

## stdoutRedirector <a href="#stdoutredirector" id="stdoutredirector"></a>

`stdoutRedirector`

Redirect stdout to another stream.

### stdoutRedirector Methods <a href="#stdoutredirector-methods" id="stdoutredirector-methods"></a>

#### \_\_init\_\_(stream=None) <a href="#init" id="init"></a>

`__init__(stream=None)`

Constructor.

Parameters:

| Name     | Type            | Description                                                                      | Default |
| -------- | --------------- | -------------------------------------------------------------------------------- | ------- |
| `stream` | `Optional[str]` | Output stream to redirect to; None to redirect to null device. Defaults to None. | `None`  |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.degirum.com/degirum-tools/support/ui_support.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
