-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1673 lines (1421 loc) · 66.1 KB
/
main.py
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from tkinter import *
from tkinter import ttk, filedialog, messagebox, colorchooser
from idlelib.tooltip import Hovertip
from PIL import Image, ImageOps, ImageEnhance, ImageFilter, ImageStat
import threading
import os
import re
VERSION = "1.1"
DATE = "31.03.2024"
CWD = os.path.abspath(os.getcwd()).replace(os.sep, '/')
INPUT_PATH = os.path.join(CWD, 'input').replace(os.sep, '/')
OUTPUT_PATH = os.path.join(CWD, 'output').replace(os.sep, '/')
FILL_COLOR = "#000000"
RESIZE_REGEX = re.compile("^(?:\d+%?x\d+%?|\d+%|\d+x\d+)$")
CROP_REGEX = re.compile("^(?:\d+%?)(?:,\s*\d+%?){3}$")
ACTIVE_THREADS = []
THREAD_COUNT = 0
IMG_COUNT = 0
ERR_COUNT = 0
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
SAVE_FORMATS = [
"BLP", # blp_version (str): "BLP1" or "BLP2" (default)
"BMP",
"DDS",
"DIB",
"EPS",
"GIF", # save_all (bool), interlace (bool)
"ICNS",
"ICO",
"IM",
"JPEG", # quality (0-95 or "keep"), optimize (bool), progressive (bool)
"JFIF", # same as above
"JP2",
"MSP",
"PCX",
"PDF", # save_all (bool)
"PNG", # optimize (bool)
"PBM",
"PGM",
"PPM",
"PNM",
"SGI",
"SPI", # format='SPIDER' has to be provided, extension can be any 3 alphanumeric characters
"TGA",
"TIFF", # save_all (bool)
"WebP", # lossless (bool), quality (0-100, def. 80)
"XBM"
]
MODES = [
"1", # values can be directly used
"L",
"P",
"RGB",
"RGBA",
"CMYK",
"YCbCr",
"LAB",
"HSV",
"I",
"F"
]
RESAMPLING = [
"NEAREST", # indices correspond to value
"LANCZOS",
"BILINEAR",
"BICUBIC",
"BOX",
"HAMMING",
]
TRANSPOSE = [
"FLIP_LEFT_RIGHT", # indices correspond to value
"FLIP_TOP_BOTTOM",
"ROTATE_90",
"ROTATE_180",
"ROTATE_270"
]
RESIZING = [
"Contain",
"Cover",
"Fit",
"Pad"
]
def how_to():
"""
Opens up a new window explaining how the program works.
"""
help_window = Toplevel()
help_window.resizable(False, False)
help_window.title("BatchIMG: Help")
help_text = """
To use BatchIMG, you must first select a valid input (source) and
a valid output (destination) directory. Your source directory will
contain the images to operate on.
You may select multiple effects and transformation options, if
they are compatible with one another, as represented by a possible
error message.
To learn the syntax / meaning of each option, hover your mouse over
the corresponding label.
Descriptions taken from the Pillow 10.2.0 documentation:
https://pillow.readthedocs.io/
IMPORTANT:
Effects are applied top to bottom, left to right, sequentially.
For example, if you have selected "Resize", "Blur", "Smooth", the
image will first be resized, then blurred, then finally smoothed.
This may lead to some unwanted side effects, such as selecting a
border fill color, then grayscaling the image, which will lead to
the fill color also becoming grayscaled.
To avoid this, you will need to run the batch processing multiple
times (e.g. first grayscaling the images, then expanding them).
This also applies to tabs: the operations in the "Transform" tab
are applied before the operations in the "Advanced" tab.
Some effects are also incompatible with some modes. As a workaround,
first convert the images to the fitting modes, then try applying the
effects again.
"""
ttk.Label(help_window, text=re.sub(' +', ' ', help_text.strip())).pack(
padx=5, pady=5, anchor=W)
ttk.Button(help_window, text="Close",
command=help_window.destroy).pack(padx=5, pady=5)
def about():
"""
Opens up a new About messagebox.
"""
messagebox.showinfo(
"About BatchIMG", "BatchIMG: A GUI for image batch processing.\n" +
"Developed by FlamingLeo, 2024.\n\n" +
f"Version {VERSION}, finished {DATE}.\nMade using Python, Pillow and tkinter.\n\n" +
"PyPI (Pillow): \nhttps://pypi.org/project/pillow/")
def check_on_close():
"""
Checks for active threads on close.
If there are still active threads, warn the user about closing the program.
"""
running_threads = False
for thread in ACTIVE_THREADS:
if thread.is_alive():
running_threads = True
break
if running_threads:
if messagebox.askokcancel("Ongoing Operations", "There are still ongoing operations.\nAre you sure you want to quit?"):
root.destroy()
else:
root.destroy()
def save_logs():
"""
Saves the logs to an external text file in the same directory as the program.
"""
try:
if log_listbox.size():
with open("logs.txt", "w") as file:
for listbox_entry in enumerate(log_listbox.get(0, END)):
file.write(listbox_entry[1] + "\n")
except:
pass
def set_input_path():
"""
Set input (source) directory and replace input entry box.
"""
global INPUT_PATH
INPUT_PATH = filedialog.askdirectory()
if INPUT_PATH:
general_input_entry.delete(0, END)
general_input_entry.insert(0, INPUT_PATH)
def set_output_path():
"""
Set output (destination) directory and replace output entry box.
"""
global OUTPUT_PATH
OUTPUT_PATH = filedialog.askdirectory()
if OUTPUT_PATH:
general_output_entry.delete(0, END)
general_output_entry.insert(0, OUTPUT_PATH)
def set_fill_color():
"""
Set fill color for expanding.
"""
global FILL_COLOR
color = colorchooser.askcolor()[1]
FILL_COLOR = color if color is not None else FILL_COLOR
def replace_input_path():
"""
Pastes and replaces input path if the clipboard is not empty.
"""
if root.clipboard_get():
general_input_entry.delete(0, END)
general_input_entry.insert(0, root.clipboard_get())
def replace_output_path():
"""
Pastes and replaces output path if the clipboard is not empty.
"""
if root.clipboard_get():
general_output_entry.delete(0, END)
general_output_entry.insert(0, root.clipboard_get())
"""
------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------UI functions start here.---------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------
"""
def ui_toggle_resize():
"""
Enables / disables UI elements if resizing is chosen or not.
"""
STATE = "readonly" if transform_resize.get() else "disabled"
transform_resize_entry.config(
state="normal" if transform_resize.get() else "disabled")
transform_resize_combobox.config(state=STATE)
transform_contain_radio.config(state=STATE)
transform_cover_radio.config(state=STATE)
transform_fit_radio.config(state=STATE)
transform_pad_radio.config(state=STATE)
def ui_toggle_transpose():
"""
Enables / disables UI elements if transposing is chosen or not.
"""
transform_transpose_combobox.config(
state="readonly" if transform_transpose.get() else "disabled")
def ui_toggle_crop():
"""
Enables / disables UI elements if cropping is chosen or not.
"""
transform_crop_entry.config(
state="normal" if transform_crop.get() else "disabled")
def ui_toggle_scale():
"""
Enables / disables UI elements if scaling is chosen or not.
"""
transform_scale_entry.config(
state="normal" if transform_scale.get() else "disabled")
transform_scale_combobox.config(
state="readonly" if transform_scale.get() else "disabled")
def ui_toggle_expand():
"""
Enables / disables UI elements if expanding is chosen or not.
"""
transform_expand_entry.config(
state="normal" if transform_expand.get() else "disabled")
transform_expand_button.config(
state="normal" if transform_expand.get() else "disabled")
def ui_toggle_posterize():
"""
Enables / disables UI elements if posterize is chosen or not.
"""
transform_posterize_entry.config(
state="normal" if transform_posterize.get() else "disabled")
def ui_toggle_solarize():
"""
Enables / disables UI elements if solarize is chosen or not.
"""
transform_solarize_entry.config(
state="normal" if transform_solarize.get() else "disabled")
def ui_toggle_color():
"""
Enables / disables UI elements if color is chosen or not.
"""
transform_color_entry.config(
state="normal" if transform_color.get() else "disabled")
def ui_toggle_contrast():
"""
Enables / disables UI elements if contrast is chosen or not.
"""
transform_contrast_entry.config(
state="normal" if transform_contrast.get() else "disabled")
def ui_toggle_brightness():
"""
Enables / disables UI elements if brightness is chosen or not.
"""
transform_brightness_entry.config(
state="normal" if transform_brightness.get() else "disabled")
def ui_toggle_sharpness():
"""
Enables / disables UI elements if sharpness is chosen or not.
"""
transform_sharpness_entry.config(
state="normal" if transform_sharpness.get() else "disabled")
def ui_toggle_filetype():
"""
Enables / disables UI elements if filetype conversion is chosen or not.
"""
advanced_convert_filetype_combobox.config(
state="readonly" if advanced_convert_filetype.get() else "disabled")
def ui_toggle_mode():
"""
Enables / disables UI elements if mode conversion is chosen or not.
"""
advanced_convert_modes_combobox.config(
state="readonly" if advanced_convert_modes.get() else "disabled")
def ui_toggle_stats():
"""
Enables / disables UI elements if statistics showcase is chosen or not.
"""
STATE = "normal" if advanced_stats.get() else "disabled"
advanced_extrema_checkbutton.config(state=STATE)
advanced_count_checkbutton.config(state=STATE)
advanced_sum_checkbutton.config(state=STATE)
advanced_sum2_checkbutton.config(state=STATE)
advanced_mean_checkbutton.config(state=STATE)
advanced_median_checkbutton.config(state=STATE)
advanced_rms_checkbutton.config(state=STATE)
advanced_var_checkbutton.config(state=STATE)
advanced_stddev_checkbutton.config(state=STATE)
"""
------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------Helper functions start here.-------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------
"""
def insert_log(msg):
"""
Helper method to insert string into listbox and move view to end of listbox.
"""
log_listbox.insert(END, msg)
log_listbox.yview(END)
def format_size_1d(dim, size):
"""
Helper method to format the size of an image in one dimension.
If the input contains a percentage, the corresponding dimension in pixels is calculated.
Otherwise, return the dimension as is.
"""
return int(float(dim.split("%")[0]) / 100.0 * size) if '%' in dim else int(dim)
def is_float(string):
"""
Helper method to determine if string is float.
Returns corresponding boolean.
"""
try:
float(string)
return True
except ValueError:
return False
def check(val, func, img):
"""
Helper method. Performs a function only if the checkbutton is checked.
Yes, this is just a fancy wrapper for if-statements and try-catch-expressions.
"""
global ERR_COUNT
if val.get():
try:
img = func(img)
except Exception as e:
insert_log(f"[ERROR] {str(e)}")
ERR_COUNT += 1
return img
def check2(val, func, arg1, arg2):
"""
Helper method for functions with 2 arguments.
"""
global ERR_COUNT
if val.get():
try:
arg2 = func(arg1, arg2)
except Exception as e:
insert_log(f"[ERROR] {str(e)}")
ERR_COUNT += 1
return arg2
"""
------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------Image modification functions start here.-------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------
"""
def func_transform_resize(img):
"""
Resizes image based on input and resampling selection.
Returns resized image if entry has valid pattern, otherwise returns unmodified image.
"""
input = transform_resize_entry.get()
greater_than = input.split(">")
less_than = input.split("<")
new_size = greater_than[0] if len(greater_than) == 2 else less_than[0]
# check if resizing regex matches input, otherwise don't resize
if RESIZE_REGEX.match(new_size):
# check if input is either single percentage (n%) or contains 2 sizes (n x n) to determine new size
size_input = new_size.split("x")
if len(size_input) == 2:
new_size = (format_size_1d(size_input[0], img.width), format_size_1d(
size_input[1], img.height))
else:
new_size = (format_size_1d(size_input[0], img.width), format_size_1d(
size_input[0], img.height))
# if one of the dimensions is 0, return default image to prevent division by zero
if new_size[0] == 0 or new_size[1] == 0:
insert_log(
"[WARN] Invalid resize parameter(s). No resizing performed.")
return img
# resize based on radio button value (0: contain, 1: cover, 2: fit, 3: pad)
# also check if greater than / less than dimensions have been specified and fit
if len(greater_than) == 2:
if RESIZE_REGEX.match(greater_than[1]):
resize_input = greater_than[1].split("x")
if len(resize_input) != 2:
insert_log(
"[WARN] Invalid resize parameter(s). No resizing performed.")
return img
if resize_input[0].isnumeric() and resize_input[1].isnumeric():
new_width = int(resize_input[0])
new_height = int(resize_input[1])
else:
insert_log(
"[WARN] Invalid resize parameter(s). No resizing performed.")
return img
if img.width < new_width or img.height < new_height:
insert_log(
f"[INFO] Image dimension(s) less than {new_width}x{new_height}. Skipping.")
return img
else:
insert_log(
"[WARN] Invalid resize parameter(s). No resizing performed.")
return img
elif len(less_than) == 2:
if RESIZE_REGEX.match(less_than[1]):
resize_input = less_than[1].split("x")
if len(resize_input) != 2:
insert_log(
"[WARN] Invalid resize parameter(s). No resizing performed.")
return img
if resize_input[0].isnumeric() and resize_input[1].isnumeric():
new_width = int(resize_input[0])
new_height = int(resize_input[1])
else:
insert_log(
"[WARN] Invalid resize parameter(s). No resizing performed.")
return img
if img.width > new_width or img.height > new_height:
insert_log(
f"[INFO] Image dimension(s) greater than {new_width}x{new_height}. Skipping.")
return img
else:
insert_log(
"[WARN] Invalid resize parameter(s). No resizing performed.")
return img
resize_method = RESAMPLING.index(transform_resize_resample.get())
match transform_resize_type.get():
case 0:
img = ImageOps.contain(img, new_size, method=resize_method)
case 1:
img = ImageOps.cover(img, new_size, method=resize_method)
case 2:
img = ImageOps.fit(img, new_size, method=resize_method)
case 3:
img = ImageOps.pad(img, new_size, method=resize_method)
insert_log(
f"[TRANSFORM] Resized image using {transform_resize_resample.get()} ({RESIZING[transform_resize_type.get()]}, {img.width}x{img.height}).")
else:
insert_log(
"[WARN] Incorrect resize syntax. No resizing performed.")
return img
def func_transform_transpose(img):
"""
Transposes image based on selection.
Returns the transposed image.
"""
img = img.transpose(TRANSPOSE.index(transform_transpose_mode.get()))
insert_log(
f"[TRANSFORM] Transposed image using {transform_transpose_mode.get()}.")
return img
def func_transform_crop(img):
"""
Crops an image based on input.
Returns the cropped image if entry has valid pattern and valid coordinates, otherwise returns unmodified image.
"""
coordinates = transform_crop_entry.get()
# check if entry matches regex, otherwise don't crop
if CROP_REGEX.match(coordinates):
left, upper, right, lower = list(
map(str.strip, coordinates.split(",")))
left = (format_size_1d(left, img.width)) if '%' in left else int(left)
upper = (format_size_1d(upper, img.height)
) if '%' in upper else int(upper)
right = (img.width - format_size_1d(right, img.width)
) if '%' in right else int(right)
lower = (img.height - format_size_1d(lower, img.height)
) if '%' in lower else int(lower)
# check for invalid dimensions
if left < right and upper < lower and right != 0 and lower != 0:
img = img.crop((left, upper, right, lower))
insert_log(
f"[TRANSFORM] Cropped image region ({left}, {upper}, {right}, {lower}).")
else:
insert_log(
"[WARN] Invalid cropping dimensions. No cropping performed.")
else:
insert_log("[WARN] Incorrect cropping syntax. No cropping performed.")
return img
def func_transform_scale(img):
"""
Scales image based on input and resampling selection.
Returns scaled image if input is valid, otherwise returns original image.
"""
factor = transform_scale_entry.get()
if is_float(factor) and float(factor) > 0:
scale_method = RESAMPLING.index(transform_scale_resample.get())
img = ImageOps.scale(img, float(factor), resample=scale_method)
insert_log(
f"[TRANSFORM] Scaled image with factor {factor} using {RESAMPLING[scale_method]}.")
else:
insert_log(f"[WARN] Invalid scaling factor. No scaling performed.")
return img
def func_transform_expand(img):
"""
Adds border to image.
Returns expanded image if input is valid, otherwise returns original image.
"""
border = transform_expand_entry.get()
if border.isnumeric():
img = ImageOps.expand(img, int(border), FILL_COLOR)
insert_log(
f"[TRANSFORM] Expanded image by {border} pixels with color {FILL_COLOR}.")
else:
insert_log(f"[WARN] Invalid border width. No expanding performed.")
return img
def func_transform_flip(img):
"""
Flips image.
Returns flipped image.
"""
img = ImageOps.flip(img)
insert_log("[TRANSFORM] Flipped image.")
return img
def func_transform_mirror(img):
"""
Mirrors image.
Returns mirrored image.
"""
img = ImageOps.mirror(img)
insert_log("[TRANSFORM] Mirrored image.")
return img
def func_transform_equalize(img):
"""
Equalizes image histogram.
Returns image with equalized histogram.
"""
img = ImageOps.equalize(img, mask=None)
insert_log("[TRANSFORM] Equalized image histogram.")
return img
def func_transform_grayscale(img):
"""
Grayscales image.
Returns grayscaled image.
"""
img = ImageOps.grayscale(img)
insert_log("[TRANSFORM] Grayscaled image.")
return img
def func_transform_invert(img):
"""
Inverts image.
Returns inverted image.
"""
img = ImageOps.invert(img)
insert_log("[TRANSFORM] Inverted image.")
return img
def func_transform_posterize(img):
"""
Reduces the number of bits for each color channel.
Returns posterized image or original image if argument is invalid.
"""
bits = transform_posterize_entry.get()
if bits.isnumeric() and int(bits) > 0 and int(bits) < 9:
img = ImageOps.posterize(img, int(bits))
insert_log(f"[TRANSFORM] Posterized image, kept {bits} bit(s).")
else:
insert_log(
"[WARN] Invalid posterize argument. Did not posterize image.")
return img
def func_transform_solarize(img):
"""
Inverts all pixel values above a threshold.
Returns solarized image or original image if argument is invalid.
"""
threshold = transform_solarize_entry.get()
if threshold.isnumeric() and int(threshold) >= 0:
img = ImageOps.solarize(img, int(threshold))
insert_log(f"[TRANSFORM] Solarized image with threshold {threshold}.")
else:
insert_log(
"[WARN] Invalid solarize argument. Did not solarize image.")
return img
def func_transform_blur(img):
"""
Applies blur filter to image.
Returns blurred image.
"""
img = img.filter(ImageFilter.BLUR)
insert_log("[TRANSFORM] Applied blur to image.")
return img
def func_transform_contour(img):
"""
Applies contour filter to image.
Returns contoured image.
"""
img = img.filter(ImageFilter.CONTOUR)
insert_log("[TRANSFORM] Applied contour to image.")
return img
def func_transform_detail(img):
"""
Applies detail filter to image.
Returns detailed image.
"""
img = img.filter(ImageFilter.DETAIL)
insert_log("[TRANSFORM] Applied detail to image.")
return img
def func_transform_edge_enhance(img):
"""
Applies edge enhance filter to image.
Returns edge enhanced image.
"""
img = img.filter(ImageFilter.EDGE_ENHANCE)
insert_log("[TRANSFORM] Applied edge enhance to image.")
return img
def func_transform_edge_enhance_more(img):
"""
Applies more edge enhance filter to image.
Returns more edge enhanced image.
"""
img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
insert_log("[TRANSFORM] Applied more edge enhance to image.")
return img
def func_transform_emboss(img):
"""
Applies emboss filter to image.
Returns embossed image.
"""
img = img.filter(ImageFilter.EMBOSS)
insert_log("[TRANSFORM] Applied emboss to image.")
return img
def func_transform_find_edges(img):
"""
Applies edgefind filter to image.
Returns image with edge find filter.
"""
img = img.filter(ImageFilter.FIND_EDGES)
insert_log("[TRANSFORM] Applied edgefind to image.")
return img
def func_transform_sharpen(img):
"""
Applies sharpen filter to image.
Returns sharpened image.
"""
img = img.filter(ImageFilter.SHARPEN)
insert_log("[TRANSFORM] Applied sharpen to image.")
return img
def func_transform_smooth(img):
"""
Applies smooth filter to image.
Returns smoothed image.
"""
img = img.filter(ImageFilter.SMOOTH)
insert_log("[TRANSFORM] Applied smoothing to image.")
return img
def func_transform_smooth_more(img):
"""
Applies more smooth filter to image.
Returns more smoothed image.
"""
img = img.filter(ImageFilter.SMOOTH_MORE)
insert_log("[TRANSFORM] Applied more smoothing to image.")
return img
def func_transform_color(img):
"""
Enhances color of image based on input.
Returns enhanced image or original image if input is invalid.
"""
factor = transform_color_entry.get()
if is_float(factor) and float(factor) >= 0:
img = ImageEnhance.Color(img).enhance(float(factor))
insert_log(
f"[TRANSFORM] Enhanced color of image with factor {factor}.")
else:
insert_log("[WARN] Invalid color factor. No enhancing performed.")
return img
def func_transform_contrast(img):
"""
Enhances contrast of image based on input.
Returns enhanced image or original image if input is invalid.
"""
factor = transform_contrast_entry.get()
if is_float(factor) and float(factor) >= 0:
img = ImageEnhance.Contrast(img).enhance(float(factor))
insert_log(
f"[TRANSFORM] Enhanced contrast of image with factor {factor}.")
else:
insert_log("[WARN] Invalid contrast factor. No enhancing performed.")
return img
def func_transform_brightness(img):
"""
Enhances brightness of image based on input.
Returns enhanced image or original image if input is invalid.
"""
factor = transform_brightness_entry.get()
if is_float(factor) and float(factor) >= 0:
img = ImageEnhance.Brightness(img).enhance(float(factor))
insert_log(
f"[TRANSFORM] Enhanced brightness of image with factor {factor}.")
else:
insert_log("[WARN] Invalid brightness factor. No enhancing performed.")
return img
def func_transform_sharpness(img):
"""
Enhances sharpness of image based on input.
Returns sharpened image or original image if input is invalid.
"""
factor = transform_sharpness_entry.get()
if is_float(factor) and float(factor) >= 0:
img = ImageEnhance.Sharpness(img).enhance(float(factor))
insert_log(
f"[TRANSFORM] Enhanced sharpness of image with factor {factor}.")
else:
insert_log("[WARN] Invalid sharpness factor. No enhancing performed.")
return img
def func_advanced_convert_filetype(img_extension):
"""
Converts the filetype of the image.
Returns the new extension of the image as ".ext"
"""
new_type = advanced_convert_filetype_option.get()
img_extension = f".{new_type.lower()}"
insert_log(f"[ADVANCED] Converted image to filetype {new_type}.")
return img_extension
def func_advanced_convert_mode(img):
"""
Converts the mode of the image.
Returns the image with the converted mode.
"""
new_mode = advanced_convert_modes_option.get()
img = img.convert(new_mode)
insert_log(f"[ADVANCED] Converted image to mode {new_mode}.")
return img
def process(img):
"""
Process an image based on selected options.
Returns the modified Image object, the image name, the final extension and everything to be included in the image statistics post-modification.
"""
img_name = os.path.splitext(os.path.basename(img.filename))[0]
img_extension = os.path.splitext(img.filename)[1]
img_name_full = os.path.split(img.filename)[1]
img_stats = ""
insert_log(
f"[FILE] Processing {img_name_full} ({img.format}, {img.width}x{img.height}, {img.mode})...")
# transform: transform
img = check(transform_resize, func_transform_resize, img)
img = check(transform_transpose, func_transform_transpose, img)
img = check(transform_crop, func_transform_crop, img)
img = check(transform_scale, func_transform_scale, img)
img = check(transform_expand, func_transform_expand, img)
# transform: operations
img = check(transform_flip, func_transform_flip, img)
img = check(transform_mirror, func_transform_mirror, img)
img = check(transform_equalize, func_transform_equalize, img)
img = check(transform_grayscale, func_transform_grayscale, img)
img = check(transform_invert, func_transform_invert, img)
img = check(transform_posterize, func_transform_posterize, img)
img = check(transform_solarize, func_transform_solarize, img)
# transform: filters
img = check(transform_blur, func_transform_blur, img)
img = check(transform_contour, func_transform_contour, img)
img = check(transform_detail, func_transform_detail, img)
img = check(transform_edge_enhance, func_transform_edge_enhance, img)
img = check(transform_edge_enhance_more,
func_transform_edge_enhance_more, img)
img = check(transform_emboss, func_transform_emboss, img)
img = check(transform_find_edges, func_transform_find_edges, img)
img = check(transform_sharpen, func_transform_sharpen, img)
img = check(transform_smooth, func_transform_smooth, img)
img = check(transform_smooth_more, func_transform_smooth_more, img)
# transform: enhancements
img = check(transform_color, func_transform_color, img)
img = check(transform_contrast, func_transform_contrast, img)
img = check(transform_brightness, func_transform_brightness, img)
img = check(transform_sharpness, func_transform_sharpness, img)
# advanced: conversion
img_extension = check(advanced_convert_filetype,
func_advanced_convert_filetype, img_extension)
img = check(advanced_convert_modes, func_advanced_convert_mode, img)
# advanced: statistics
if advanced_stats.get():
img_stats += f"extrema:{str(img.getextrema())}\n" if advanced_extrema.get() else ""
img_stats += f"count:{str(ImageStat.Stat(img).count)}\n" if advanced_count.get() else ""
img_stats += f"sum:{str(ImageStat.Stat(img).sum)}\n" if advanced_sum.get() else ""
img_stats += f"sum2:{str(ImageStat.Stat(img).sum2)}\n" if advanced_sum2.get() else ""
img_stats += f"mean:{str(ImageStat.Stat(img).mean)}\n" if advanced_mean.get() else ""
img_stats += f"median:{str(ImageStat.Stat(img).median)}\n" if advanced_median.get() else ""
img_stats += f"rms:{str(ImageStat.Stat(img).rms)}\n" if advanced_rms.get() else ""
img_stats += f"var:{str(ImageStat.Stat(img).var)}\n" if advanced_var.get() else ""
img_stats += f"stddev:{str(ImageStat.Stat(img).stddev)}\n" if advanced_stddev.get() else ""
# finished image processing
insert_log(f"[FILE] Successfully processed {img_name_full}.")
return (img, img_name, img_extension, img_stats)
def start_processing():
"""
Perform image batch processing for each image in a directory and log errors.
Optionally, log statistics for each image post-modification in an associated .txt file.
"""
global THREAD_COUNT, IMG_COUNT, ERR_COUNT
INPUT_PATH = general_input_entry.get()
OUTPUT_PATH = general_output_entry.get()
IMG_COUNT = 0
ERR_COUNT = 0
in_directory = ""
out_directory = ""
try:
in_directory = os.fsencode(INPUT_PATH)
out_directory = os.fsencode(OUTPUT_PATH)
except Exception as e:
insert_log(f"[ERROR] {str(e)}")
THREAD_COUNT = 0 if THREAD_COUNT < 0 else (THREAD_COUNT - 1)
log_active_label.config(text=f"Active Threads: {THREAD_COUNT}")
return
in_files = []
out_files = []
insert_log("[INFO] Started processing job.")
# create directories if they do not exist
try:
if not os.path.exists(in_directory):
os.makedirs(in_directory)
if not os.path.exists(out_directory):
os.makedirs(out_directory)
except Exception as e:
insert_log(f"[ERROR] {str(e)}")
THREAD_COUNT = 0 if THREAD_COUNT < 0 else (THREAD_COUNT - 1)
log_active_label.config(text=f"Active Threads: {THREAD_COUNT}")
return
# check if any file has the same name and warn user if overwrite checkbox not checked
for file in os.listdir(in_directory):
in_files.append(os.fsdecode(os.path.splitext(
os.path.basename(file))[0]).lower().strip())
for file in os.listdir(out_directory):
out_files.append(os.fsdecode(os.path.splitext(
os.path.basename(file))[0]).lower().strip())
if not set(in_files).isdisjoint(out_files) and not general_overwrite.get():
if not messagebox.askokcancel("Overwrite Images?", "At least one image has the same name in the output directory.\nAre you sure you want to overwrite these files?"):
insert_log("[INFO] Aborted processing job.")
THREAD_COUNT = 0 if THREAD_COUNT < 0 else (THREAD_COUNT - 1)
log_active_label.config(text=f"Active Threads: {THREAD_COUNT}")
return
# try opening each file in directory as image, otherwise show error on load
for file in os.listdir(in_directory):
try:
img_path = os.fsdecode(os.path.join(