Project

General

Profile

Files » ui.py

the GUI of the program - Pratama Kwee BRANDON, 11/12/2025 08:22 PM

 
1
import tkinter as tk
2
from tkinter import ttk, messagebox
3
from PIL import Image, ImageTk
4
import os
5
import altmain
6
import video_processing
7
import cv2
8
import config_reader
9

    
10
class ImageDisplayApp:
11
    """
12
    @brief Main GUI application class for image processing and display
13
    
14
    @details This class provides a graphical interface for splitting images,
15
    processing videos, and displaying results with various blending options.
16
    """
17
    def __init__(self, root):
18
        """
19
        @brief Constructor for ImageDisplayApp class
20
        
21
        @param root Tkinter root window object
22
        """
23
        self.root = root
24
        self.root.title("Image Split & Update GUI")
25
        self.root.geometry("1000x750")
26
        self.root.configure(bg="#f5f5f5")
27
        self.cfg = config_reader.ConfigReader("config.ini")
28

    
29
        self.image_paths = {
30
            "main": self.cfg.get_image_path(),
31
            "left": "left.png",
32
            "right": "right.png"
33
        }
34

    
35
        self.image_frame = ttk.Frame(self.root, padding=10)
36
        self.image_frame.pack(pady=20)
37
        self.processor = altmain.ProjectionSplit()
38
        self.video_processor = video_processing.VideoProcessing("input.mp4")
39
        self.fps = 60
40
        self.is_running = True
41

    
42
        self.labels = {}
43
        for key in self.image_paths:
44
            lbl = ttk.Label(self.image_frame)
45
            lbl.pack(side=tk.LEFT, padx=10)
46
            self.labels[key] = lbl
47

    
48
        control_frame = ttk.Frame(self.root, padding=10)
49
        control_frame.pack(pady=10)
50

    
51
        ttk.Label(control_frame, text="Overlap (pixels):").grid(row=0, column=0, padx=5)
52
        self.param_var = tk.IntVar(value=self.cfg.get_overlap())
53
        entry = ttk.Entry(control_frame, textvariable=self.param_var, width=8)
54
        entry.grid(row=0, column=1, padx=5)
55

    
56
        ttk.Label(control_frame, text="Blend Type:").grid(row=0, column=2, padx=5)
57
        self.blend_var = tk.StringVar(value=self.cfg.get_blend_mode())
58
        blend_box = ttk.Combobox(
59
            control_frame,
60
            textvariable=self.blend_var,
61
            values=["linear", "quadratic", "gaussian"],
62
            state="readonly",
63
            width=12
64
        )
65
        blend_box.grid(row=0, column=3, padx=5)
66

    
67
        entry.bind("<FocusOut>", lambda e: self.debounced_update())
68
        blend_box.bind("<<ComboboxSelected>>", lambda e: self.debounced_update())
69

    
70
        timer_frame = ttk.Frame(self.root, padding=10)
71
        timer_frame.pack(pady=5)
72

    
73
        ttk.Label(timer_frame, text="Start Time (HH:MM:SS):").pack(side=tk.LEFT, padx=5)
74
        self.start_time_var = tk.StringVar(value="14:30:00")  # default example
75
        ttk.Entry(timer_frame, textvariable=self.start_time_var, width=10).pack(side=tk.LEFT, padx=5)
76

    
77
        ttk.Button(
78
            timer_frame,
79
            text="Start at Time",
80
            command=self.schedule_start
81
        ).pack(side=tk.LEFT, padx=10)
82

    
83

    
84
        fullscreen_frame = ttk.Frame(self.root, padding=10)
85
        fullscreen_frame.pack(pady=5)
86

    
87
        ttk.Button(
88
            fullscreen_frame,
89
            text="Show Left Fullscreen",
90
            command=lambda: self.show_fullscreen("left")
91
        ).pack(side=tk.LEFT, padx=10)
92

    
93
        ttk.Button(
94
            fullscreen_frame,
95
            text="Show Right Fullscreen",
96
            command=lambda: self.show_fullscreen("right")
97
        ).pack(side=tk.LEFT, padx=10)
98
        ttk.Button(
99
            fullscreen_frame,
100
            text="Run Video",
101
            command=self.run_video
102
        ).pack(side=tk.LEFT, padx=10)
103

    
104
        self._update_after_id = None
105

    
106
    def debounced_update(self):
107
        """
108
        @brief Debounced update to prevent rapid consecutive calls
109
        
110
        @details Cancels pending updates and schedules a new one after delay
111
        to prevent multiple rapid updates when parameters change.
112
        """
113
        if self._update_after_id is not None:
114
            self.root.after_cancel(self._update_after_id)
115
        self._update_after_id = self.root.after(500, self.run_and_update)
116

    
117
    def show_fullscreen(self, key):
118
        """
119
        @brief Display image in fullscreen mode
120
        
121
        @param key Image identifier ("left" or "right")
122
        @exception FileNotFoundError If image file does not exist
123
        """
124
        path = self.image_paths.get(key)
125
        if not os.path.exists(path):
126
            messagebox.showwarning("Missing Image", f"{path} not found.")
127
            return
128

    
129
        fullscreen = tk.Toplevel(self.root)
130
        fullscreen.attributes("-fullscreen", True)
131
        fullscreen.configure(bg="black")
132
        fullscreen.bind("<Escape>", lambda e: fullscreen.destroy())
133

    
134
        lbl = ttk.Label(fullscreen, background="black")
135
        lbl.pack(expand=True)
136

    
137
        def update_fullscreen():
138
            """
139
            @brief Update fullscreen display with current image
140
            
141
            @details Continuously updates the fullscreen display with
142
            the current image, resizing to fit screen while maintaining aspect ratio.
143
            """
144
            if not os.path.exists(path):
