-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImage Enhancer.py
More file actions
748 lines (621 loc) · 30.1 KB
/
Copy pathImage Enhancer.py
File metadata and controls
748 lines (621 loc) · 30.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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
import json
from datetime import datetime
from pathlib import Path
from tkinter import StringVar, Tk, filedialog, messagebox, ttk
try:
from PIL import Image, ImageTk
except ModuleNotFoundError as error:
Image = None
ImageTk = None
PREVIEW_IMPORT_ERROR = error
else:
PREVIEW_IMPORT_ERROR = None
try:
import cv2
import numpy as np
except ModuleNotFoundError as error:
cv2 = None
np = None
ENHANCEMENT_IMPORT_ERROR = error
else:
ENHANCEMENT_IMPORT_ERROR = None
SUPPORTED_OUTPUT_TYPES = {
"png": ".png",
"jpg": ".jpg",
"jpeg": ".jpeg",
"bmp": ".bmp",
"webp": ".webp",
}
HISTORY_FILE = Path(__file__).with_name("enhancement_history.json")
INVALID_FILENAME_CHARACTERS = '<>:"/\\|?*'
COLORS = {
"background": "#09090b",
"panel": "#141417",
"panel_alt": "#18181b",
"field": "#202024",
"border": "#3f3f46",
"text": "#f4f4f5",
"muted": "#a1a1aa",
"primary": "#2563eb",
"primary_hover": "#1d4ed8",
"success": "#15803d",
"success_hover": "#166534",
"secondary": "#27272a",
"secondary_hover": "#3f3f46",
"warning": "#f59e0b",
}
def create_output_path(image_name, image_suffix, save_folder):
"""Create the final file path for the enhanced image."""
return save_folder / f"{image_name}{image_suffix}"
def check_enhancement_dependencies():
"""Stop enhancement with a clear message when required packages are missing."""
if ENHANCEMENT_IMPORT_ERROR is not None:
missing_package = ENHANCEMENT_IMPORT_ERROR.name
raise RuntimeError(
f"Missing required package: {missing_package}. "
"Install enhancement dependencies with: pip install opencv-python numpy"
)
def check_preview_dependencies():
"""Stop preview with a clear message when required packages are missing."""
if PREVIEW_IMPORT_ERROR is not None:
missing_package = PREVIEW_IMPORT_ERROR.name
raise RuntimeError(
f"Missing required package: {missing_package}. "
"Install preview dependencies with: pip install pillow"
)
def is_black_and_white(image):
"""Check whether the image has little to no color information."""
blue_channel, green_channel, red_channel = cv2.split(image)
blue_green_diff = cv2.absdiff(blue_channel, green_channel)
blue_red_diff = cv2.absdiff(blue_channel, red_channel)
green_red_diff = cv2.absdiff(green_channel, red_channel)
channel_diff = np.maximum.reduce([blue_green_diff, blue_red_diff, green_red_diff])
return np.mean(channel_diff) < 2 and np.percentile(channel_diff, 99) < 10
def estimate_blur(image):
"""Return a Laplacian variance score; lower values mean blurrier images."""
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
return cv2.Laplacian(gray_image, cv2.CV_64F).var()
def gray_world_white_balance(image):
"""Apply restrained white balance so color casts look more natural."""
image_float = image.astype(np.float32)
channel_means = image_float.reshape(-1, 3).mean(axis=0)
gray_mean = channel_means.mean()
scale = gray_mean / np.maximum(channel_means, 1)
balanced = image_float * scale
return np.clip(balanced, 0, 255).astype(np.uint8)
def enhance_luminance(image, clip_limit=1.8):
"""Improve local contrast without pushing the image into an artificial look."""
lab_image = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
l_channel, a_channel, b_channel = cv2.split(lab_image)
clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=(8, 8))
enhanced_l = clahe.apply(l_channel)
merged_lab = cv2.merge((enhanced_l, a_channel, b_channel))
return cv2.cvtColor(merged_lab, cv2.COLOR_LAB2BGR)
def realistic_sharpen(image, blur_score):
"""Sharpen gently, using more strength only when the source is visibly blurry."""
if blur_score < 60:
amount = 1.15
radius = (0, 0)
sigma = 1.35
elif blur_score < 140:
amount = 0.75
radius = (0, 0)
sigma = 1.05
else:
amount = 0.38
radius = (0, 0)
sigma = 0.85
blurred = cv2.GaussianBlur(image, radius, sigma)
sharpened = cv2.addWeighted(image, 1 + amount, blurred, -amount, 0)
return np.clip(sharpened, 0, 255).astype(np.uint8)
def restore_blurry_details(image, blur_score):
"""Make blurry photos clearer while avoiding harsh outlines."""
if blur_score >= 140:
return image
smooth = cv2.bilateralFilter(image, 7, 35, 35)
detail = cv2.subtract(image, smooth)
strength = 0.45 if blur_score < 60 else 0.28
restored = cv2.addWeighted(image, 1.0, detail, strength, 0)
return np.clip(restored, 0, 255).astype(np.uint8)
def enhance_color_image(image):
"""Enhance a color image with realistic contrast, color, and detail."""
blur_score = estimate_blur(image)
denoise_strength = 5 if blur_score < 140 else 3
denoised = cv2.fastNlMeansDenoisingColored(image, None, denoise_strength, denoise_strength, 7, 21)
balanced = gray_world_white_balance(denoised)
contrasted = enhance_luminance(balanced, clip_limit=1.7)
restored = restore_blurry_details(contrasted, blur_score)
sharpened = realistic_sharpen(restored, blur_score)
hsv_image = cv2.cvtColor(sharpened, cv2.COLOR_BGR2HSV)
hue_channel, saturation_channel, value_channel = cv2.split(hsv_image)
saturation_channel = np.clip(saturation_channel.astype(np.float32) * 1.04, 0, 245).astype(np.uint8)
natural_color = cv2.merge((hue_channel, saturation_channel, value_channel))
return cv2.cvtColor(natural_color, cv2.COLOR_HSV2BGR), blur_score
def enhance_black_and_white_image(image):
"""Enhance a black-and-white image with a restrained warm tone."""
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur_score = estimate_blur(image)
denoised = cv2.fastNlMeansDenoising(gray_image, None, 8, 7, 21)
clahe = cv2.createCLAHE(clipLimit=1.8, tileGridSize=(8, 8))
enhanced_gray = clahe.apply(denoised)
warm_tone = cv2.merge(
(
np.clip(enhanced_gray.astype(np.float32) * 0.92, 0, 255).astype(np.uint8),
np.clip(enhanced_gray.astype(np.float32) * 0.98, 0, 255).astype(np.uint8),
np.clip(enhanced_gray.astype(np.float32) * 1.06, 0, 255).astype(np.uint8),
)
)
sharpened = realistic_sharpen(warm_tone, blur_score)
return sharpened, blur_score
def preview_enhancement(input_path, progress_callback=None):
"""Enhance an image and return the enhanced pixels for preview before saving."""
check_enhancement_dependencies()
if progress_callback:
progress_callback("Loading...", 10)
image = cv2.imread(str(input_path))
if image is None:
raise ValueError(f"Could not read image: {input_path}")
if progress_callback:
progress_callback("Checking...", 25)
if is_black_and_white(image):
if progress_callback:
progress_callback("Enhancing...", 45)
enhanced_image, blur_score = enhance_black_and_white_image(image)
image_mode = "Black-and-white image detected. Enhanced with a natural warm tone."
else:
if progress_callback:
progress_callback("Enhancing...", 45)
enhanced_image, blur_score = enhance_color_image(image)
image_mode = "Color image detected. Enhanced with realistic correction."
if progress_callback:
progress_callback("Finishing...", 80)
if blur_score < 60:
blur_message = "Very blurry source; detail restoration was applied."
elif blur_score < 140:
blur_message = "Mild blur detected; gentle sharpening was applied."
else:
blur_message = "Source sharpness looks acceptable."
return enhanced_image, f"{image_mode} {blur_message}"
def save_enhanced_image(enhanced_image, output_path):
"""Save the already-previewed enhanced image."""
check_enhancement_dependencies()
if not cv2.imwrite(str(output_path), enhanced_image):
raise ValueError(f"Could not save enhanced image to: {output_path}")
class ImageEnhancerApp:
"""Tkinter UI for previewing, saving, and tracking enhanced images."""
def __init__(self, root):
self.root = root
self.root.title("Image Enhancer")
self.root.geometry("1120x760")
self.root.minsize(980, 680)
self.root.configure(bg=COLORS["background"])
self.input_path = StringVar()
self.output_name = StringVar()
self.output_type = StringVar(value="png")
self.save_folder = StringVar()
self.status_text = StringVar(value="NULL")
self.progress_text = StringVar(value="0%")
self.original_preview_image = None
self.enhanced_preview_image = None
self.enhanced_image = None
self.preview_source_path = None
self.enhancement_message = ""
self.history = self.load_history()
self.configure_styles()
self.build_ui()
self.refresh_history()
def configure_styles(self):
style = ttk.Style()
style.theme_use("clam")
self.root.option_add("*TCombobox*Listbox.background", COLORS["field"])
self.root.option_add("*TCombobox*Listbox.foreground", COLORS["text"])
self.root.option_add("*TCombobox*Listbox.selectBackground", COLORS["primary"])
self.root.option_add("*TCombobox*Listbox.selectForeground", "#ffffff")
style.configure(".", background=COLORS["background"], foreground=COLORS["text"], font=("Segoe UI", 10))
style.configure("TFrame", background=COLORS["background"])
style.configure("Header.TFrame", background=COLORS["background"])
style.configure(
"Panel.TLabelframe",
background=COLORS["panel"],
foreground=COLORS["text"],
bordercolor=COLORS["border"],
relief="solid",
)
style.configure("Panel.TLabelframe.Label", background=COLORS["background"], foreground=COLORS["text"])
style.configure("TLabel", background=COLORS["background"], foreground=COLORS["text"])
style.configure("Title.TLabel", background=COLORS["background"], foreground=COLORS["text"], font=("Segoe UI", 30, "bold"))
style.configure("Subtitle.TLabel", background=COLORS["background"], foreground=COLORS["muted"], font=("Segoe UI", 10))
style.configure("Process.TFrame", background=COLORS["panel_alt"], bordercolor=COLORS["border"], relief="solid")
style.configure("ProcessTitle.TLabel", background=COLORS["panel_alt"], foreground=COLORS["muted"], font=("Segoe UI", 8, "bold"))
style.configure("ProcessText.TLabel", background=COLORS["panel_alt"], foreground=COLORS["text"], font=("Segoe UI", 9, "bold"))
style.configure("ProcessPercent.TLabel", background=COLORS["panel_alt"], foreground=COLORS["muted"], font=("Segoe UI", 8, "bold"))
style.configure("Field.TLabel", background=COLORS["panel"], foreground=COLORS["muted"], font=("Segoe UI", 9, "bold"))
style.configure("PreviewTitle.TLabel", background=COLORS["panel"], foreground=COLORS["muted"], font=("Segoe UI", 9, "bold"))
style.configure("HistoryHeader.TFrame", background=COLORS["secondary"])
style.configure("HistoryHeader.TLabel", background=COLORS["secondary"], foreground=COLORS["text"], font=("Segoe UI", 9, "bold"), padding=(10, 8))
style.configure(
"Preview.TLabel",
background=COLORS["field"],
foreground=COLORS["muted"],
bordercolor=COLORS["border"],
relief="solid",
padding=18,
)
style.configure(
"Status.TLabel",
background=COLORS["panel_alt"],
foreground=COLORS["muted"],
bordercolor=COLORS["border"],
relief="solid",
padding=(10, 6),
)
style.configure(
"Process.Horizontal.TProgressbar",
background=COLORS["primary"],
troughcolor=COLORS["field"],
bordercolor=COLORS["border"],
lightcolor=COLORS["primary"],
darkcolor=COLORS["primary"],
)
style.configure(
"TEntry",
fieldbackground=COLORS["field"],
foreground=COLORS["text"],
insertcolor=COLORS["text"],
bordercolor=COLORS["border"],
lightcolor=COLORS["border"],
darkcolor=COLORS["border"],
padding=7,
)
style.configure(
"TCombobox",
fieldbackground=COLORS["field"],
background=COLORS["field"],
foreground=COLORS["text"],
arrowcolor=COLORS["text"],
bordercolor=COLORS["border"],
padding=7,
)
style.configure(
"TButton",
background=COLORS["secondary"],
foreground=COLORS["text"],
bordercolor=COLORS["border"],
focusthickness=1,
padding=(12, 9),
)
style.configure("Primary.TButton", background=COLORS["primary"], foreground="#ffffff", bordercolor=COLORS["primary"])
style.configure("Success.TButton", background=COLORS["success"], foreground="#ffffff", bordercolor=COLORS["success"])
style.configure("Secondary.TButton", background=COLORS["secondary"], foreground=COLORS["text"], bordercolor=COLORS["border"])
style.map("TButton", background=[("active", COLORS["secondary_hover"]), ("disabled", COLORS["panel_alt"])])
style.map("Primary.TButton", background=[("active", COLORS["primary_hover"]), ("disabled", COLORS["panel_alt"])])
style.map("Success.TButton", background=[("active", COLORS["success_hover"]), ("disabled", COLORS["panel_alt"])])
style.map("TButton", foreground=[("disabled", "#71717a")])
style.configure(
"Treeview",
background=COLORS["panel_alt"],
fieldbackground=COLORS["panel_alt"],
foreground=COLORS["text"],
bordercolor=COLORS["border"],
rowheight=30,
font=("Segoe UI", 9),
)
style.configure("Treeview.Heading", background=COLORS["secondary"], foreground=COLORS["text"], font=("Segoe UI", 9, "bold"))
style.map("Treeview", background=[("selected", "#334155")], foreground=[("selected", "#ffffff")])
def build_ui(self):
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
main_frame = ttk.Frame(self.root, padding=24)
main_frame.grid(row=0, column=0, sticky="nsew")
main_frame.columnconfigure(0, weight=2)
main_frame.columnconfigure(1, weight=3)
main_frame.rowconfigure(1, weight=5)
main_frame.rowconfigure(2, weight=1)
header_frame = ttk.Frame(main_frame, style="Header.TFrame")
header_frame.grid(row=0, column=0, columnspan=2, sticky="ew", pady=(0, 18))
header_frame.columnconfigure(0, weight=1)
header_frame.columnconfigure(1, weight=3)
header_frame.columnconfigure(2, weight=1)
title_frame = ttk.Frame(header_frame, style="Header.TFrame")
title_frame.grid(row=0, column=1, sticky="ew")
title_frame.columnconfigure(0, weight=1)
title = ttk.Label(title_frame, text="Image Enhancer", style="Title.TLabel", anchor="center")
title.grid(row=0, column=0, sticky="ew")
subtitle = ttk.Label(
title_frame,
text="Realistic blur correction, before-and-after preview, and saved enhancement history.",
style="Subtitle.TLabel",
anchor="center",
)
subtitle.grid(row=1, column=0, sticky="ew", pady=(3, 0))
process_frame = ttk.Frame(header_frame, padding=(12, 9), style="Process.TFrame")
process_frame.grid(row=0, column=2, sticky="ne", padx=(16, 0))
process_frame.columnconfigure(0, weight=1)
process_frame.columnconfigure(1, weight=0)
ttk.Label(process_frame, text="PROCESS", style="ProcessTitle.TLabel", anchor="center").grid(row=0, column=0, columnspan=2, sticky="ew")
ttk.Label(process_frame, textvariable=self.status_text, style="ProcessText.TLabel", anchor="center").grid(
row=1,
column=0,
columnspan=2,
sticky="ew",
pady=(2, 6),
)
self.process_bar = ttk.Progressbar(
process_frame,
mode="determinate",
length=118,
maximum=100,
style="Process.Horizontal.TProgressbar",
)
self.process_bar.grid(row=2, column=0, sticky="ew")
ttk.Label(process_frame, textvariable=self.progress_text, style="ProcessPercent.TLabel", anchor="e").grid(
row=2,
column=1,
sticky="e",
padx=(8, 0),
)
form_frame = ttk.LabelFrame(main_frame, text="Image Details", padding=18, style="Panel.TLabelframe")
form_frame.grid(row=1, column=0, sticky="nsew", padx=(0, 10))
form_frame.columnconfigure(1, weight=1)
preview_frame = ttk.LabelFrame(main_frame, text="Before And After Preview", padding=18, style="Panel.TLabelframe")
preview_frame.grid(row=1, column=1, sticky="nsew", padx=(10, 0))
preview_frame.columnconfigure(0, weight=1)
preview_frame.rowconfigure(0, weight=1)
history_frame = ttk.LabelFrame(main_frame, text="Recent History", padding=12, style="Panel.TLabelframe")
history_frame.grid(row=2, column=0, columnspan=2, sticky="nsew", pady=(14, 0))
history_frame.columnconfigure(0, weight=1)
history_frame.rowconfigure(0, weight=1)
self.create_form(form_frame)
self.create_preview(preview_frame)
self.create_history(history_frame)
def create_form(self, parent):
ttk.Label(parent, text="SOURCE IMAGE", style="Field.TLabel").grid(row=0, column=0, sticky="w", pady=(0, 8))
ttk.Entry(parent, textvariable=self.input_path).grid(row=0, column=1, sticky="ew", padx=(12, 8), pady=(0, 8), ipady=2)
ttk.Button(parent, text="Browse", command=self.select_image, style="Secondary.TButton").grid(
row=0,
column=2,
sticky="ew",
pady=(0, 8),
)
ttk.Label(parent, text="ENHANCED IMAGE NAME", style="Field.TLabel").grid(row=1, column=0, sticky="w", pady=8)
ttk.Entry(parent, textvariable=self.output_name).grid(row=1, column=1, columnspan=2, sticky="ew", padx=(12, 0), pady=8, ipady=2)
ttk.Label(parent, text="IMAGE TYPE", style="Field.TLabel").grid(row=2, column=0, sticky="w", pady=8)
type_box = ttk.Combobox(
parent,
textvariable=self.output_type,
values=list(SUPPORTED_OUTPUT_TYPES.keys()),
state="readonly",
)
type_box.grid(row=2, column=1, columnspan=2, sticky="ew", padx=(12, 0), pady=8, ipady=2)
ttk.Label(parent, text="SAVE FOLDER", style="Field.TLabel").grid(row=3, column=0, sticky="w", pady=8)
ttk.Entry(parent, textvariable=self.save_folder).grid(row=3, column=1, sticky="ew", padx=(12, 8), pady=8, ipady=2)
ttk.Button(parent, text="Browse", command=self.select_save_folder, style="Secondary.TButton").grid(
row=3,
column=2,
sticky="ew",
pady=8,
)
ttk.Button(parent, text="Preview Enhancement", command=self.preview_selected_image, style="Primary.TButton").grid(
row=4,
column=0,
columnspan=3,
sticky="ew",
pady=(18, 8),
)
self.save_button = ttk.Button(
parent,
text="Save Enhanced Image",
command=self.save_previewed_image,
state="disabled",
style="Success.TButton",
)
self.save_button.grid(row=5, column=0, columnspan=3, sticky="ew")
ttk.Button(parent, text="New Enhancement", command=self.start_new_enhancement, style="Secondary.TButton").grid(
row=6,
column=0,
columnspan=3,
sticky="ew",
pady=(8, 0),
)
def create_preview(self, parent):
parent.columnconfigure(0, weight=1)
parent.columnconfigure(1, weight=1)
parent.rowconfigure(1, weight=1)
ttk.Label(parent, text="BEFORE", anchor="center", style="PreviewTitle.TLabel").grid(row=0, column=0, sticky="ew", padx=(0, 8))
ttk.Label(parent, text="AFTER", anchor="center", style="PreviewTitle.TLabel").grid(row=0, column=1, sticky="ew", padx=(8, 0))
self.before_preview_label = ttk.Label(parent, text="No source preview", anchor="center", style="Preview.TLabel")
self.before_preview_label.grid(row=1, column=0, sticky="nsew", padx=(0, 8), pady=(10, 0))
self.after_preview_label = ttk.Label(parent, text="No enhanced preview", anchor="center", style="Preview.TLabel")
self.after_preview_label.grid(row=1, column=1, sticky="nsew", padx=(8, 0), pady=(10, 0))
def create_history(self, parent):
parent.rowconfigure(1, weight=1)
header_frame = ttk.Frame(parent, style="HistoryHeader.TFrame")
header_frame.grid(row=0, column=0, sticky="ew")
header_frame.columnconfigure(0, weight=0, minsize=140)
header_frame.columnconfigure(1, weight=1, minsize=180)
header_frame.columnconfigure(2, weight=0, minsize=170)
header_frame.columnconfigure(3, weight=3, minsize=460)
ttk.Label(header_frame, text="Date", style="HistoryHeader.TLabel", anchor="w").grid(row=0, column=0, sticky="ew")
ttk.Label(header_frame, text="Image Enhanced", style="HistoryHeader.TLabel", anchor="w").grid(row=0, column=1, sticky="ew")
ttk.Label(header_frame, text="Enhanced Image Type", style="HistoryHeader.TLabel", anchor="w").grid(row=0, column=2, sticky="ew")
ttk.Label(header_frame, text="Enhanced Image Address", style="HistoryHeader.TLabel", anchor="w").grid(row=0, column=3, sticky="ew")
columns = ("date", "image_enhanced", "enhanced_image_type", "enhanced_image_address")
self.history_table = ttk.Treeview(parent, columns=columns, show="", height=4)
self.history_table.column("date", width=140, stretch=False)
self.history_table.column("image_enhanced", width=180)
self.history_table.column("enhanced_image_type", width=170, stretch=False)
self.history_table.column("enhanced_image_address", width=460)
self.history_table.grid(row=1, column=0, sticky="nsew")
self.history_table.tag_configure("odd", background=COLORS["panel_alt"])
self.history_table.tag_configure("even", background=COLORS["field"])
scrollbar = ttk.Scrollbar(parent, orient="vertical", command=self.history_table.yview)
scrollbar.grid(row=1, column=1, sticky="ns")
self.history_table.configure(yscrollcommand=scrollbar.set)
def select_image(self):
selected_file = filedialog.askopenfilename(
title="Select an image to enhance",
filetypes=[
("Image files", "*.png;*.jpg;*.jpeg;*.bmp;*.gif;*.webp"),
("All files", "*.*"),
],
)
if not selected_file:
return
input_path = Path(selected_file)
self.input_path.set(str(input_path))
if not self.output_name.get().strip():
self.output_name.set(f"{input_path.stem}_enhanced")
if not self.save_folder.get().strip():
self.save_folder.set(str(input_path.parent))
self.clear_preview()
def select_save_folder(self):
selected_folder = filedialog.askdirectory(title="Select where to save the enhanced image")
if selected_folder:
self.save_folder.set(selected_folder)
def validate_source_image(self):
input_path = Path(self.input_path.get().strip())
if not input_path.is_file():
raise ValueError("Please select a valid source image.")
return input_path
def validate_save_details(self):
image_name = self.output_name.get().strip()
image_type = self.output_type.get().strip().lower()
save_folder = Path(self.save_folder.get().strip())
if not image_name:
raise ValueError("Please enter the enhanced image name.")
if any(character in image_name for character in INVALID_FILENAME_CHARACTERS):
raise ValueError(f"Image name cannot contain these characters: {INVALID_FILENAME_CHARACTERS}")
if image_type not in SUPPORTED_OUTPUT_TYPES:
raise ValueError("Please select a valid image type.")
if not save_folder.is_dir():
raise ValueError("Please select a valid save folder.")
return image_name, image_type, save_folder
def preview_selected_image(self):
try:
input_path = self.validate_source_image()
self.set_process("Starting...", 5)
self.root.update_idletasks()
self.enhanced_image, self.enhancement_message = preview_enhancement(input_path, self.update_preview_progress)
self.set_process("Rendering...", 90)
self.root.update_idletasks()
self.preview_source_path = input_path
self.show_before_after_preview(input_path, self.enhanced_image)
self.save_button.configure(state="normal")
self.set_process("Ready", 100)
except Exception as error:
self.clear_preview("Error", 0)
messagebox.showerror("Error", str(error))
def save_previewed_image(self):
try:
if self.enhanced_image is None:
raise ValueError("Generate a preview before saving.")
input_path = self.validate_source_image()
if self.preview_source_path != input_path:
raise ValueError("The source image changed. Generate a new preview before saving.")
image_name, image_type, save_folder = self.validate_save_details()
output_path = create_output_path(image_name, SUPPORTED_OUTPUT_TYPES[image_type], save_folder)
if output_path.exists():
should_overwrite = messagebox.askyesno(
"File already exists",
f"{output_path.name} already exists. Do you want to replace it?",
)
if not should_overwrite:
return
save_enhanced_image(self.enhanced_image, output_path)
self.add_history_entry(input_path, output_path, image_type)
messagebox.showinfo("Done", f"Enhanced image saved to:\n{output_path}")
except Exception as error:
messagebox.showerror("Error", str(error))
def show_before_after_preview(self, input_path, enhanced_image):
check_preview_dependencies()
original_image = cv2.imread(str(input_path))
if original_image is None:
raise ValueError(f"Could not read image: {input_path}")
original_preview = self.create_tk_preview(original_image)
enhanced_preview = self.create_tk_preview(enhanced_image)
self.original_preview_image = original_preview
self.enhanced_preview_image = enhanced_preview
self.before_preview_label.configure(image=self.original_preview_image, text="")
self.after_preview_label.configure(image=self.enhanced_preview_image, text="")
def create_tk_preview(self, image_array):
preview = cv2.cvtColor(image_array, cv2.COLOR_BGR2RGB)
image = Image.fromarray(preview)
image.thumbnail((300, 360))
return ImageTk.PhotoImage(image)
def clear_preview(self, status="NULL", progress=0):
self.enhanced_image = None
self.preview_source_path = None
self.enhancement_message = ""
self.original_preview_image = None
self.enhanced_preview_image = None
self.before_preview_label.configure(image="", text="No source preview")
self.after_preview_label.configure(image="", text="No enhanced preview")
self.save_button.configure(state="disabled")
self.set_process(status, progress)
def update_preview_progress(self, status, progress):
self.set_process(status, progress)
self.root.update_idletasks()
def set_process(self, status=None, progress=None):
if status is None or not str(status).strip():
status = "NULL"
if progress is None:
progress = 0
progress = max(0, min(100, int(progress)))
self.status_text.set(status)
self.progress_text.set(f"{progress}%")
if not hasattr(self, "process_bar"):
return
self.process_bar.stop()
self.process_bar["value"] = progress
def start_new_enhancement(self):
self.input_path.set("")
self.output_name.set("")
self.output_type.set("png")
self.save_folder.set("")
self.clear_preview("NULL", 0)
def load_history(self):
if not HISTORY_FILE.exists():
return []
try:
with HISTORY_FILE.open("r", encoding="utf-8") as file:
history = json.load(file)
except (OSError, json.JSONDecodeError):
return []
if not isinstance(history, list):
return []
return history
def save_history(self):
with HISTORY_FILE.open("w", encoding="utf-8") as file:
json.dump(self.history[-100:], file, indent=2)
def add_history_entry(self, input_path, output_path, image_type):
entry = {
"date": datetime.now().strftime("%Y-%m-%d %H:%M"),
"source": str(input_path),
"image_enhanced": output_path.stem,
"enhanced_image_type": image_type,
"enhanced_image_address": str(output_path),
}
self.history.append(entry)
self.save_history()
self.refresh_history()
def refresh_history(self):
for item_id in self.history_table.get_children():
self.history_table.delete(item_id)
for index, entry in enumerate(reversed(self.history[-50:])):
self.history_table.insert(
"",
"end",
values=(
entry.get("date", ""),
entry.get("image_enhanced") or Path(entry.get("output", "")).stem,
entry.get("enhanced_image_type") or Path(entry.get("output", "")).suffix.lstrip("."),
entry.get("enhanced_image_address") or entry.get("output", ""),
),
tags=("even" if index % 2 == 0 else "odd",),
)
def main():
root = Tk()
ImageEnhancerApp(root)
root.mainloop()
if __name__ == "__main__":
main()