opencv-proto documentation

https://github.com/idlesign/opencv-proto

Description

Allows fast prototyping in Python for OpenCV

Offers primitives and simplified interfaces to streamline prototypes construction in Python.

Facilitates:

  • Windows construction and management
  • Trackbar construction
  • Configuration save/load (including trackbar values)
  • Key binding (e.g. for trackbar control, configuration save/load)
  • Video capturing and modification
  • Work with images
  • Work with text
  • Frames transformation

Requirements

  1. Python 3.6+
  2. opencv-python (or variants)

Quick install with third-parties: $ pip install opencv-proto[all]

Table of Contents

Quickstart

Color Palette

Let’s replace 37 lines of source code from Trackbar as the Color Palette tutorial with ocvproto-based implementation:

from ocvproto.toolbox import WindowManager, Canvas

with WindowManager() as wm:
    # Window manager will create a default window for us if none provided.
    # Default window is available through .window property.

    # With the help of .add_trackbar_group() we create three trackbars,
    # to adjust our color values for R, G and B. Batch apply `max` value
    # to all three trackbars.
    rgb = wm.window.add_trackbar_group(['R', 'G', 'B'], max=255)

    # If one doesn't configure their own Application object,
    # Window manager will instantiate one automatically, using default settings.
    for _ in wm.app.loop():
        # Most of the time we'll need a loop to process our frames.
        # Application object (available through .app property) offers us such a loop.

        # Lastly we create a canvas object using RGB value from trackbars,
        # and pass its' frame to .set_frame() shortcut.
        # That shortcut puts the frame into default window.
        wm.set_frame(Canvas(512, 300, color=rgb))

Camera capture

Now let’s capture video camera stream into ocvproto.avi file, being able to adjust blur.

Let’s also setup config filepath (ocvproto.json) - this allows us to store current trackbar values (s key) and load them (r key). It is useful to restore settings between sessions.

We bind z key to take camera shots.

from ocvproto.toolbox import WindowManager, Camera

with WindowManager() as wm:

    # We instruct our application to store settings into file.
    wm.app.set_config('ocvproto.json')

    # We create two trackbars to adjust blur.
    blur = wm.window.add_trackbar_group(['x', 'y'], 'Blur', default=1)

    # We initiate default (first available) camera connection.
    with Camera() as cam:

        # Let's add trackbars for adjustable camera properties (contrast, brightness, etc.).
        wm.window.add_trackbar_group(cam.describe_properties(), default=1, max=255)

        # You can bind keys to actions.
        # Here we bind `z` to trigger .cam.dump_image() to take stills.
        wm.app.bind_key('z', cam.dump_image)

        for _ in wm.app.loop():
            # Read a frame from camera, we'll work with.
            cam.read()

            # Now we blur that frame.
            cam.blur(blur)

            # And we dump the frame into the file.
            # If dumping parameters were not set up before
            # .dump() shortcut will use defaults
            # (e.g. `ocvproto.avi` name, XVID codec).
            cam.dump()

            # Show the frame.
            wm.set_frame(cam)

API

Application

class ocvproto.app.application.Application(*, config: Union[str, pathlib.Path, None] = None)

Represents ocvproto application.

Parameters:config – Configuration to be used.
bind_key(key: Union[str, int], func: Callable)

Binds a key to a function.

Parameters:
  • key
  • func
config_load()

Loads a configuration from config file.

config_save()

Saves current configuration to config file.

hook_register(key: str, func: Callable)

Registers a hook.

Parameters:
  • key – Hooks group key.
  • func – Hook function to add to group.
loop()

Main application loop. Handles keys listening and issues a loop function (see .set_loop_func()).

set_config(config: Union[str, pathlib.Path, None], keys: Tuple[Union[str, int], Union[str, int]] = None)

Sets configuration from the app.

Parameters:
  • config – Configuration object.
  • keys – Keys tuple to save and load configuration.
set_loop_func(func: Callable)

Sets a function to perform in a main app loop.

Config
class ocvproto.app.config.Config(fpath: Union[str, pathlib.Path])

Represent an interface to configuration file.