145
                return
146
            try:
147
                img = Image.open(path)
148
                screen_w = fullscreen.winfo_screenwidth()
149
                screen_h = fullscreen.winfo_screenheight()
150

    
151
                img_ratio = img.width / img.height
152
                screen_ratio = screen_w / screen_h
153

    
154
                if img_ratio > screen_ratio:
155
                    new_w = screen_w
156
                    new_h = int(screen_w / img_ratio)
157
                else:
158
                    new_h = screen_h
159
                    new_w = int(screen_h * img_ratio)
160

    
161
                img = img.resize((new_w, new_h), Image.LANCZOS)
162
                photo = ImageTk.PhotoImage(img)
163
                lbl.configure(image=photo)
164
                lbl.image = photo
165
            except Exception as e:
166
                print("Fullscreen update error:", e)
167

    
168
            fullscreen.after(100, update_fullscreen)
169

    
170
        update_fullscreen()
171

    
172
    def _update_image_widget(self, key, np_image):
173
        """
174
        @brief Update individual image widget with new image data
175
        
176
        @param key Widget identifier
177
        @param np_image Numpy array containing image data
178
        """
179
        if np_image is None:
180
            self.labels[key].configure(text=f"No image data", image="")
181
            self.labels[key].image = None
182
            return
183

    
184
        if np_image.shape[2] == 4:
185
            np_image = cv2.cvtColor(np_image, cv2.COLOR_BGRA2RGBA)
186
        else:
187
            np_image = cv2.cvtColor(np_image, cv2.COLOR_BGR2RGB)
188

    
189
        img = Image.fromarray(np_image)
190
        img = img.resize((300, 300))
191

    
192
        photo = ImageTk.PhotoImage(img)
193

    
194
        self.labels[key].configure(image=photo, text="")
195
        self.labels[key].image = photo
196

    
197
    def run_and_update(self):
198
        """
199
        @brief Process images and update display
200
        
201
        @details Applies current parameters to process images and
202
        updates all image displays with the results.
203
        
204
        @exception Exception Catches and displays any processing errors
205
        """
206
        try:
207
            overlap_value = int(self.param_var.get())
208
            blend_type = self.blend_var.get()
209
            self.processor.process_images(overlap_value, blend_type)
210
            self.update_images_from_arrays({"left": self.processor.image_left, "right": self.processor.image_right,
211
                                            "main": self.processor.image_main})
212
        except Exception as e:
213
            import traceback
214
            traceback.print_exc()
215
            print("TYPE OF E:", type(e))
216
            print("VALUE OF E:", repr(e))
217
            messagebox.showerror("Error", repr(e))
218
    def run_video(self):
219
        """
220
        @brief Process and display next video frame
221
        
222
        @details Retrieves next frame from video, processes it with
223
        current parameters, and updates the display.
224
        """
225

    
226
        if not self.is_running:
227
            return
228

    
229
        image = self.video_processor.get_next_frame()
230
        if image is None:
231
            print("End of video.")
232
            self.is_running = False
233
            return
234

    
235
        try:
236
            overlap_value = int(self.param_var.get())
237
            blend_type = self.blend_var.get()
238
            self.processor.process_frame(image, overlap_value, blend_type)
239
            self.update_images_from_arrays({
240
                "left": self.processor.image_left,
241
                "right": self.processor.image_right,
242
                "main": self.processor.image_main
243
            })
244
        except Exception as e:
245
            import traceback
246
            traceback.print_exc()
247
            messagebox.showerror("Error", repr(e))
248
            self.is_running = False
249
            return
250

    
251
        delay = int(1000 / self.fps)
252
        self.root.after(delay, self.run_video)
253

    
254
    def start_video(self):
255
        """
256
        @brief Start video processing and display
257
        """
258
        self.is_running = True
259
        self.run_video()
260

    
261
    def stop_video(self):
262
        """
263
        @brief Stop video processing and release resources
264
        """
265
        self.is_running = False
266
        if self.video_processor.cap is not None:
267
            self.video_processor.release()
268

    
269
    def update_images_from_arrays(self, images: dict):
270
        """
271
        @brief Update all image widgets from numpy arrays
272
        
273
        @param images Dictionary of image identifiers and numpy arrays
274
        """
275
        for key, np_img in images.items():
276
            self._update_image_widget(key, np_img)
277

    
278
    def schedule_start(self):
279
        """
280
        @brief Schedule video to start at specified time
281
        
282
        @details Parses time string and starts checking loop to begin
283
        video playback at the specified time.
284
        """
285

    
286
        import datetime
287
        target_str = self.start_time_var.get().strip()
288
        try:
289
            target_time = datetime.datetime.strptime(target_str, "%H:%M:%S").time()
290
            print(f"[Timer] Scheduled video start at {target_time}.")
291
            self._check_time_loop(target_time)
292
        except ValueError:
293
            print("[Timer] Invalid time format. Please use HH:MM:SS (e.g., 14:30:00).")
294

    
295
    def _check_time_loop(self, target_time):
296
        """
297
        @brief Internal method to check if target time has been reached
298
        
299
        @param target_time Target time to start video
300
        """
301

    
302
        import datetime
303
        now = datetime.datetime.now().time()
304

    
305
        if now >= target_time:
306
            print("[Timer] Target time reached — starting video.")
307
            self.start_video()
308
            return
309

    
310
        self.root.after(1000, lambda: self._check_time_loop(target_time))
311

    
312

    
313

    
314

    
315
if __name__ == "__main__":
316
    """
317
    @brief Main entry point for the application
318
    
319
    @details Creates Tkinter root window and starts the GUI application
320
    """
321
    root = tk.Tk()
322
    app = ImageDisplayApp(root)
323
    root.mainloop()
(12-12/17)