pibooth-modnet 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,667 @@
1
+ # -*- coding: utf-8 -*-
2
+ """pibooth-modnet: AI background replacement and overlays for pibooth.
3
+
4
+ Removes the background behind guests with the MODNet portrait-matting model
5
+ (ONNX Runtime, CPU), replaces it with a background image and adds an overlay
6
+ on top of each capture. Built for pibooth 2.1.x on a Raspberry Pi 5 with
7
+ Raspberry Pi OS Trixie and a Camera Module 3 capturing at full resolution.
8
+
9
+ Speed strategy
10
+ --------------
11
+ * Each capture is processed in a worker thread as soon as it is taken, so the
12
+ work overlaps the countdown for the next shot instead of piling up in the
13
+ processing screen.
14
+ * MODNet runs at a small fixed size (short side 512 by default); the matte is
15
+ then upsampled to full resolution with a fast guided filter that snaps it to
16
+ the real edges in the full-resolution photo.
17
+ * Full-resolution compositing uses C-level PIL / OpenCV operations only, and
18
+ resized backgrounds and overlays are cached per theme and capture size.
19
+ * Themes with only an overlay skip the AI step entirely.
20
+
21
+ Install with ``pip install pibooth-modnet``; pibooth discovers it automatically.
22
+ See README.md for the full guide.
23
+ """
24
+
25
+ import os
26
+ import os.path as osp
27
+ import sys
28
+ import time
29
+ import random
30
+ import hashlib
31
+ import threading
32
+ import urllib.request
33
+ from io import BytesIO
34
+ from concurrent.futures import ThreadPoolExecutor
35
+
36
+ import numpy as np
37
+ from PIL import Image, ImageOps
38
+
39
+ try:
40
+ import cv2
41
+ cv2.setNumThreads(2) # Keep OpenCV from fighting ONNX Runtime and the preview for cores
42
+ except ImportError: # Fallback to PIL only (no edge refinement)
43
+ cv2 = None
44
+
45
+ try:
46
+ import onnxruntime as ort
47
+ except ImportError:
48
+ ort = None
49
+
50
+ try:
51
+ import pygame
52
+ import pibooth
53
+ from pibooth.utils import LOGGER
54
+ except ImportError: # Allow the command line tools to run without pibooth
55
+ pibooth = None
56
+ pygame = None
57
+ import logging
58
+ LOGGER = logging.getLogger("pibooth-modnet")
59
+
60
+
61
+ __version__ = "1.0.0"
62
+
63
+ SECTION = 'MODNET'
64
+
65
+ # MODNet photographic portrait matting (Apache-2.0), ONNX export with dynamic
66
+ # input size, as packaged by photobooth-app. Pinned to a commit and checked by
67
+ # SHA-256 so the download can never silently change.
68
+ MODEL_URL = ("https://github.com/photobooth-app/photobooth-app/raw/"
69
+ "e2db0d33752efe2204af08bcfd0d20c2c4d985ff/"
70
+ "src/photobooth/utils/rembg/models/modnet.onnx")
71
+ MODEL_SHA256 = "07c308cf0fc7e6e8b2065a12ed7fc07e1de8febb7dc7839d7b7f15dd66584df9"
72
+
73
+ IMAGE_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.bmp', '.webp')
74
+ NO_THEME_NAME = "No theme"
75
+
76
+
77
+ def _plugin_hookimpl(*args, **kwargs):
78
+ """Return pibooth.hookimpl, or a no-op decorator outside pibooth."""
79
+ if pibooth is not None:
80
+ return pibooth.hookimpl(*args, **kwargs)
81
+ if args and callable(args[0]):
82
+ return args[0]
83
+ return lambda func: func
84
+
85
+
86
+ # --------------------------------------------------------------------------
87
+ # Model handling
88
+ # --------------------------------------------------------------------------
89
+
90
+ def _sha256(path):
91
+ digest = hashlib.sha256()
92
+ with open(path, 'rb') as fp:
93
+ for chunk in iter(lambda: fp.read(1 << 20), b''):
94
+ digest.update(chunk)
95
+ return digest.hexdigest()
96
+
97
+
98
+ def ensure_model(path):
99
+ """Download the MODNet model if it is missing or corrupted.
100
+
101
+ :return: path to a valid model file
102
+ """
103
+ path = osp.abspath(osp.expanduser(path))
104
+ if osp.isfile(path):
105
+ return path # A user supplied model is trusted as is
106
+
107
+ os.makedirs(osp.dirname(path), exist_ok=True)
108
+ LOGGER.info("MODNet: downloading model to %s", path)
109
+ tmp = path + '.part'
110
+ urllib.request.urlretrieve(MODEL_URL, tmp)
111
+ if _sha256(tmp) != MODEL_SHA256:
112
+ os.remove(tmp)
113
+ raise IOError("MODNet: downloaded model failed its checksum, please retry")
114
+ os.replace(tmp, path)
115
+ LOGGER.info("MODNet: model downloaded")
116
+ return path
117
+
118
+
119
+ class MattingEngine(object):
120
+
121
+ """Compute a full resolution alpha matte with MODNet."""
122
+
123
+ def __init__(self, model_path, ref_size=512, threads=3, refine=True):
124
+ if ort is None:
125
+ raise ImportError("onnxruntime is not installed (pip install onnxruntime)")
126
+ self.ref_size = max(64, int(ref_size) // 32 * 32)
127
+ self.refine = refine and cv2 is not None
128
+
129
+ opts = ort.SessionOptions()
130
+ opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
131
+ opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
132
+ opts.intra_op_num_threads = max(1, int(threads))
133
+ opts.inter_op_num_threads = 1
134
+ self.session = ort.InferenceSession(model_path, sess_options=opts,
135
+ providers=['CPUExecutionProvider'])
136
+ self.input_name = self.session.get_inputs()[0].name
137
+
138
+ def inference_size(self, width, height):
139
+ """Scale so the short side is ``ref_size``, keep the aspect ratio (no
140
+ square stretching) and round both sides to a multiple of 32."""
141
+ scale = self.ref_size / float(min(width, height))
142
+ return (max(32, int(round(width * scale / 32.0)) * 32),
143
+ max(32, int(round(height * scale / 32.0)) * 32))
144
+
145
+ def warmup(self):
146
+ """First ONNX Runtime run allocates buffers, do it before any guest."""
147
+ self.matte(np.zeros((2592, 4608, 3), dtype=np.uint8))
148
+
149
+ def _run(self, small_rgb):
150
+ tensor = small_rgb.astype(np.float32)
151
+ tensor *= 1.0 / 127.5
152
+ tensor -= 1.0
153
+ tensor = np.ascontiguousarray(tensor.transpose(2, 0, 1)[np.newaxis])
154
+ return self.session.run(None, {self.input_name: tensor})[0][0, 0]
155
+
156
+ def matte(self, rgb):
157
+ """Return a uint8 alpha matte (H, W) for the uint8 RGB array ``rgb``."""
158
+ height, width = rgb.shape[:2]
159
+ size = self.inference_size(width, height)
160
+
161
+ if cv2 is not None:
162
+ small = cv2.resize(rgb, size, interpolation=cv2.INTER_AREA)
163
+ else:
164
+ small = np.asarray(Image.fromarray(rgb).resize(size, Image.Resampling.BILINEAR,
165
+ reducing_gap=2.0))
166
+ low = self._run(small)
167
+
168
+ if self.refine:
169
+ return self._guided_upsample(low, small, rgb)
170
+
171
+ low8 = (np.clip(low, 0.0, 1.0) * 255.0).astype(np.uint8)
172
+ if cv2 is not None:
173
+ return cv2.resize(low8, (width, height), interpolation=cv2.INTER_LINEAR)
174
+ return np.asarray(Image.fromarray(low8).resize((width, height), Image.Resampling.BILINEAR))
175
+
176
+ @staticmethod
177
+ def _guided_upsample(low, small_rgb, full_rgb, radius=2, eps=1e-3):
178
+ """Fast guided filter (He & Sun, 2015).
179
+
180
+ The linear coefficients are solved at inference resolution, upsampled,
181
+ then applied to the full resolution grey image: the edges of the matte
182
+ follow the real full resolution edges instead of a blurry upscale.
183
+ """
184
+ box = (2 * radius + 1, 2 * radius + 1)
185
+ guide = cv2.cvtColor(small_rgb, cv2.COLOR_RGB2GRAY).astype(np.float32) * (1.0 / 255.0)
186
+ mean_i = cv2.blur(guide, box)
187
+ mean_p = cv2.blur(low, box)
188
+ cov_ip = cv2.blur(guide * low, box) - mean_i * mean_p
189
+ var_i = cv2.blur(guide * guide, box) - mean_i * mean_i
190
+ coef_a = cov_ip / (var_i + eps)
191
+ coef_b = mean_p - coef_a * mean_i
192
+ # Work in 0-255 directly on the big image: q = a * grey_u8 + b * 255
193
+ coef_a = cv2.blur(coef_a, box)
194
+ coef_b = cv2.blur(coef_b, box) * 255.0
195
+
196
+ height, width = full_rgb.shape[:2]
197
+ full_a = cv2.resize(coef_a, (width, height), interpolation=cv2.INTER_LINEAR)
198
+ full_b = cv2.resize(coef_b, (width, height), interpolation=cv2.INTER_LINEAR)
199
+ grey = cv2.cvtColor(full_rgb, cv2.COLOR_RGB2GRAY)
200
+ result = cv2.multiply(full_a, grey, dtype=cv2.CV_32F)
201
+ del full_a
202
+ cv2.add(result, full_b, dst=result)
203
+ del full_b
204
+ cv2.max(result, 0.0, dst=result)
205
+ return cv2.convertScaleAbs(result) # Saturates to [0, 255] as uint8
206
+
207
+
208
+ # --------------------------------------------------------------------------
209
+ # Themes (background and / or overlay)
210
+ # --------------------------------------------------------------------------
211
+
212
+ class Theme(object):
213
+
214
+ """A background image and/or an overlay image applied to each capture."""
215
+
216
+ def __init__(self, name, background=None, overlay=None):
217
+ self.name = name
218
+ self.background = background
219
+ self.overlay = overlay
220
+ self._cache = {}
221
+ self._lock = threading.Lock()
222
+
223
+ def __repr__(self):
224
+ return "Theme({!r})".format(self.name)
225
+
226
+ @property
227
+ def needs_matting(self):
228
+ return self.background is not None
229
+
230
+ @property
231
+ def is_empty(self):
232
+ return self.background is None and self.overlay is None
233
+
234
+ def get_background(self, size):
235
+ """Background resized to cover ``size`` (centre crop), cached."""
236
+ key = ('bg', size)
237
+ with self._lock:
238
+ if key not in self._cache:
239
+ image = ImageOps.exif_transpose(Image.open(self.background)).convert('RGB')
240
+ self._cache[key] = ImageOps.fit(image, size, Image.Resampling.LANCZOS)
241
+ return self._cache[key]
242
+
243
+ def get_overlay(self, size):
244
+ """(RGB, alpha) overlay stretched to ``size``, cached.
245
+
246
+ Overlays should be designed at the capture aspect ratio (16:9 for a
247
+ Camera Module 3 at full resolution), they are not cropped.
248
+ """
249
+ key = ('ov', size)
250
+ with self._lock:
251
+ if key not in self._cache:
252
+ image = Image.open(self.overlay).convert('RGBA')
253
+ if image.size != size:
254
+ image = image.resize(size, Image.Resampling.LANCZOS)
255
+ self._cache[key] = (image.convert('RGB'), image.getchannel('A'))
256
+ return self._cache[key]
257
+
258
+ def preload(self, size):
259
+ if self.background:
260
+ self.get_background(size)
261
+ if self.overlay:
262
+ self.get_overlay(size)
263
+
264
+
265
+ def _find_image(folder, stem):
266
+ for ext in IMAGE_EXTENSIONS:
267
+ path = osp.join(folder, stem + ext)
268
+ if osp.isfile(path):
269
+ return path
270
+ return None
271
+
272
+
273
+ def load_themes(themes_path, include_no_theme=False):
274
+ """Each sub-folder of ``themes_path`` is a theme containing a
275
+ ``background.*`` image, an ``overlay.png`` image, or both."""
276
+ themes = []
277
+ if osp.isdir(themes_path):
278
+ for name in sorted(os.listdir(themes_path)):
279
+ folder = osp.join(themes_path, name)
280
+ if not osp.isdir(folder):
281
+ continue
282
+ theme = Theme(name.replace('_', ' '), _find_image(folder, 'background'),
283
+ _find_image(folder, 'overlay'))
284
+ if theme.is_empty:
285
+ LOGGER.warning("MODNet: theme folder '%s' has no background or overlay image", folder)
286
+ else:
287
+ themes.append(theme)
288
+ else:
289
+ LOGGER.warning("MODNet: themes folder '%s' does not exist", themes_path)
290
+
291
+ if include_no_theme or not themes:
292
+ themes.insert(0, Theme(NO_THEME_NAME))
293
+ return themes
294
+
295
+
296
+ # --------------------------------------------------------------------------
297
+ # Capture processing
298
+ # --------------------------------------------------------------------------
299
+
300
+ class CaptureProcessor(object):
301
+
302
+ def __init__(self, engine):
303
+ self.engine = engine
304
+
305
+ def process(self, image, theme):
306
+ """Return a new image with ``theme`` applied (``image`` is untouched)."""
307
+ if theme is None or theme.is_empty:
308
+ return image
309
+
310
+ start = time.time()
311
+ image = image.convert('RGB')
312
+ size = image.size
313
+
314
+ if theme.needs_matting and self.engine is not None:
315
+ rgb = np.asarray(image)
316
+ matte = self.engine.matte(rgb)
317
+ inferred = time.time()
318
+ # composite(fg, bg, mask): PIL C loop, uint8 only, no float copies
319
+ result = Image.composite(image, theme.get_background(size), Image.fromarray(matte))
320
+ LOGGER.info("MODNet: matte %.2fs, composite %.2fs (%dx%d)",
321
+ inferred - start, time.time() - inferred, size[0], size[1])
322
+ else:
323
+ if theme.needs_matting:
324
+ LOGGER.warning("MODNet: model not available, background left unchanged")
325
+ result = image.copy()
326
+
327
+ if theme.overlay:
328
+ overlay_rgb, overlay_alpha = theme.get_overlay(size)
329
+ result.paste(overlay_rgb, (0, 0), overlay_alpha)
330
+
331
+ LOGGER.info("MODNet: theme '%s' applied in %.2fs", theme.name, time.time() - start)
332
+ return result
333
+
334
+
335
+ class ModnetController(object):
336
+
337
+ """State shared by the pibooth hooks."""
338
+
339
+ def __init__(self):
340
+ self.enabled = False
341
+ self.themes = []
342
+ self.index = 0
343
+ self.selection = 'manual'
344
+ self.session_theme = None
345
+ self.show_banner = True
346
+ self.timeout = 60.0
347
+ self.capture_size = None
348
+
349
+ self.engine = None
350
+ self.processor = CaptureProcessor(None)
351
+ self.engine_ready = threading.Event()
352
+ self.executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='modnet')
353
+ self.pending = [] # futures for the captures of the current sequence
354
+ self.results = {} # id(raw capture image) -> future of processed image
355
+ self._banner = None
356
+
357
+ # -- setup ---------------------------------------------------------------
358
+
359
+ def load_engine(self, model_path, ref_size, threads, refine):
360
+ try:
361
+ path = ensure_model(model_path)
362
+ started = time.time()
363
+ engine = MattingEngine(path, ref_size, threads, refine)
364
+ engine.warmup()
365
+ self.engine = engine
366
+ self.processor = CaptureProcessor(engine)
367
+ LOGGER.info("MODNet: model ready in %.1fs (inference short side %d, %d threads, "
368
+ "edge refinement %s)", time.time() - started, engine.ref_size, threads,
369
+ 'on' if engine.refine else 'off')
370
+ except Exception as ex:
371
+ LOGGER.error("MODNet: model could not be loaded, backgrounds will not be replaced: %s", ex)
372
+ finally:
373
+ self.engine_ready.set()
374
+
375
+ @property
376
+ def current_theme(self):
377
+ return self.themes[self.index] if self.themes else None
378
+
379
+ def preload_current(self):
380
+ theme, size = self.current_theme, self.capture_size
381
+ if theme and size:
382
+ self.executor.submit(self._safe_preload, theme, size)
383
+
384
+ @staticmethod
385
+ def _safe_preload(theme, size):
386
+ try:
387
+ theme.preload(size)
388
+ except Exception as ex:
389
+ LOGGER.error("MODNet: theme '%s' images could not be loaded: %s", theme.name, ex)
390
+
391
+ # -- capture sequence ----------------------------------------------------
392
+
393
+ def start_sequence(self):
394
+ self.reset()
395
+ if not self.enabled or not self.themes:
396
+ self.session_theme = None
397
+ return
398
+ if self.selection == 'random':
399
+ self.index = random.randrange(len(self.themes))
400
+ self.session_theme = self.current_theme
401
+ if self.selection == 'cycle': # Next guest gets the next theme
402
+ self.index = (self.index + 1) % len(self.themes)
403
+ LOGGER.info("MODNet: theme for this sequence is '%s'", self.session_theme.name)
404
+
405
+ def submit_capture(self, camera, capture_data):
406
+ """Start processing a capture still held by the camera, while the
407
+ booth carries on with the next countdown."""
408
+ theme = self.session_theme
409
+ if theme is None or theme.is_empty:
410
+ return
411
+ try:
412
+ stream, effect = capture_data
413
+ # Private copy of the JPEG so the camera can still decode its own one
414
+ copy = (BytesIO(stream.getvalue()), effect)
415
+ except (TypeError, ValueError, AttributeError):
416
+ return # Not a Picamera2 JPEG stream: processed later in bind_captures()
417
+ self.pending.append(self.executor.submit(self._process_raw, camera, copy, theme))
418
+
419
+ def _process_raw(self, camera, capture_data, theme):
420
+ image = camera._post_process_capture(capture_data) # Same rotation, crop, flip and effect
421
+ return self._process_image(image, theme)
422
+
423
+ def _process_image(self, image, theme):
424
+ if theme.needs_matting:
425
+ self.engine_ready.wait(self.timeout)
426
+ return self.processor.process(image, theme)
427
+
428
+ def bind_captures(self, captures):
429
+ """Link the raw captures returned by the camera to the processed ones."""
430
+ if self.pending and len(self.pending) == len(captures):
431
+ for capture, future in zip(captures, self.pending):
432
+ self.results[id(capture)] = future
433
+ else:
434
+ if self.pending:
435
+ LOGGER.warning("MODNet: %d early captures for %d raw ones, processing again",
436
+ len(self.pending), len(captures))
437
+ self.reset()
438
+ theme = self.session_theme
439
+ if theme is not None and not theme.is_empty:
440
+ # Other camera types: process now from the decoded captures
441
+ for capture in captures:
442
+ self.results[id(capture)] = self.executor.submit(self._process_image,
443
+ capture, theme)
444
+ self.pending = []
445
+
446
+ def replace_images(self, factory):
447
+ """Swap raw captures in a picture factory for their processed version."""
448
+ images = getattr(factory, '_images', None)
449
+ if not images or not self.results:
450
+ return
451
+ replaced = []
452
+ for image in images:
453
+ future = self.results.get(id(image))
454
+ if future is None:
455
+ replaced.append(image)
456
+ continue
457
+ try:
458
+ replaced.append(future.result(timeout=self.timeout))
459
+ except Exception as ex:
460
+ LOGGER.error("MODNet: capture processing failed, using the original: %s", ex)
461
+ replaced.append(image)
462
+ factory._images = tuple(replaced)
463
+
464
+ def reset(self):
465
+ for future in self.pending:
466
+ future.cancel()
467
+ self.pending = []
468
+ self.results = {}
469
+
470
+ # -- wait screen ---------------------------------------------------------
471
+
472
+ def select(self, step):
473
+ if len(self.themes) > 1:
474
+ self.index = (self.index + step) % len(self.themes)
475
+ self._banner = None
476
+ LOGGER.info("MODNet: theme '%s' selected", self.current_theme.name)
477
+ self.preload_current()
478
+
479
+ def draw_banner(self, win):
480
+ if not (self.enabled and self.show_banner and self.selection == 'manual'
481
+ and len(self.themes) > 1 and pygame):
482
+ return
483
+ width = win.surface.get_width()
484
+ if self._banner is None or self._banner.get_width() != width:
485
+ height = max(40, win.surface.get_height() // 14)
486
+ font = pygame.font.Font(None, int(height * 0.8))
487
+ label = font.render("< {} >".format(self.current_theme.name), True, (255, 255, 255))
488
+ # Opaque: the wait screen is not repainted every frame, so a
489
+ # translucent banner would darken as it is blitted again and again
490
+ banner = pygame.Surface((width, height))
491
+ banner.fill((25, 25, 25))
492
+ banner.blit(label, label.get_rect(center=(width // 2, height // 2)))
493
+ self._banner = banner
494
+ win.surface.blit(self._banner, (0, 0))
495
+
496
+ def shutdown(self):
497
+ self.reset()
498
+ self.executor.shutdown(wait=False)
499
+
500
+
501
+ CTRL = ModnetController()
502
+
503
+
504
+ # --------------------------------------------------------------------------
505
+ # pibooth hooks
506
+ # --------------------------------------------------------------------------
507
+
508
+ @_plugin_hookimpl
509
+ def pibooth_configure(cfg):
510
+ cfg.add_option(SECTION, 'enabled', True,
511
+ "Replace backgrounds and add overlays on captures",
512
+ "Enable AI backgrounds", ['True', 'False'])
513
+ cfg.add_option(SECTION, 'themes_path', '~/.config/pibooth/themes',
514
+ "Folder of themes, one sub-folder per theme holding background.jpg/png and/or overlay.png")
515
+ cfg.add_option(SECTION, 'theme_selection', 'manual',
516
+ "How the theme is chosen: manual (left/right arrows on the wait screen), "
517
+ "cycle (next theme for each guest) or random",
518
+ "Theme selection", ['manual', 'cycle', 'random'])
519
+ cfg.add_option(SECTION, 'include_no_theme', False,
520
+ "Add a 'No theme' choice that keeps the original photo",
521
+ "Offer no theme", ['True', 'False'])
522
+ cfg.add_option(SECTION, 'show_theme_banner', True,
523
+ "Show the selected theme name on the wait screen (manual selection only)")
524
+ cfg.add_option(SECTION, 'model_path', '~/.config/pibooth/models/modnet.onnx',
525
+ "MODNet ONNX model, downloaded automatically on first start if missing")
526
+ cfg.add_option(SECTION, 'inference_size', 512,
527
+ "Short side in pixels the model runs at (multiple of 32). 512 is what MODNet "
528
+ "was trained for; 384 is faster, 640 can help large groups")
529
+ cfg.add_option(SECTION, 'threads', 3,
530
+ "CPU threads for the model (3 leaves one core free for a smooth preview)")
531
+ cfg.add_option(SECTION, 'refine_edges', True,
532
+ "Snap the matte to full resolution edges with a guided filter (needs OpenCV)")
533
+
534
+
535
+ @_plugin_hookimpl
536
+ def pibooth_startup(cfg, app):
537
+ CTRL.enabled = cfg.getboolean(SECTION, 'enabled')
538
+ CTRL.selection = cfg.get(SECTION, 'theme_selection').strip().lower()
539
+ if CTRL.selection not in ('manual', 'cycle', 'random'):
540
+ LOGGER.warning("MODNet: unknown theme_selection '%s', using manual", CTRL.selection)
541
+ CTRL.selection = 'manual'
542
+ CTRL.show_banner = cfg.getboolean(SECTION, 'show_theme_banner')
543
+ CTRL.themes = load_themes(cfg.getpath(SECTION, 'themes_path'),
544
+ cfg.getboolean(SECTION, 'include_no_theme'))
545
+ CTRL.index = 0
546
+ LOGGER.info("MODNet: %d theme(s): %s", len(CTRL.themes), ", ".join(t.name for t in CTRL.themes))
547
+
548
+ resolution = cfg.gettyped('CAMERA', 'resolution')
549
+ if isinstance(resolution, (tuple, list)) and len(resolution) == 2:
550
+ CTRL.capture_size = (int(resolution[0]), int(resolution[1]))
551
+ for theme in CTRL.themes: # Resize every theme once, in the background
552
+ CTRL.executor.submit(CTRL._safe_preload, theme, CTRL.capture_size)
553
+
554
+ if CTRL.enabled and any(theme.needs_matting for theme in CTRL.themes):
555
+ # Load in the background so pibooth starts without waiting
556
+ threading.Thread(target=CTRL.load_engine, daemon=True, name='modnet-load',
557
+ args=(cfg.getpath(SECTION, 'model_path'),
558
+ cfg.getint(SECTION, 'inference_size'),
559
+ cfg.getint(SECTION, 'threads'),
560
+ cfg.getboolean(SECTION, 'refine_edges'))).start()
561
+ else:
562
+ CTRL.engine_ready.set()
563
+
564
+ # Wrap the camera so raw captures can be matched to processed ones
565
+ camera = app.camera
566
+ original_get_captures = camera.get_captures
567
+
568
+ def get_captures():
569
+ captures = original_get_captures()
570
+ CTRL.bind_captures(captures)
571
+ return captures
572
+
573
+ camera.get_captures = get_captures
574
+
575
+
576
+ @_plugin_hookimpl(trylast=True)
577
+ def state_wait_enter(win):
578
+ CTRL.reset()
579
+ CTRL._banner = None
580
+ CTRL.draw_banner(win)
581
+
582
+
583
+ @_plugin_hookimpl(trylast=True)
584
+ def state_wait_do(win, events):
585
+ if CTRL.enabled and CTRL.selection == 'manual':
586
+ for event in events:
587
+ if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
588
+ CTRL.select(-1)
589
+ elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
590
+ CTRL.select(1)
591
+ CTRL.draw_banner(win)
592
+
593
+
594
+ @_plugin_hookimpl
595
+ def state_wait_exit(win):
596
+ CTRL.start_sequence()
597
+ if CTRL._banner is not None:
598
+ win.update() # Repaint the background to remove the theme banner
599
+
600
+
601
+ @_plugin_hookimpl
602
+ def state_capture_exit(app):
603
+ captures = getattr(app.camera, '_captures', None)
604
+ if captures:
605
+ CTRL.submit_capture(app.camera, captures[-1])
606
+
607
+
608
+ @_plugin_hookimpl(tryfirst=True)
609
+ def pibooth_setup_picture_factory(factory):
610
+ # This is a firstresult hook: plugins such as pibooth-picture-template return
611
+ # a new factory built from factory._images, which stops later plugins from
612
+ # running. Run first so the images are already replaced when they do.
613
+ CTRL.replace_images(factory)
614
+ # Return nothing: the factory is updated in place
615
+
616
+
617
+ @_plugin_hookimpl
618
+ def state_failsafe_enter():
619
+ CTRL.reset()
620
+
621
+
622
+ @_plugin_hookimpl
623
+ def pibooth_cleanup():
624
+ CTRL.shutdown()
625
+
626
+
627
+ # --------------------------------------------------------------------------
628
+ # Command line: download the model and benchmark before an event
629
+ # pibooth-modnet --download
630
+ # pibooth-modnet --test photo.jpg path/to/theme_folder [out.jpg]
631
+ # --------------------------------------------------------------------------
632
+
633
+ def _main(argv):
634
+ import logging
635
+ logging.basicConfig(level=logging.INFO, format='%(message)s')
636
+ model = osp.expanduser('~/.config/pibooth/models/modnet.onnx')
637
+
638
+ if len(argv) >= 1 and argv[0] == '--download':
639
+ print(ensure_model(model))
640
+ return 0
641
+
642
+ if len(argv) >= 3 and argv[0] == '--test':
643
+ photo, folder = argv[1], argv[2]
644
+ output = argv[3] if len(argv) > 3 else 'modnet-test.jpg'
645
+ theme = Theme(osp.basename(folder.rstrip('/')), _find_image(folder, 'background'),
646
+ _find_image(folder, 'overlay'))
647
+ image = ImageOps.exif_transpose(Image.open(photo)).convert('RGB')
648
+ engine = MattingEngine(ensure_model(model))
649
+ engine.warmup()
650
+ processor = CaptureProcessor(engine)
651
+ theme.preload(image.size)
652
+ for _ in range(3):
653
+ start = time.time()
654
+ result = processor.process(image, theme)
655
+ print("Total {:.2f}s".format(time.time() - start))
656
+ result.save(output, quality=92)
657
+ print("Saved", output)
658
+ return 0
659
+
660
+ print(__doc__.split('Install with')[0])
661
+ print("Usage:\n pibooth-modnet --download\n"
662
+ " pibooth-modnet --test photo.jpg themes/My_Theme [out.jpg]")
663
+ return 1
664
+
665
+
666
+ if __name__ == '__main__':
667
+ sys.exit(_main(sys.argv[1:]))
@@ -0,0 +1,7 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Allow ``python -m pibooth_modnet``."""
3
+
4
+ from pibooth_modnet import main
5
+
6
+ if __name__ == '__main__':
7
+ main()
@@ -0,0 +1,222 @@
1
+ Metadata-Version: 2.4
2
+ Name: pibooth-modnet
3
+ Version: 1.0.0
4
+ Summary: pibooth plugin: AI background replacement and overlays using MODNet portrait matting (ONNX Runtime, CPU)
5
+ License: MIT License
6
+
7
+ Copyright (c) 2026 pibooth-modnet contributors
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+
27
+ Project-URL: Homepage, https://github.com/peteoheat/pibooth-modnet
28
+ Project-URL: Issues, https://github.com/peteoheat/pibooth-modnet/issues
29
+ Keywords: pibooth,photobooth,raspberry pi,background removal,modnet,onnx
30
+ Classifier: Development Status :: 4 - Beta
31
+ Classifier: Environment :: Other Environment
32
+ Classifier: Intended Audience :: End Users/Desktop
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Operating System :: POSIX :: Linux
35
+ Classifier: Programming Language :: Python :: 3
36
+ Classifier: Topic :: Multimedia :: Graphics
37
+ Requires-Python: >=3.9
38
+ Description-Content-Type: text/markdown
39
+ License-File: LICENSE
40
+ Requires-Dist: pibooth>=2.1.0
41
+ Requires-Dist: numpy
42
+ Requires-Dist: Pillow
43
+ Requires-Dist: onnxruntime!=1.21.*,>=1.16
44
+ Provides-Extra: opencv
45
+ Requires-Dist: opencv-python-headless; extra == "opencv"
46
+ Dynamic: license-file
47
+
48
+ # pibooth-modnet
49
+
50
+ AI background replacement and overlays for [pibooth](https://github.com/pibooth/pibooth) 2.1.x, using the
51
+ [MODNet](https://github.com/ZHKKKe/MODNet) portrait-matting model on the CPU with ONNX Runtime.
52
+
53
+ Built for a Raspberry Pi 5 (4GB) on Raspberry Pi OS Trixie with a Camera Module 3 capturing at full resolution
54
+ (4608×2592), but it works with any camera pibooth supports.
55
+
56
+ ## How it works
57
+
58
+ 1. **Each capture is processed as soon as it is taken**, in a background thread. The work overlaps the countdown
59
+ for the next shot, so by the time the last photo is taken most of the sequence is already done.
60
+ 2. **MODNet runs at a small size** (short side 512 px by default, aspect ratio kept, no square stretching).
61
+ 3. **The matte is upsampled with a fast guided filter**, which snaps its edges to the real edges in the
62
+ full-resolution photo instead of a blurry upscale.
63
+ 4. **Full-resolution compositing** uses only C-level PIL/OpenCV operations. Backgrounds and overlays are resized once
64
+ per theme and cached.
65
+ 5. The processed captures replace the originals in pibooth's final picture (and in the wait-screen animation). The
66
+ untouched originals are still saved in pibooth's `raw` folder.
67
+
68
+ Themes with only an overlay skip the AI step entirely. If the model cannot load, the booth keeps working and simply
69
+ leaves backgrounds unchanged.
70
+
71
+ ## Install
72
+
73
+ On Raspberry Pi OS Trixie, pip refuses to install into the system Python (PEP 668), so choose one of the options below.
74
+ In both, OpenCV comes from apt so it matches the system numpy; it is optional, and without it edge refinement is
75
+ skipped.
76
+
77
+ ### Option 1: virtual environment (recommended)
78
+
79
+ ```bash
80
+ sudo apt install python3-opencv python3-picamera2 python3-venv
81
+
82
+ # --system-site-packages lets the venv see the apt-installed picamera2 and OpenCV
83
+ python3 -m venv --system-site-packages ~/pibooth-venv
84
+ source ~/pibooth-venv/bin/activate
85
+
86
+ pip install pibooth pibooth-modnet # skip "pibooth" if it is already in the venv
87
+ ```
88
+
89
+ Everything that runs pibooth must use this venv: start it with `~/pibooth-venv/bin/pibooth`, and in an autostart
90
+ entry or systemd service use that full path instead of `pibooth`. The model download command below needs the venv
91
+ too (`~/pibooth-venv/bin/pibooth-modnet --download`, or activate it first).
92
+
93
+ If pibooth is already installed in an existing venv, activate that one and run only `pip install pibooth-modnet`.
94
+
95
+ ### Option 2: system Python, no venv
96
+
97
+ ```bash
98
+ sudo apt install python3-opencv
99
+ pip install --break-system-packages pibooth-modnet
100
+ ```
101
+
102
+ This is simpler but can clash with apt-managed packages. Use it only if your pibooth is already installed this way.
103
+
104
+ ### Without the apt OpenCV
105
+
106
+ `pip install "pibooth-modnet[opencv]"` installs `opencv-python-headless` from PyPI instead. Do not install both.
107
+
108
+ pibooth discovers the plugin automatically; no `plugins =` line in `pibooth.cfg` is needed. Check the start-up log
109
+ for `Installed plugins: ... modnet-1.0.0`.
110
+
111
+ Download the model (about 26 MB) before your first event, so the booth never needs the internet:
112
+
113
+ ```bash
114
+ pibooth-modnet --download
115
+ ```
116
+
117
+ It is saved to `~/.config/pibooth/models/modnet.onnx` and checked against a SHA-256 hash. If the download fails,
118
+ copy `modnet.onnx` from the photobooth-app repository (`src/photobooth/utils/rembg/models/`) to that path.
119
+
120
+ ### Upgrading from the single-file plugin
121
+
122
+ If you used the old `pibooth-modnet.py` file, remove its path from `[GENERAL] plugins` in `pibooth.cfg` (otherwise
123
+ the plugin loads twice), then install from PyPI as above. Your `[MODNET]` settings are kept.
124
+
125
+ ### Known issue: onnxruntime 1.21 on Raspberry Pi
126
+
127
+ onnxruntime 1.21 prints many `Schema error: Trying to register schema ... already registered` lines when the model
128
+ loads. They are harmless, but 1.20.1 is clean; the package therefore excludes 1.21.x. If pip left you on 1.21, run
129
+ `pip install onnxruntime==1.20.1`.
130
+
131
+ ## Themes
132
+
133
+ Each sub-folder of `themes_path` is one theme. Underscores in folder names become spaces on screen.
134
+
135
+ ```
136
+ ~/.config/pibooth/themes/
137
+ ├── Beach/
138
+ │ ├── background.jpg # replaces the background (needs AI)
139
+ │ └── overlay.png # drawn on top of each photo (transparent PNG)
140
+ ├── Neon_Party/
141
+ │ └── background.jpg # background only
142
+ └── Wedding_Frame/
143
+ └── overlay.png # overlay only: no AI, very fast
144
+ ```
145
+
146
+ * **Backgrounds** can be any size or aspect ratio; they are centre-cropped to fill the capture.
147
+ * **Overlays** are stretched to the capture size, so design them at the capture aspect ratio: **4608×2592 (16:9)**
148
+ for a Camera Module 3 at full resolution. Use a PNG with transparency.
149
+ * If `[PICTURE] captures_cropping = True`, pibooth crops captures to fit its layout slots, which can cut off the edges
150
+ of an overlay. Either keep important overlay content near the centre or turn cropping off.
151
+ * pibooth's own `[PICTURE] overlays` option still works too; it goes over the *whole* final picture, whereas theme
152
+ overlays go over *each capture*.
153
+
154
+ ### Choosing a theme
155
+
156
+ | `theme_selection` | Behaviour |
157
+ |---|---|
158
+ | `manual` | Guests press **← / →** on the wait screen; the theme name shows in a bar at the top. |
159
+ | `cycle` | Each new guest gets the next theme. |
160
+ | `random` | A random theme per guest. |
161
+
162
+ On the wait screen, touch and the hardware buttons already mean capture/print in pibooth, so manual selection uses
163
+ the keyboard arrow keys (a small USB or Bluetooth keypad works well).
164
+
165
+ ## Configuration
166
+
167
+ All options live in the `[MODNET]` section and are added to `pibooth.cfg` automatically on first start.
168
+
169
+ | Option | Default | Notes |
170
+ |---|---|---|
171
+ | `enabled` | `True` | Also in pibooth's settings menu. |
172
+ | `themes_path` | `~/.config/pibooth/themes` | Folder of theme folders. |
173
+ | `theme_selection` | `manual` | `manual`, `cycle` or `random`. |
174
+ | `include_no_theme` | `False` | Adds a "No theme" choice that keeps the original photo. |
175
+ | `show_theme_banner` | `True` | Theme name bar on the wait screen (manual only). |
176
+ | `model_path` | `~/.config/pibooth/models/modnet.onnx` | Downloaded automatically if missing. |
177
+ | `inference_size` | `512` | Model short side. 512 is what MODNet was trained for; 384 is faster; 640 can help wide group shots. |
178
+ | `threads` | `3` | Model CPU threads. 3 leaves one core for a smooth live preview; try 4 if the preview stays smooth. |
179
+ | `refine_edges` | `True` | Guided-filter edge refinement (needs OpenCV). |
180
+
181
+ ## Test and benchmark on the Pi
182
+
183
+ Before an event, run a real capture through a theme:
184
+
185
+ ```bash
186
+ pibooth-modnet --test ~/Pictures/pibooth/raw/<date>/pibooth000.jpg ~/.config/pibooth/themes/Beach out.jpg
187
+ ```
188
+
189
+ It prints the matte and composite times for three runs and saves the result. On a 2-core x86 test machine a
190
+ 4608×2592 capture took about 0.9 s in total (0.5 s model, 0.08 s edge refinement, 0.07 s composite). Expect the Pi 5 to
191
+ be slower per capture; because each capture is processed during the next countdown, what matters is that one capture
192
+ finishes within your `[WINDOW] preview_delay`.
193
+
194
+ ## Tips for clean cut-outs
195
+
196
+ * Light guests evenly from the front; avoid strong backlight.
197
+ * A plain backdrop a metre or more behind guests helps more than any setting. Busy patterns and colours close to skin
198
+ or hair are the hardest cases.
199
+ * MODNet is trained for people. Large props held away from the body may be partly removed.
200
+
201
+ ## Credits and licences
202
+
203
+ * MODNet by Ke et al., Apache-2.0 — https://github.com/ZHKKKe/MODNet
204
+ * ONNX model file as packaged by photobooth-app, MIT — https://github.com/photobooth-app/photobooth-app
205
+ * Plugin: MIT
206
+
207
+ ## Development and releasing
208
+
209
+ ```bash
210
+ git clone https://github.com/peteoheat/pibooth-modnet && cd pibooth-modnet
211
+ pip install -e .
212
+ ```
213
+
214
+ To publish a release to PyPI:
215
+
216
+ 1. Bump `__version__` in `pibooth_modnet/__init__.py` and add an entry to `CHANGELOG.md`.
217
+ 2. One-off setup: on pypi.org add a *trusted publisher* for the project (owner `peteoheat`, repository
218
+ `pibooth-modnet`, workflow `publish.yml`, environment `pypi`), and create a `pypi` environment in the GitHub
219
+ repository settings.
220
+ 3. Create a GitHub release for the new tag. The `Publish to PyPI` workflow builds and uploads it.
221
+
222
+ To publish by hand instead: `pip install build twine && python -m build && twine upload dist/*`.
@@ -0,0 +1,8 @@
1
+ pibooth_modnet/__init__.py,sha256=t42fnEsPOvqeFJ10sezuzvbl3kK3zar8E7WWutN5Ht4,26384
2
+ pibooth_modnet/__main__.py,sha256=269JWLLCj-fc1s87htlyMVUMtfzpTO_PZ6Wm1bKUDY4,138
3
+ pibooth_modnet-1.0.0.dist-info/licenses/LICENSE,sha256=vGjsy_9EAZWREg8dv_rf95C6uVkNer1heosclsqKpBo,1084
4
+ pibooth_modnet-1.0.0.dist-info/METADATA,sha256=IBAmGKXjkB-xX2IvW2AVF0SbjtPGF5CcE0usz6EbxX4,10565
5
+ pibooth_modnet-1.0.0.dist-info/WHEEL,sha256=a-udL2m4V_6Yn8b-uKzWb12RjRxwwMo6ohYFM24tpaY,91
6
+ pibooth_modnet-1.0.0.dist-info/entry_points.txt,sha256=pcIpdhC5i3SoztvmG6dYI5JFG8MFbgXTrwWGhvOLqIs,98
7
+ pibooth_modnet-1.0.0.dist-info/top_level.txt,sha256=3QDzt7qZ9LYIc0OJp_bb6uaY-yTWuHqVP2vPBLNoUQE,15
8
+ pibooth_modnet-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,5 @@
1
+ [console_scripts]
2
+ pibooth-modnet = pibooth_modnet:main
3
+
4
+ [pibooth]
5
+ pibooth_modnet = pibooth_modnet
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pibooth-modnet contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pibooth_modnet