Parameters:fpath – Configuration file path.
get_data(key: str, default: Any = None)

Reads data from a config section denoted by key.

Parameters:
  • key
  • default – Default values to return.
load()

Loads configuration from file.

save()

Saves configuration to file.

set_data(key: str, value: Any)

Places the data into config section denoted by key.

Parameters:
  • key
  • value
Keys
class ocvproto.app.keys.Key

Keys registry. Can be used for binding actions.

User Interface

Windows Manager
class ocvproto.ui.wm.WindowManager(windows: List[ocvproto.ui.window.Window] = None, app: ocvproto.app.application.Application = None)

Manages windows.

Parameters:
  • windows – Windows to manage. If not set, one window is automatically constructed.
  • app – ocvproto application object. Automatically constructed if not set.
config_load(config: ocvproto.app.config.Config)

Updates managed windows using data from the given config.

Parameters:config
config_update(config: ocvproto.app.config.Config)

Updates data gathered from managed windows in the given config.

Parameters:config
iter_trackbars() → Generator[Tuple[ocvproto.ui.window.Window, ocvproto.ui.trackbars.base.Trackbar], None, None]

Generator yielding managed windows and trackbars.

render()

Renders managed windows.

set_frame(frame: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame])

Sets frame to be rendered in default window.

Parameters:frame
window

Default window.

Window
class ocvproto.ui.window.Window(name: str = None)

Represents a window.

Parameters:name – Window name. If not set, automatically generated.
add_trackbar(*trackbars)

Add the given trackbars to the window.

Parameters:trackbars
add_trackbar_group(definitions: Union[int, Dict[str, dict], List[dict], List[str]], prefix: str = '', **common_kwargs) → Tuple

A shortcut to batch create trackbars in a declarative way.

Parameters:
  • definitions

    Definitions to construct trackbars.

    • Integer:
      • 2 - create two trackbars with generated titles and default params.
    • List:
      • [‘one’, ‘two’, ‘three’] -
        • create 3 trackbars with the given titles and default params.
      • [{‘keys’: ‘kl’}, {}] -
        • create 2 trackbars with generated titles and default params.
    • Dictionary:
      • {‘y’: {‘keys’: ‘kl’}, ‘x’: {‘step’: 20}} - create 2 trackbars with the given titles and params.
  • prefix – Prefix to add to trackbars titles.
  • common_kwargs – Common keyword arguments to pass to all trackbars.
create(*, autosize=True)

Creates a window.

Parameters:autosize – If try, window is automatically sized to a content.
position(*, x: int, y: int)

Positions the window.

render()

Renders window contents.

resize(*, width: int, height: int)

Resizes the window.

Parameters:
  • width
  • height
set_frame(frame: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame])

Sets current frame for the window.

Parameters:frame
Trackbar
class ocvproto.ui.trackbars.base.Trackbar(name, *, max: Union[int, float] = None, default: Union[int, float] = None, callback: Callable = None, step: Union[int, float] = None, keys: str = None)

Represents a trackbar.

Parameters:
  • name – Name to show in UI and address this in opencv api.
  • max – Max value. Default: 100
  • default – Default (current) value. Default: 0
  • callback – Function to be called on trackbar value change through UI.
  • step – Step to inc/dec trackbar value. Default: 1
  • keys – Two-letter string to represent keys to inc and dec value.
bind(window_name: str)

Binds the trackabr to the given window.

Parameters:window_name
dec()

Decrements the current value.

get_value() → Union[int, float]

Force getting current value.

inc()

Increments the current value.

onChange(val: Union[int, float])

Issued on value change from UI.

set_keys(keys: str)

Set keys to inc/dec trackbar value.

Parameters:keys – Two-letter string to represent keys to inc and dec value.
value

Current trackbar value.

Sources

Image
class ocvproto.sources.image.Image(src: Union[int, str, <sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame] = None)

Bases: ocvproto.sources.base.Source

Represents an image.

Parameters:src – Source id (int), path (str) or frame (np array)
absdiff(frame: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame]) → ocvproto.frame.Frame

Returns absolute difference between the current and a given frame as a new Source.

