-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMorphMe.py
More file actions
682 lines (578 loc) · 26.1 KB
/
Copy pathMorphMe.py
File metadata and controls
682 lines (578 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
import dearpygui.dearpygui as dpg
import morpher as m
import cv2
import numpy as np
import threading
import time
import Segmenter
import datetime
from tkinter import filedialog, Tk
from ultralytics import YOLO
# ── State ────────────────────────────────────────────────────────────────────
cap = None
running = False
process_thread = None
processed_frame_rgba = None # UI thread uses this flat array
processed_frame_bgr = None # For saving snapshots
processed_frame_id = 0 # incremented each time a new frame is ready
last_displayed_id = -1 # last frame id pushed to the texture
processed_lock = threading.Lock()
transform_enabled = False
# Camera and performance metrics
camera_fps = 0.0
frame_count = 0
fps_timestamp = time.time()
# INCREASED: Camera Capture & UI Output Resolutions
FEED_W, FEED_H = 640, 480 # Increased capture resolution
THUMB_W, THUMB_H = 960, 720 # Increased UI viewing resolution
MORPH_RES = 128 # Left at 128 for Morph engine performance
VIEWPORT_W = 980
VIEWPORT_H = 900
# ── Target image state ───────────────────────────────────────────────────────
target_image_raw = None
target_image_edit = None
target_weights = None
target_path_short = ""
target_path_full = ""
target_lock = threading.Lock()
# INCREASED: UI Panel & Preview Dimensions
PREVIEW_W, PREVIEW_H = 300, 300
PANEL_PAD = 10
PANEL_LABEL_H = 30
PATH_FRAME_W = 480
PATH_FRAME_H = 30
PREVIEW_FRAME_W = PREVIEW_W + (PANEL_PAD * 2)
PREVIEW_FRAME_H = PREVIEW_H + (PANEL_PAD * 2)
FEED_PANEL_W = FEED_W + (PANEL_PAD * 2)
FEED_PANEL_H = FEED_H + (PANEL_PAD * 2) + PANEL_LABEL_H
OUTPUT_PANEL_W = THUMB_W + (PANEL_PAD * 2)
OUTPUT_PANEL_H = THUMB_H + (PANEL_PAD * 2) + PANEL_LABEL_H
# Crop/zoom state — persists between opens
crop_state = {
"zoom": 1.0,
"offset_x": 0,
"offset_y": 0,
"pan_x_max": 1000,
"pan_y_max": 1000,
}
# Face detection model
yolo_model = YOLO("best.pt", task="detect")
yolo_model.to("cuda")
# ── One-time setup: textures and handler ─────────────────────────────────────
def setup_persistent_items():
with dpg.texture_registry():
dpg.add_raw_texture(
width=PREVIEW_W, height=PREVIEW_H,
default_value=[0.15] * (PREVIEW_W * PREVIEW_H * 4),
format=dpg.mvFormat_Float_rgba,
tag="target_preview_texture"
)
# Global handler for keyboard events
with dpg.handler_registry():
dpg.add_key_press_handler(key=dpg.mvKey_Escape, callback=lambda: dpg.stop_dearpygui())
with dpg.item_handler_registry(tag="preview_click_handler"):
dpg.add_item_clicked_handler(callback=on_preview_clicked)
with dpg.theme(tag="compact_path_frame_theme"):
with dpg.theme_component(dpg.mvChildWindow):
dpg.add_theme_style(dpg.mvStyleVar_WindowPadding, 8, 0)
with dpg.theme(tag="reset_button_theme"):
with dpg.theme_component(dpg.mvButton):
dpg.add_theme_color(dpg.mvThemeCol_Button, (220, 40, 40, 255))
dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, (240, 60, 60, 255))
dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, (190, 20, 20, 255))
with dpg.theme(tag="finalize_button_theme"):
with dpg.theme_component(dpg.mvButton):
dpg.add_theme_color(dpg.mvThemeCol_Button, (40, 220, 40, 255))
dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, (60, 240, 60, 255))
dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, (20, 190, 20, 255))
with dpg.theme_component(dpg.mvButton, enabled_state=False):
dpg.add_theme_color(dpg.mvThemeCol_Button, (70, 120, 70, 255))
dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, (70, 120, 70, 255))
dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, (70, 120, 70, 255))
dpg.add_theme_color(dpg.mvThemeCol_Text, (210, 230, 210, 255))
# Real-time FPS box styling
with dpg.theme(tag="fps_theme"):
with dpg.theme_component(dpg.mvChildWindow):
dpg.add_theme_color(dpg.mvThemeCol_Border, (0, 255, 255, 255))
dpg.add_theme_color(dpg.mvThemeCol_ChildBg, (20, 20, 20, 150))
dpg.add_theme_style(dpg.mvStyleVar_WindowPadding, 8, 6)
# Switch style checkbox toggle
with dpg.theme(tag="switch_theme"):
with dpg.theme_component(dpg.mvCheckbox):
dpg.add_theme_color(dpg.mvThemeCol_CheckMark, (0, 255, 170, 255))
dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (100, 100, 90, 255))
dpg.add_theme_color(dpg.mvThemeCol_FrameBgHovered, (130, 130, 100, 255))
dpg.add_theme_color(dpg.mvThemeCol_FrameBgActive, (50, 100, 80, 255))
dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 4)
# ── Helpers ───────────────────────────────────────────────────────────────────
def bgr_to_rgba_flat(img, w, h):
img_resized = cv2.resize(img, (w, h))
img_rgba = cv2.cvtColor(img_resized, cv2.COLOR_BGR2RGBA)
return img_rgba.astype(np.float32).flatten() * (1.0 / 255.0)
def apply_crop_zoom(img):
if img is None:
return None
h, w = img.shape[:2]
zoom = crop_state["zoom"]
view_w = max(1, int(w / zoom))
view_h = max(1, int(h / zoom))
ox = int(np.clip(crop_state["offset_x"], 0, w - view_w))
oy = int(np.clip(crop_state["offset_y"], 0, h - view_h))
crop_state["offset_x"] = ox
crop_state["offset_y"] = oy
cropped = img[oy:oy + view_h, ox:ox + view_w]
ch, cw = cropped.shape[:2]
side = min(ch, cw)
sy = (ch - side) // 2
sx = (cw - side) // 2
return cropped[sy:sy + side, sx:sx + side]
def refresh_preview():
global target_image_edit
if target_image_raw is None:
return
edited = apply_crop_zoom(target_image_raw)
target_image_edit = edited
dpg.set_value("target_preview_texture", bgr_to_rgba_flat(edited, PREVIEW_W, PREVIEW_H))
def open_file_dialog():
root = Tk()
root.withdraw()
root.attributes("-topmost", True)
path = filedialog.askopenfilename(
title="Select Target Image",
filetypes=[("Image files", "*.png *.jpg *.jpeg *.bmp *.webp"), ("All files", "*.*")]
)
root.destroy()
return path
# ── Segmentation worker ───────────────────────────────────────────────────────
def run_segmentation_worker(img):
global target_weights
dpg.set_value("seg_status", "Segmenting... please wait")
dpg.configure_item("finalize_btn", enabled=False)
try:
target_size = MORPH_RES
resized = cv2.resize(img, (target_size, target_size))
mask = Segmenter.Segmenter().segment(resized)
weights = mask.flatten().tolist()
with target_lock:
target_weights = weights
dpg.set_value("seg_status", "Done! Target image ready.")
dpg.set_value("status_text", "Status: target image set")
if target_path_full and dpg.does_item_exist("target_path_label"):
dpg.set_value("target_path_label", target_path_full)
dpg.configure_item("target_path_label", color=(180, 220, 180))
if dpg.does_item_exist("target_window"):
dpg.configure_item("target_window", show=False)
except Exception as e:
dpg.set_value("seg_status", f"Segmentation failed: {e}")
finally:
dpg.configure_item("finalize_btn", enabled=True)
# ── Popup window ──────────────────────────────────────────────────────────────
def open_target_window():
if dpg.does_item_exist("target_window"):
if not dpg.is_item_shown("target_window"):
dpg.configure_item("target_window", show=True)
dpg.focus_item("target_window")
return
# INCREASED: Target Popup Dimensions
WIN_W = 420
CTRL_W = WIN_W - 32
with dpg.window(
label="Select Target Image",
tag="target_window",
width=WIN_W,
pos=(450, 100),
modal=False,
no_close=False,
no_resize=True,
autosize=True,
no_scrollbar=True,
no_scroll_with_mouse=True,
):
dpg.add_text("Click image to load from file:")
dpg.add_spacer(height=6)
with dpg.table(
header_row=False, resizable=False,
policy=dpg.mvTable_SizingStretchProp,
borders_innerV=False, borders_outerV=False,
borders_innerH=False, borders_outerH=False,
):
dpg.add_table_column(init_width_or_weight=1.0)
dpg.add_table_column(width_fixed=True, init_width_or_weight=PREVIEW_FRAME_W)
dpg.add_table_column(init_width_or_weight=1.0)
with dpg.table_row():
dpg.add_table_cell()
with dpg.table_cell():
with dpg.child_window(
width=PREVIEW_FRAME_W, height=PREVIEW_FRAME_H,
border=True, no_scrollbar=True, no_scroll_with_mouse=True,
):
dpg.add_image(
"target_preview_texture",
width=PREVIEW_W, height=PREVIEW_H,
tag="target_preview_image"
)
dpg.add_table_cell()
dpg.bind_item_handler_registry("target_preview_image", "preview_click_handler")
dpg.add_spacer(height=8)
with dpg.table(
header_row=False, resizable=False,
policy=dpg.mvTable_SizingStretchProp,
borders_innerV=False, borders_outerV=False,
borders_innerH=False, borders_outerH=False,
):
dpg.add_table_column(init_width_or_weight=1.0)
dpg.add_table_column(width_fixed=True, init_width_or_weight=PREVIEW_FRAME_W)
dpg.add_table_column(init_width_or_weight=1.0)
with dpg.table_row():
dpg.add_table_cell()
with dpg.table_cell():
loaded_label = target_path_short if target_path_short else "No image loaded"
loaded_color = (200, 200, 200) if target_path_short else (130, 130, 130)
dpg.add_text(loaded_label, tag="loaded_path_text", color=loaded_color, wrap=PREVIEW_FRAME_W)
dpg.add_table_cell()
dpg.add_separator()
dpg.add_text("Zoom:")
dpg.add_slider_float(
tag="zoom_slider", min_value=1.0, max_value=5.0,
default_value=crop_state["zoom"], width=CTRL_W,
callback=on_zoom_change
)
dpg.add_spacer(height=6)
dpg.add_text("Pan X (left ↔ right):")
dpg.add_slider_int(
tag="pan_x_slider", min_value=0, max_value=crop_state["pan_x_max"],
default_value=crop_state["offset_x"], width=CTRL_W,
callback=on_pan_change
)
dpg.add_spacer(height=6)
dpg.add_text("Pan Y (top ↕ bottom):")
dpg.add_slider_int(
tag="pan_y_slider", min_value=0, max_value=crop_state["pan_y_max"],
default_value=crop_state["offset_y"], width=CTRL_W,
callback=on_pan_change
)
dpg.add_spacer(height=6)
dpg.add_separator()
dpg.add_text("", tag="seg_status", color=(200, 220, 70))
dpg.add_button(
label="Reset", tag="reset_btn", callback=reset_crop, width=CTRL_W
)
dpg.bind_item_theme("reset_btn", "reset_button_theme")
dpg.add_spacer(height=4)
dpg.add_button(
label="Segment & Finalize", tag="finalize_btn",
callback=on_finalize, width=CTRL_W, enabled=(target_image_raw is not None),
)
dpg.bind_item_theme("finalize_btn", "finalize_button_theme")
# ── Popup callbacks ───────────────────────────────────────────────────────────
def on_preview_clicked(sender, app_data):
global target_image_raw, target_path_short, target_path_full
path = open_file_dialog()
if not path:
return
img = cv2.imread(path)
if img is None:
dpg.set_value("loaded_path_text", "Failed to load image.")
return
target_image_raw = img
h, w = img.shape[:2]
crop_state["zoom"] = 1.0
crop_state["offset_x"] = 0
crop_state["offset_y"] = 0
crop_state["pan_x_max"] = w
crop_state["pan_y_max"] = h
for tag, val in [("zoom_slider", 1.0), ("pan_x_slider", 0), ("pan_y_slider", 0)]:
if dpg.does_item_exist(tag):
dpg.set_value(tag, val)
if dpg.does_item_exist("pan_x_slider"):
dpg.configure_item("pan_x_slider", max_value=w)
if dpg.does_item_exist("pan_y_slider"):
dpg.configure_item("pan_y_slider", max_value=h)
target_path_full = path
target_path_short = path.replace("\\", "/").split("/")[-1]
if dpg.does_item_exist("loaded_path_text"):
dpg.set_value("loaded_path_text", target_path_short)
dpg.configure_item("loaded_path_text", color=(200, 200, 200))
if dpg.does_item_exist("finalize_btn"):
dpg.configure_item("finalize_btn", enabled=True)
if dpg.does_item_exist("seg_status"):
dpg.set_value("seg_status", "")
refresh_preview()
def on_zoom_change(sender, value):
crop_state["zoom"] = value
refresh_preview()
def on_pan_change(sender, app_data):
crop_state["offset_x"] = dpg.get_value("pan_x_slider")
crop_state["offset_y"] = dpg.get_value("pan_y_slider")
refresh_preview()
def reset_crop():
if target_image_raw is None:
return
h, w = target_image_raw.shape[:2]
crop_state["zoom"] = 1.0
crop_state["offset_x"] = 0
crop_state["offset_y"] = 0
for tag, val in [("zoom_slider", 1.0), ("pan_x_slider", 0), ("pan_y_slider", 0)]:
if dpg.does_item_exist(tag):
dpg.set_value(tag, val)
if dpg.does_item_exist("pan_x_slider"):
dpg.configure_item("pan_x_slider", max_value=w)
if dpg.does_item_exist("pan_y_slider"):
dpg.configure_item("pan_y_slider", max_value=h)
refresh_preview()
def on_finalize():
if target_image_raw is None:
return
edited = apply_crop_zoom(target_image_raw)
threading.Thread(target=run_segmentation_worker, args=(edited,), daemon=True).start()
def on_transform_toggle(sender, app_data):
global transform_enabled
transform_enabled = bool(app_data)
# ── Main pipeline ─────────────────────────────────────────────────────────────
def transform_frame(frame):
start_time = time.time()
with target_lock:
weights = target_weights
target_img = target_image_edit
if weights is None or target_img is None:
return frame
# detect face
result = yolo_model(frame, verbose=False, device=0)
box = result[0].boxes
if box is None or len(box) == 0 :
return frame # if no face detected, just return the frame
# crop the detected face
x1, y1, x2, y2 = map(int, box[0].xyxy[0])
frame_h, frame_w = frame.shape[:2]
x1 = max(0, min(x1, frame_w - 1))
y1 = max(0, min(y1, frame_h - 1))
x2 = max(0, min(x2, frame_w))
y2 = max(0, min(y2, frame_h))
if x2 <= x1 or y2 <= y1:
return frame
face = frame[y1:y2, x1:x2]
# resize the face and target to fit the morpher requirements
source = cv2.resize(face, (MORPH_RES, MORPH_RES))
target = cv2.resize(target_img, (MORPH_RES, MORPH_RES))
# transform form np array to list of tuples to pass to rust code
source_flat = source.reshape(-1, 3).astype(np.int32).tolist()
target_flat = target.reshape(-1, 3).astype(np.int32).tolist()
source = [tuple(px) for px in source_flat]
target = [tuple(px) for px in target_flat]
# pass to morpher
morphed, time_taken = m.morph(source, target, weights, MORPH_RES, 1,13) #get back to the last 2 values later
morphed = np.array(morphed, dtype=np.uint8).reshape(MORPH_RES,MORPH_RES,3) # convert again to numpy array
# resize the morphes face to the yolo box size
morphed = cv2.resize(morphed, (x2 - x1, y2- y1))
frame[y1:y2, x1:x2] = morphed #paste the morphed face back to the original frame
end_time = time.time()
print(f"Time taken: {(end_time - start_time):.3f} sec")
return frame
def process_loop():
global cap, running, processed_frame_rgba, processed_frame_bgr, processed_frame_id
global frame_count, fps_timestamp, camera_fps
while running:
if cap is None:
time.sleep(0.05)
continue
ret, frame = cap.read()
if not ret or frame is None or frame.size == 0:
time.sleep(0.01)
continue
try:
# Internal Camera FPS logic
frame = cv2.flip(frame,1)
frame_count += 1
now = time.time()
if now - fps_timestamp >= 1.0:
camera_fps = frame_count / (now - fps_timestamp)
frame_count = 0
fps_timestamp = now
safe_frame = frame.copy()
output_bgr = transform_frame(safe_frame) if transform_enabled else safe_frame
output_rgba = bgr_to_rgba_flat(output_bgr, THUMB_W, THUMB_H)
with processed_lock:
processed_frame_rgba = output_rgba
processed_frame_bgr = output_bgr
processed_frame_id += 1
except Exception as exc:
print(f"Processing error: {exc}")
def update_textures():
global last_displayed_id
with processed_lock:
fid = processed_frame_id
tex_data = processed_frame_rgba
if tex_data is not None and fid != last_displayed_id:
last_displayed_id = fid
try:
dpg.set_value("output_texture", tex_data)
except Exception:
pass
# Update FPS text using both custom camera FPS and official UI frame rate
dpg.set_value("fps_text", f"Cam: {camera_fps:.1f} | UI: {dpg.get_frame_rate():.0f}")
def start_camera():
global cap, running, process_thread, processed_frame_id
if running: return
cap = cv2.VideoCapture(0)
if cap is None or not cap.isOpened():
dpg.set_value("status_text", "Status: camera not found")
return
cap.set(cv2.CAP_PROP_FRAME_WIDTH, FEED_W)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, FEED_H)
if hasattr(cv2, "CAP_PROP_BUFFERSIZE"):
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
with processed_lock:
processed_frame_rgba = None
processed_frame_bgr = None
processed_frame_id = 0
running = True
process_thread = threading.Thread(target=process_loop, daemon=True)
process_thread.start()
dpg.set_value("status_text", "Status: running")
def stop_camera():
global running, cap, process_thread
running = False
if process_thread and process_thread.is_alive():
process_thread.join(timeout=0.5)
process_thread = None
if cap:
cap.release()
cap = None
def save_snapshot():
with processed_lock:
frame = processed_frame_bgr.copy() if processed_frame_bgr is not None else None
if frame is not None:
cv2.imwrite(f"Snapshots/snapshot{datetime.datetime.now().strftime('%d-%m-%Y')}.png", frame)
dpg.set_value("status_text", "Status: saved snapshot.png")
# ── UI Auto-Layout Worker ─────────────────────────────────────────────────────
def update_camera_layout():
"""Dynamically scales and centers the image item."""
try:
rect = dpg.get_item_rect_size("camera_container")
if not rect or rect[0] <= 0: return
cw, ch = rect
# Constants for top-bar spacing and padding
pad_y_top = 65 # Space for "Camera Output" text and separator
avail_w = cw - 20
avail_h = ch - pad_y_top - 20
if avail_w < 10 or avail_h < 10: return
# 4:3 Aspect Ratio logic
target_aspect = 4.0 / 3.0
current_aspect = avail_w / avail_h
if current_aspect > target_aspect:
new_h = avail_h
new_w = avail_h * target_aspect
else:
new_w = avail_w
new_h = avail_w / target_aspect
# --- Centering Calculation ---
# Calculate horizontal and vertical gaps
gap_x = (cw - new_w) / 2
gap_y = pad_y_top + ((avail_h - new_h) / 2)
# Apply size and position
dpg.configure_item("camera_image", width=int(new_w), height=int(new_h))
dpg.set_item_pos("camera_image", [int(gap_x), int(gap_y)])
except Exception:
pass
# ── Build UI ──────────────────────────────────────────────────────────────────
dpg.create_context()
# INCREASED: Scale all standard UI components (fonts, checkboxes, buttons, padding)
dpg.set_global_font_scale(1.25)
setup_persistent_items()
with dpg.texture_registry():
dpg.add_raw_texture(
width=THUMB_W, height=THUMB_H,
default_value=[0.1] * (THUMB_W * THUMB_H * 4),
format=dpg.mvFormat_Float_rgba,
tag="output_texture"
)
with dpg.window(
label="MorphMe",
tag="main_window",
no_scrollbar=True,
no_scroll_with_mouse=True,
no_collapse=True,
no_move=True,
no_resize=True
):
# Top bar wrapped in a zero-border table to push the FPS readout to the right
with dpg.table(header_row=False, borders_innerV=False, borders_outerV=False, borders_innerH=False, borders_outerH=False):
dpg.add_table_column()
# INCREASED layout
dpg.add_table_column(width_fixed=True, init_width_or_weight=200)
with dpg.table_row():
with dpg.table_cell():
dpg.add_text("Status: idle", tag="status_text")
with dpg.table_cell():
with dpg.child_window(tag="fps_box", width=200, height=36, border=True, no_scrollbar=True):
dpg.add_text("Cam: 0 | UI: 0", tag="fps_text")
dpg.bind_item_theme("fps_box", "fps_theme")
dpg.add_separator()
# Target image row
with dpg.table(header_row=False, borders_innerV=False, borders_outerV=False, borders_innerH=False, borders_outerH=False, policy=dpg.mvTable_SizingStretchProp):
dpg.add_table_column(init_width_or_weight=1.0) # Stretchy left side
# INCREASED layout
dpg.add_table_column(width_fixed=True, init_width_or_weight=175) # Fixed right side
with dpg.table_row():
with dpg.table_cell():
# Wrap the left-side items in a horizontal group
with dpg.group(horizontal=True):
dpg.add_text("Target image:")
with dpg.child_window(
tag="target_path_frame",
width=PATH_FRAME_W, height=PATH_FRAME_H,
border=True,
show=True,
):
dpg.add_text("No image selected", tag="target_path_label", color=(130, 130, 130))
dpg.bind_item_theme("target_path_frame", "compact_path_frame_theme")
# Action operations placed together
dpg.add_button(label="Choose image", callback=open_target_window)
with dpg.table_cell():
# Switch-Styled Toggle is now isolated in the right cell
dpg.add_checkbox(
label="Enable Transform",
tag="transform_toggle",
default_value=False,
callback=on_transform_toggle,
)
dpg.bind_item_theme("transform_toggle", "switch_theme")
dpg.add_separator()
with dpg.group():
# Added the tag "camera_container" here so we can measure it
with dpg.child_window(
tag="camera_container",
border=True,
no_scrollbar=True,
no_scroll_with_mouse=True,
):
with dpg.table(header_row=False, borders_innerV=False, borders_outerV=False, borders_innerH=False, borders_outerH=False, policy=dpg.mvTable_SizingStretchProp):
dpg.add_table_column(init_width_or_weight=1.0)
# INCREASED layout
dpg.add_table_column(width_fixed=True, init_width_or_weight=130)
with dpg.table_row():
with dpg.table_cell():
dpg.add_text("Camera Output")
with dpg.table_cell():
dpg.add_button(label="Save Snapshot", callback=save_snapshot)
dpg.add_separator()
# Added the tag "camera_image" here so we can resize it
dpg.add_image("output_texture", tag="camera_image", width=THUMB_W, height=THUMB_H)
# INCREASED: Main Viewport size
dpg.create_viewport(title="MorphMe", width=VIEWPORT_W, height=VIEWPORT_H, resizable=False, decorated=False)
screen_w = 1920 # You can use a library like 'screeninfo' for dynamic detection
screen_h = 1080
start_x = (screen_w // 2) - (VIEWPORT_W // 2)
start_y = (screen_h // 2) - (VIEWPORT_H // 2)
dpg.configure_viewport(0, x_pos=start_x, y_pos=start_y)
dpg.setup_dearpygui()
dpg.show_viewport()
dpg.set_primary_window("main_window", True)
# ── Explicit Render Loop ──────────────────────────────────────────────────────
start_camera()
while dpg.is_dearpygui_running():
update_camera_layout() # <-- Continuously updates scale on resize
update_textures()
dpg.render_dearpygui_frame()
stop_camera()
dpg.destroy_context()