GUIDE / REAL TIME

Video and frames

Show live images from a camera, a model or a simulation with <video> and Frames, draw over them, and know which pixel was clicked.

Core janelkit Included with janelkit. Nothing extra to install.
CHAPTER 21 / 29~5 min read · try examples at your own pace
Alpha / 0.2 — These pages document JanelKit 0.2 and its packages. Each series (0.1, 0.2…) may change the public API, always with migration notes: see Changes and migration. The website uses Svelte; the desktop examples use Python and JanelKit, not JavaScript.

What you will learn

  • Why frames travel through Frames and not through state.
  • How to push images from any thread and show the latest one with <video>.
  • How to place elements over the image and find the pixel the user clicked.
  • How to know the frame rate and whether the source stopped.

Frames do not go through reactivity

A camera delivers 30 to 60 images per second. A state per image would recalculate the interface each time, so images take another road: a Frames object, which any thread can feed with push, and <video source={frames}>, which always shows the latest one. What is reactive is what you learn from the images: the detections, the counts, the measurements.

An image is a NumPy array or a QImage in the same process as the interface. Your model reads it there, without a server and without serializing anything, and its results go into state like any other data.

PathCarriesHow
Frames → <video>Every image, latest firstframes.push(image) from any thread; images that cannot be shown in time are skipped, never queued.
Frames → your modelThe latest image when the model is freeasync for image in frames, with the model in background().
state → templateResults: boxes, labels, countsAn ordinary assignment after the await.

A first video, without a camera

This complete component draws a scene that changes color 30 times per second, so it runs on any computer. A timer stands in for the camera. Click on the image to mark a point; the mark is placed in image pixels, so it stays on the same spot of the image when the window is resized.

janel
<script lang="python">
import itertools
from PySide6.QtGui import QColor, QImage
from janelkit import Frames, interval, state

frames = Frames(stall_after=1.0)
marks = state([])
hues = itertools.count(0, 4)

@interval(33)
def draw():                        # stands in for a camera
    image = QImage(320, 180, QImage.Format.Format_RGB32)
    image.fill(QColor.fromHsv(next(hues) % 360, 150, 230))
    frames.push(image)

def mark(event):
    if event.image_x is not None:  # None outside the image
        marks.value.append((event.image_x, event.image_y))

def pct(value, axis):              # image pixels to a percentage of the image
    size = frames.size or (1, 1)
    return f"{100 * value / size[axis]}%"
</script>