Parameters:frame
blur(ksize: Tuple[int, int]) → ocvproto.frame.Frame

Blures the current frame inplace.

Parameters:ksize – Kernel size tuple (width, height)
canny(thr_1: int, thr_2: int) → ocvproto.frame.Frame

Applies Canny Edge Detection algorithm to the current frame inplace.

Parameters:
  • thr_1
  • thr_2
dilate(element: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame], iterations: int = None) → ocvproto.frame.Frame

Dilates the current frame inplace.

Parameters:
  • element
  • iterations
draw_rectangle(*, pos: Tuple[int, int], width: int, height: int, color: Union[int, str, Tuple[int, int, int]] = None)

Draws a rectangle.

Parameters:
  • pos – Top left corner (x, y).
  • width
  • height
  • color
dump(fpath: Union[str, pathlib.Path] = None)

Dumps frame into a file.

Parameters:fpath – Filepath to store image into. If not set, name is generated automatically.
fill(color: Union[int, str, Tuple[int, int, int]])

Fills the canvas with the given color.

Parameters:color
frame

Current frame.

height

Height

make_gray() → ocvproto.frame.Frame

Makes the current frame grayscale inplace.

make_rgb() → ocvproto.frame.Frame

Makes the current frame RGB inplace.

read() → ocvproto.sources.image.Image

Read and return current frame.

resize(width: int, height: int) → ocvproto.frame.Frame

Resizes the current frame inplace.

Parameters:
  • width
  • height
width

Width

Camera
class ocvproto.sources.camera.Camera(src: Union[int, str] = 0)

Bases: ocvproto.sources.video.Video

Represents a camera device.

Parameters:src

Device path (str) or id (int). Default 0.

E.g.:
  • ’/dev/video0’
  • 0
  • 1
absdiff(frame: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame]) → ocvproto.frame.Frame

Returns absolute difference between the current and a given frame as a new Source.

Parameters:frame
blur(ksize: Tuple[int, int]) → ocvproto.frame.Frame

Blures the current frame inplace.

Parameters:ksize – Kernel size tuple (width, height)
brightness

Brightness

canny(thr_1: int, thr_2: int) → ocvproto.frame.Frame

Applies Canny Edge Detection algorithm to the current frame inplace.

Parameters:
  • thr_1
  • thr_2
codec

FOURCC codec alias.

contrast

Contrast

describe_properties() → Dict[str, Any]

Returns descriptions for CV properties found in the class of this object and its bases.

One can initialize trackbars with these descriptions: see Window.add_trackbar_group()

dilate(element: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame], iterations: int = None) → ocvproto.frame.Frame

Dilates the current frame inplace.

Parameters:
  • element
  • iterations
draw_rectangle(*, pos: Tuple[int, int], width: int, height: int, color: Union[int, str, Tuple[int, int, int]] = None)

Draws a rectangle.

Parameters:
  • pos – Top left corner (x, y).
  • width
  • height
  • color
dump(frame: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame] = None)

Writes the current or the given frame. Automatically configures writer object is needed.

dump_image(fpath: Union[str, pathlib.Path] = None)

Dumps the image into a file.

Parameters:fpath – Filepath to store image into. If not set, name is generated automatically.
dump_setup(fpath: Union[str, pathlib.Path] = 'ocvproto.avi', *, width: int = None, height: int = None, fps: Union[int, float] = None, codec: str = 'XVID') → <sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5d9c208>

Configures write parameters. Returns opencv writer object.

Parameters:
  • fpath – Filepath.
  • width
  • height
  • fps – Frames per second.
  • codec – FOURCC codec alias.
exposure

Exposure

fill(color: Union[int, str, Tuple[int, int, int]])

Fills the canvas with the given color.

Parameters:color
frame

Current frame.

gain

Gain

get_image() → ocvproto.sources.image.Image

Returns image object from the current frame.

hue

Hue

make_gray() → ocvproto.frame.Frame

Makes the current frame grayscale inplace.

make_rgb() → ocvproto.frame.Frame

Makes the current frame RGB inplace.

