UI Support
UI Support Module Overview
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
Use
Display
class for showing images in any environmentDraw text on images with
put_text()
Track progress with
Progress
classMonitor performance with
FPSMeter
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 videosProgress
: Progress bar with speed and percentage displayFPSMeter
: Frames per second measurementTimer
: Simple timing utilitystdoutRedirector
: Context manager for redirecting stdout
Configuration Options
Font settings (face, scale, thickness)
Color schemes (RGB/BGR)
Progress bar appearance
Display window properties
Classes
CornerPosition
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:
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
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:
avg_len
int
Number of samples to use for FPS calculation.
Functions
__init__(avg_len=100)
__init__(avg_len=100)
Constructor.
Parameters:
avg_len
int
Number of samples to use for FPS calculation. Defaults to 100.
100
fps
fps()
Return current average FPS.
record
record()
Record timestamp and update average duration.
Returns current average FPS.
Display
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:
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
window_name
window_name
property
Get the window name.
Returns:
str
Name of the display window.
Functions
__init__(capt='', ...)
__init__(capt='<image>', show_fps=True, w=None, h=None)
Constructor.
Parameters:
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:
Exception
If window title is empty.
_check_gui
_check_gui()
staticmethod
Check if graphical display is supported.
Returns:
bool
True if graphical display is supported, False otherwise.
_display_fps(img, ...)
_display_fps(img, fps)
staticmethod
Helper method to display FPS.
_update_notebook_display(obj)
_update_notebook_display(obj)
Update notebook display with given object.
Parameters:
obj
Any
Object to display in the notebook.
required
show_image(img)
show_image(img)
Show still image or model result.
Parameters:
img
Any
Image to display. Can be a numpy array with valid OpenCV image, PIL image, or model result object.
required
Timer
Timer
Simple timer class.
Functions
__call__
__call__()
Get elapsed time since timer creation.
Returns:
float
Time elapsed in seconds since object construction.
__init__
__init__()
Constructor. Records start time.
Progress
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:
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
step_range
step_range
property
Get start-end step range (if defined).
Functions
__init__(last_step=None, ...)
__init__(last_step=None, *, start_step=0, bar_len=15, speed_units='FPS')
Constructor.
Parameters:
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'
_update
_update()
Update progress bar.
step(steps=1, ...)
step(steps=1, *, message=None)
Update progress by given number of steps.
Parameters:
steps
int
Number of steps to advance.
1
message
Optional[str]
Optional message to display.
None
stdoutRedirector
stdoutRedirector
Redirect stdout to another stream.
Functions
__init__(stream=None)
__init__(stream=None)
Constructor.
Parameters:
stream
Optional[str]
Output stream to redirect to; None to redirect to null device. Defaults to None.
None
Functions
deduce_text_color(bg_color)
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:
bg_color
tuple
Background color as an (R, G, B)
tuple.
required
Returns:
Tuple[int, int, int]
(R, G, B)
value for black or white text.
color_complement(color)
color_complement(color)
Return the complement of an RGB color.
Parameters:
color
tuple | list
Color specified as (R, G, B)
.
required
Returns:
Tuple[int, int, int]
Complementary color in (R, G, B)
format.
rgb_to_bgr(color)
rgb_to_bgr(color)
Convert an RGB color tuple to BGR.
Parameters:
color
tuple
Color in (R, G, B)
format.
required
Returns:
Tuple[int, int, int]
Color in (B, R, G)
order for OpenCV functions.
ipython_display(obj, ...)
ipython_display(obj, clear=False, display_id=None)
Display an object in IPython notebooks.
Parameters:
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:
Exception
If the object type is unsupported.
put_text(image, ...)
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:
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
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:
ndarray
Image with text drawn on it.
stack_images(image1, ...)
stack_images(image1, image2, dimension='horizontal', downscale=None, labels=None, font_color=(255, 255, 255))
Stack two images either horizontally or vertically.
Parameters:
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:
Union[ndarray, Image]
Combined image with optional resizing and labels.
Last updated
Was this helpful?