<column padding={16} gap={8}>
  <video source={frames} flex={1} on:click={mark} label="Scene">
    {#each marks as m}
      <flex class="mark" style={{"left": pct(m[0], 0), "top": pct(m[1], 1)}} />
    {/each}
  </video>
  <text>{frames.fps:.0f} fps · {len(marks)} mark(s){" · no signal" if frames.stalled else ""}</text>
  <row gap={8}>
    <button on:click={draw.stop()}>Stop the source</button>
    <button on:click={draw.start()}>Start it</button>
  </row>
</column>

<style>
.mark { position: absolute; width: 10px; height: 10px; border-radius: 5px; background: white; border: 2px solid black; }
</style>
Copy

Complete component · Save as src/App.janel in a scaffolded project.

How it works

  1. frames.push(image) hands each new image to Frames; <video> shows the latest one. The image never goes into a state.
  2. The children of <video> sit on a layer of the exact size of the visible image, so left: 50% is the middle of the image, not of the element.
  3. event.image_x and event.image_y are the clicked pixel of the image, whatever the fit; they are None outside the image.
  4. frames.fps and frames.stalled are reactive: the last line follows them. Stop the source, and after one second without push it says no signal.

What you should see

The image changes color continuously and the text shows about 30 fps. Each click on the image adds a white mark where you clicked. Stop the source freezes the image, and a second later the text says no signal; Start it brings the image back.

Common mistakes

  • Do not put images in a state. Use Frames for images and state for what you learn from them.
  • A real camera should push from its own thread, not from a timer on the interface thread; see the next sections.

What push accepts

frames.push(image) accepts a NumPy array, or any object with the buffer protocol, of bytes shaped height × width (gray), height × width × 3 (color="rgb" or "bgr") or × 4 ("rgba", "bgra"), and also a QImage. It copies the image, so the buffer can be reused, and converts it in the thread that calls it, not in the interface thread. Frames(color="bgr") is what OpenCV delivers; the default is "rgb".

If images arrive faster than the interface can show them, the extra ones are skipped: <video> and async for always receive the latest. async for image in frames, and await frames.next(), give you the very object you pushed. frames.latest() is the last image and frames.clear() empties the view.

python
# In a component script; camera is an opened cv2.VideoCapture and model is yours.
import threading
from janelkit import Frames, background, on_mount, spawn, state

frames = Frames(color="bgr")       # OpenCV delivers BGR
faces = state([])

def capture():                     # its own thread: never touches state
    while True:
        ok, image = camera.read()
        if ok:
            frames.push(image)

async def detect():
    async for image in frames:     # the latest, each time the model is free
        faces.value = await background(model, image)

on_mount(lambda: (threading.Thread(target=capture, daemon=True).start(), spawn(detect())))
Copy

How it works

  1. The capture thread only pushes. Reading or writing state there raises WrongThreadError.
  2. detect runs on the interface thread, but the model runs in background(), so a model at 12 fps does not slow a preview at 30. NumPy, OpenCV and PyTorch release the GIL while they work.
  3. faces is assigned after the await, back on the interface thread, and the template shows the boxes.

Draw over the image, and find the clicked pixel

The children of <video> go in a box with position: relative of the exact size of the image you see, so percentages are percentages of the image, also with fit="contain" (bands around it) or fit="cover" (cropped). Detection boxes are ordinary elements, with styles and clicks. For a mirror, such as a front camera, flip the image before push so the coordinates still match.

<video> receives on:click, on:dblclick, on:contextmenu and on:pointerdown, up, move, enter and leave. Its PointerEvent has, besides x and y on the element, image_x and image_y: the position in image pixels, as floats. They are None without a frame, in the bands of fit="contain" and for a click from the keyboard. In tests, app.find(label="Scene").click(x=100, y=50) clicks that point of the element.

Common mistakes

  • A child with position: absolute, such as a detection box, does not let clicks through to the <video>, as in any box. Its on:pointerdown and the other pointer events still bubble up.
  • Do not draw on the array you pushed: the preview, the model and a recording may all hold it. Copy it first, or better, draw with child elements.

Know the frame rate, and when the source stops

frames.size, (width, height) or None, and frames.fps are reactive. frames.stalled becomes True when more than stall_after seconds pass without a push (1.5 by default, Frames(stall_after=…)), and False again with the next image; at that moment fps also drops to 0. Before the first image and after clear() it is False: to know whether any image arrived, check frames.size is None.

Frames only sees the pushes. A source that keeps pushing the same frozen image, such as a disconnected camera whose last frame is processed in each cycle, is not detected this way; the code that reads the camera has to know.

janel
<!-- Partial template. -->
{#if frames.stalled}
  <text class="warning">No signal</text>
{/if}
Copy

Fragment · Add it to an existing component; it is not a complete file.

Opening cameras is up to you

JanelKit shows images; it does not open cameras. Use OpenCV (cv2.VideoCapture) in a thread of your own, as above, or QtMultimedia, which is in PySide6-Addons: JanelKit installs only PySide6-Essentials, so install the Addons yourself (pip install PySide6-Addons) if you choose it. <video> does not decode video files and has no audio; to play a film, use a player.

Learn moreReal-time applications ↗

Key points

  • Images go through Frames to <video>; results go through state to the template.
  • push works from any thread, copies the image and keeps only the latest.
  • Children of <video> are placed in image percentages; image_x and image_y give the clicked pixel.
  • fps, size and stalled are reactive; stalled only sees pushes.

English documentation based on the JanelKit source. For additional details, browse the source docs ↗.