read() → ocvproto.sources.video.Video

Read and return current frame.

resize(width: int, height: int) → ocvproto.frame.Frame

Resizes the current frame inplace.

Parameters:
  • width
  • height
saturation

Saturation

set_property(name: str, value: int)

Helper method to set property value.

Parameters:
  • name – Property name.
  • value
Video
class ocvproto.sources.video.Property(cv_prop: int, *, max: int = None)

Bases: object

Represents a capture video property with restrictions.

class ocvproto.sources.video.Video(src: Union[str, <sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>])

Bases: ocvproto.sources.base.Source

Represents a video.

absdiff(frame: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame]) → ocvproto.frame.Frame

Returns absolute difference between the current and a given frame as a new Source.

Parameters:frame
blur(ksize: Tuple[int, int]) → ocvproto.frame.Frame

Blures the current frame inplace.

Parameters:ksize – Kernel size tuple (width, height)
canny(thr_1: int, thr_2: int) → ocvproto.frame.Frame

Applies Canny Edge Detection algorithm to the current frame inplace.

Parameters:
  • thr_1
  • thr_2
codec

FOURCC codec alias.

describe_properties() → Dict[str, Any]

Returns descriptions for CV properties found in the class of this object and its bases.

One can initialize trackbars with these descriptions: see Window.add_trackbar_group()

dilate(element: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame], iterations: int = None) → ocvproto.frame.Frame

Dilates the current frame inplace.

Parameters:
  • element
  • iterations
draw_rectangle(*, pos: Tuple[int, int], width: int, height: int, color: Union[int, str, Tuple[int, int, int]] = None)

Draws a rectangle.

Parameters:
  • pos – Top left corner (x, y).
  • width
  • height
  • color
dump(frame: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame] = None)

Writes the current or the given frame. Automatically configures writer object is needed.

dump_image(fpath: Union[str, pathlib.Path] = None)

Dumps the image into a file.

Parameters:fpath – Filepath to store image into. If not set, name is generated automatically.
dump_setup(fpath: Union[str, pathlib.Path] = 'ocvproto.avi', *, width: int = None, height: int = None, fps: Union[int, float] = None, codec: str = 'XVID') → <sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5d9c208>

Configures write parameters. Returns opencv writer object.

Parameters:
  • fpath – Filepath.
  • width
  • height
  • fps – Frames per second.
  • codec – FOURCC codec alias.
fill(color: Union[int, str, Tuple[int, int, int]])

Fills the canvas with the given color.

Parameters:color
focus

Focus

fps

FPS

frame

Current frame.

gamma

Gamma

get_image() → ocvproto.sources.image.Image

Returns image object from the current frame.

height

Height

make_gray() → ocvproto.frame.Frame

Makes the current frame grayscale inplace.

make_rgb() → ocvproto.frame.Frame

Makes the current frame RGB inplace.

read() → ocvproto.sources.video.Video

Read and return current frame.

resize(width: int, height: int) → ocvproto.frame.Frame

Resizes the current frame inplace.

Parameters:
  • width
  • height
set_property(name: str, value: int)

Helper method to set property value.

Parameters:
  • name – Property name.
  • value
sharpness

Sharpness

width

Width

zoom

Zoom

Miscellaneous

Canvas
class ocvproto.misc.canvas.Canvas(width: int = 640, height: int = 480, *, channels: int = 3, color: Union[int, str, Tuple[int, int, int]] = None)

Represents a canvas.

Parameters:
  • width
  • height
  • channels
  • color
absdiff(frame: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame]) → ocvproto.frame.Frame

Returns absolute difference between the current and a given frame as a new Source.

Parameters:frame
blur(ksize: Tuple[int, int]) → ocvproto.frame.Frame

Blures the current frame inplace.

Parameters:ksize – Kernel size tuple (width, height)
canny(thr_1: int, thr_2: int) → ocvproto.frame.Frame

Applies Canny Edge Detection algorithm to the current frame inplace.

Parameters:
  • thr_1
  • thr_2
dilate(element: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame], iterations: int = None) → ocvproto.frame.Frame

