|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import io |
| 4 | +from collections import deque |
| 5 | +from contextlib import contextmanager |
| 6 | +from dataclasses import dataclass |
| 7 | +from functools import wraps |
| 8 | +from typing import Any, Iterator, Literal, Optional, Protocol, Union |
| 9 | + |
| 10 | +import numpy as np |
| 11 | +import PIL.Image |
| 12 | +from matplotlib.figure import Figure |
| 13 | +from PIL import Image, ImageDraw |
| 14 | + |
| 15 | +from instamatic.camera.videostream import VideoStream |
| 16 | + |
| 17 | + |
| 18 | +class VideoStreamFrameProtocol(Protocol): |
| 19 | + """Mimics the `VideoStreamFrame` interface to avoid circular import.""" |
| 20 | + |
| 21 | + auto_contrast: bool = True |
| 22 | + brightness: float = 1.0 |
| 23 | + display_range: int = 255 |
| 24 | + stream: VideoStream |
| 25 | + |
| 26 | + |
| 27 | +class DeferredImageDraw: |
| 28 | + """Defer `ImageDraw` method calls: put them in deque, draw using `on`.""" |
| 29 | + |
| 30 | + @dataclass |
| 31 | + class Instruction: |
| 32 | + """Stores info about `ImageDraw` calls deferred by `__getattr__`.""" |
| 33 | + |
| 34 | + attr_name: str |
| 35 | + args: tuple[Any, ...] |
| 36 | + kwargs: dict[str, Any] |
| 37 | + |
| 38 | + def __init__(self, draw: Optional[ImageDraw.ImageDraw] = None) -> None: |
| 39 | + self._drawing = draw if draw else ImageDraw.Draw(Image.new('RGB', (1, 1))) |
| 40 | + self.instructions: deque[DeferredImageDraw.Instruction] = deque() |
| 41 | + |
| 42 | + def __getattr__(self, attr_name: str) -> Any: |
| 43 | + """Get the first of `self.attr_name` and `self._drawing.attr_name`. |
| 44 | +
|
| 45 | + If the attribute is a method of the internal `ImageDraw` object, |
| 46 | + return its wrapped version that defers it by appending a corresponding |
| 47 | + `Instruction` to `self.instructions` to be run at render time instead. |
| 48 | + `DeferredImageDraw.Instruction` instance returned this way is mutable |
| 49 | + and can be deleted by calling `self.instructions.remove(instruction)`. |
| 50 | + Otherwise, return the attribute of `DeferredImageDraw` instance as-is. |
| 51 | + """ |
| 52 | + try: |
| 53 | + attr = object.__getattribute__(self, attr_name) |
| 54 | + except AttributeError as e: |
| 55 | + reraise_on_fail = e |
| 56 | + try: |
| 57 | + attr = getattr(self._drawing, attr_name) |
| 58 | + except AttributeError: |
| 59 | + raise reraise_on_fail |
| 60 | + |
| 61 | + if callable(attr): |
| 62 | + |
| 63 | + @wraps(attr) |
| 64 | + def wrapped(*args, **kwargs) -> DeferredImageDraw.Instruction: |
| 65 | + instruction = self.Instruction(attr_name, args, kwargs) |
| 66 | + self.instructions.append(instruction) |
| 67 | + return instruction |
| 68 | + |
| 69 | + return wrapped # do not call attr - delay it until _redraw() |
| 70 | + return attr # non-callable attr of self (if exists) or self._drawing |
| 71 | + |
| 72 | + def on(self, image: Image.Image) -> Image.Image: |
| 73 | + """Core method: draws all deferred `self.instructions` on image.""" |
| 74 | + self._drawing = ImageDraw.Draw(image) |
| 75 | + for ins in self.instructions: |
| 76 | + getattr(self._drawing, ins.attr_name)(*ins.args, **ins.kwargs) |
| 77 | + return image |
| 78 | + |
| 79 | + def circle( |
| 80 | + self, |
| 81 | + xy: tuple[int, int], |
| 82 | + radius: float, |
| 83 | + fill: Optional[Union[str, tuple[int, int, int]]] = None, |
| 84 | + outline: Optional[Union[str, tuple[int, int, int]]] = None, |
| 85 | + width: int = 1, |
| 86 | + ) -> DeferredImageDraw.Instruction: |
| 87 | + """Draw a circle by wrapping a call to `ImageDraw.ellipse`. |
| 88 | +
|
| 89 | + Since `ImageDraw.circle` was added only in Pillow 10.4.0, this |
| 90 | + provides a backward-compatible way to draw circles using ellipses. |
| 91 | + """ |
| 92 | + ellipse_xy = (xy[0] - radius, xy[1] - radius, xy[0] + radius, xy[1] + radius) |
| 93 | + return self.ellipse(ellipse_xy, fill=fill, outline=outline, width=width) |
| 94 | + |
| 95 | + |
| 96 | +class VideoStreamProcessor: |
| 97 | + """Encapsulate complex `VideoStreamFrame` frame/image processing. |
| 98 | +
|
| 99 | + This class handles converting mathematical operations behind efficiently |
| 100 | + converting raw frames into images, rendering matplotlib figures as static |
| 101 | + images in the video stream window, as well as drawing on top of images. |
| 102 | +
|
| 103 | + Streamed view can be altered by setting a temporary frame/image/figure. |
| 104 | + Each of these can be set/reset via corresponding attribute, or set |
| 105 | + temporarily via `with processor.temporary(frame/image/figure=...)` syntax. |
| 106 | +
|
| 107 | + Drawing is handled via the `draw` attribute of the `DeferredImageDraw` |
| 108 | + class which acts as a deferred proxy for PIL.ImageDraw. Instructions, |
| 109 | + instead of being applied directly on one frame only, are saved into the |
| 110 | + `draw.instructions` deque and efficiently re-applied continuously. |
| 111 | + """ |
| 112 | + |
| 113 | + def __init__(self, vsf: VideoStreamFrameProtocol) -> None: |
| 114 | + self.vsf: VideoStreamFrameProtocol = vsf |
| 115 | + self.draw: DeferredImageDraw = DeferredImageDraw() |
| 116 | + self.color_mode: Literal['L', 'RGB'] = 'RGB' |
| 117 | + self.temporary_frame: Optional[np.ndarray] = None |
| 118 | + self.temporary_image: Optional[Image.Image] = None |
| 119 | + self._temporary_figure: Optional[Figure] = None |
| 120 | + |
| 121 | + @property |
| 122 | + def frame(self) -> Union[np.ndarray, None]: |
| 123 | + """The raw `np.ndarray` frame from the stream or `_temporary_frame`""" |
| 124 | + return self.vsf.stream.frame if (t := self.temporary_frame) is None else t |
| 125 | + |
| 126 | + @property |
| 127 | + def image(self) -> Union[Image.Image, None]: |
| 128 | + """Processed image with `draw.instructions`, or `_temporary_image`.""" |
| 129 | + if (temporary_image := self.temporary_image) is not None: |
| 130 | + return temporary_image |
| 131 | + if (frame := self.frame) is not None: |
| 132 | + if self.vsf.display_range != 255.0 or self.vsf.brightness != 1.0: |
| 133 | + if self.vsf.auto_contrast: |
| 134 | + display_range = 1 + np.percentile(frame[::4, ::4], 99.5) |
| 135 | + else: |
| 136 | + display_range = self.vsf.display_range |
| 137 | + frame = (self.vsf.brightness * 255 / display_range) * frame |
| 138 | + frame = np.clip(frame.astype(np.int16), 0, 255).astype(np.uint8) |
| 139 | + if self.draw.instructions: |
| 140 | + image = Image.fromarray(frame).convert(self.color_mode) |
| 141 | + self.draw.on(image) |
| 142 | + else: |
| 143 | + image = Image.fromarray(frame) |
| 144 | + return image |
| 145 | + |
| 146 | + def render_figure(self, figure: Figure) -> Image.Image: |
| 147 | + """Convert a `Figure` into an `Image` to allow rendering it in GUI.""" |
| 148 | + buffer = io.BytesIO() |
| 149 | + dpi = min(self.vsf.stream.frame.shape / figure.get_size_inches()) |
| 150 | + figure.savefig(buffer, format='png', dpi=dpi, bbox_inches='tight', pad_inches=0) |
| 151 | + buffer.seek(0) |
| 152 | + return Image.open(buffer).convert('RGBA') |
| 153 | + |
| 154 | + @contextmanager |
| 155 | + def temporary( |
| 156 | + self, |
| 157 | + *, |
| 158 | + frame: Optional[np.ndarray] = None, |
| 159 | + image: Optional[Image.Image] = None, |
| 160 | + figure: Optional[Figure] = None, |
| 161 | + ) -> Iterator[None]: |
| 162 | + """Temporarily override the current frame/image/figure for rendering. |
| 163 | +
|
| 164 | + Use via context manager using a `with` statement with one of the args: |
| 165 | + with processor.temporary(frame=..., image=..., figure=...): |
| 166 | + ... |
| 167 | + """ |
| 168 | + pre_context_values = self.temporary_frame, self.temporary_image |
| 169 | + try: |
| 170 | + if frame is not None: |
| 171 | + self.temporary_frame = frame |
| 172 | + if image is not None: |
| 173 | + self.temporary_image = image |
| 174 | + elif figure is not None: |
| 175 | + self.temporary_image = self.render_figure(figure) |
| 176 | + yield |
| 177 | + finally: |
| 178 | + self.temporary_frame, self.temporary_image = pre_context_values |
| 179 | + |
| 180 | + @property |
| 181 | + def temporary_figure(self) -> Figure: |
| 182 | + return self._temporary_figure |
| 183 | + |
| 184 | + @temporary_figure.setter |
| 185 | + def temporary_figure(self, figure: Union[Figure, None]) -> None: |
| 186 | + self._temporary_figure = figure |
| 187 | + self.temporary_image = self.render_figure(figure) if figure else None |
0 commit comments