Dilates the current frame inplace.

Parameters:
  • element
  • iterations
draw_rectangle(*, pos: Tuple[int, int], width: int, height: int, color: Union[int, str, Tuple[int, int, int]] = None)

Draws a rectangle.

Parameters:
  • pos – Top left corner (x, y).
  • width
  • height
  • color
dump(fpath: Union[str, pathlib.Path] = None)

Dumps frame into a file.

Parameters:fpath – Filepath to store image into. If not set, name is generated automatically.
fill(color: Union[int, str, Tuple[int, int, int]])

Fills the canvas with the given color.

Parameters:color
height

Height

make_gray() → ocvproto.frame.Frame

Makes the current frame grayscale inplace.

make_rgb() → ocvproto.frame.Frame

Makes the current frame RGB inplace.

resize(width: int, height: int) → ocvproto.frame.Frame

Resizes the current frame inplace.

Parameters:
  • width
  • height
width

Width

Colors
ocvproto.misc.colors.COLORS = {'beige': (245, 245, 220), 'black': (0, 0, 0), 'blue': (0, 0, 255), 'brown': (165, 42, 42), 'chocolate': (210, 105, 30), 'cyan': (0, 255, 255), 'gold': (255, 215, 0), 'gray': (128, 128, 128), 'green': (0, 128, 0), 'indigo': (75, 0, 130), 'khaki': (240, 230, 140), 'lime': (0, 255, 0), 'linen': (250, 240, 230), 'magenta': (255, 0, 255), 'maroon': (128, 0, 0), 'navy': (0, 0, 128), 'olive': (128, 128, 0), 'orange': (255, 165, 0), 'pink': (255, 192, 203), 'purple': (128, 0, 128), 'red': (255, 0, 0), 'silver': (192, 192, 192), 'tan': (210, 180, 140), 'teal': (0, 128, 128), 'violet': (238, 130, 238), 'wheat': (245, 222, 179), 'white': (255, 255, 255), 'yellow': (255, 255, 0)}

Color aliases to RGB tuples map.

ocvproto.misc.colors.to_rgb(value: Union[int, str, Tuple[int, int, int]]) → Tuple[int, int, int]

Translates the given color value to RGB tuple.

Parameters:value
Text
class ocvproto.misc.text.Text(val: str = None, *, face: str = None, scale: float = None, color: Union[int, str, Tuple[int, int, int]] = None, pos: Tuple[int, int] = None, weight: int = None)

Represents a text that can be placed into a frame.

Parameters:
  • val – Text value itself.
  • face – Font face alias (see .face_map keys). Default: normal
  • scale – Scale factor. Default: 1
  • color – Color RGB tuple or alias (see COLORS). Default: white
  • pos – Position tuple (x, y) in frame from top-left. Default: (20, 20)
  • weight – Line thickness. Default: 1
put_on(frame: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame], text: str = None, *, pos: Tuple[int, int] = None)

Applies text to the frame.

Parameters:
  • frame – Frame to apply text to.
  • text – Text value to set on frame. If not set, value from initializer is used.
  • pos – Position tuple (x, y) in frame from top-left. Default: (20, 20)
classmethod put_on_demo(frame: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f75a5e65240>, Frame], text: str = 'Test Text 1 2 3 4 5')

Demonstrates available font faces applying all of them to the frame.

Parameters:
  • frame – Frame to apply text to.
  • text – Text value to on frame.

Primitives

Legend
class ocvproto.primitives.legend.Legend(labels: Sequence[str], pos: Tuple[int, int] = None, width: int = None, gap: int = None)

Bases: object

Represents a color-legend for labels.

Parameters:
  • labels – Strings to get colors for.
  • pos – Position (x, y) to place top left legend corner. Default: (20, 20)
  • width – Default: 250
  • gap – Base gap (also a height for each color stripe). Default: 25
put_on(frame: ocvproto.frame.Frame, *, pos: Tuple[int, int] = None)

Applies the legend to the frame.

Parameters:
  • frame – Frame to apply the legend to.
  • pos – Position (x, y) to place top left legend corner. Default: (20, 20)