-
Notifications
You must be signed in to change notification settings - Fork 0
/
hd_mosaic.py
1365 lines (1167 loc) · 55.8 KB
/
hd_mosaic.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
"""HD Mosaic
A script that creates a photo mosaic by comparing sub-tile pixels for a higher quality result.
Copyright (C) 2024 Ethan Lacasse
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
# ruff: noqa: PLW0603
import argparse
import os
import random
import shutil
import sys
import time
import numpy as np
from PIL import Image, ImageChops, ImageEnhance, ImageFilter, ImageOps
# |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
# | _ __ __ _ . . ___ __ |
# | | \ |_ |_ /_\ | | | | (__` |
# | |__/ |__ | / \ |__| |__ | .__) |
# | |
# |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
# |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DEFAULTS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
# |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
DEFAULT_SCALE = 1.0
DEFAULT_COMPARE = '3x3'
DEFAULT_LINEAR_WEIGHT = 1.0
DEFAULT_KERNEL_WEIGHT = 0.1
DEFAULT_OVERLAY = 0.0
DEFAULT_SUBTLE_OVERLAY = 0.5
DEFAULT_REPEAT_PENALTY = 0.1
DEFAULT_SUBDIVISIONS = 1
DEFAULT_SUBDIVISION_THRESHOLD = 150
# |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
# | __ __ __ _ __ |
# | / _ | / \ |__) /_\ | (__` |
# | \__) |__ \__/ |__) / \ |__ .__) |
# | |
# |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
# |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GLOBALS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
# |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
VERBOSE = False
SHOW_PREVIEW = False
USER_INPUT = None
MOSAIC = None
# ||==============================================================================================||
# || __ _ _____ _____ _____ ____ __ _ _____ __ _ ________ ||
# || || | // ` || ` || \\ || |\\ | || \\ || | ' || ' ||
# || || | \\___ ||___ ||___// || | \\ | ||___// || | || ||
# || || | \\ || || \\ || | \\ | || || | || ||
# || \\___/ \____// ||____, || \\, _||_ | \\| || \\___/ _||_ ||
# || ||
# ||==============================================================================================||
# ||========================================= USER INPUT =========================================||
# ||==============================================================================================||
# ___ __
# | _ ,_ _|_ |__) __╮ ,_ __╮ , , _ _|_ _ ,_
# _|_ | | |_) (_| | | (_/| | (_/| |\/| (/, | (/, |
# j
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class InputParameter:
"""Stores information about an input parameter"""
def __init__(
self,
name: str,
*,
help: str = '',
type: callable = str,
prompt: str|None = None,
metavar: str|None = None,
default=None,
static: bool = False,
allow_none: bool = False):
"""Create an InputParameter object for handling `input` options."""
self.name = name
self.help = help
self.prompt = f'{name}: {help}' if prompt is None else prompt
self.type = type
self.metavar = metavar
self.default = default if default is None else type(default)
self.value = default if default is None else type(default)
self.static = static
self.allow_none = allow_none
def set_val(self, val):
"""Assign a value to this parameter"""
if val is None and self.allow_none:
self.value = val
else:
self.value = self.type(val)
def prompt_string(self, add_in: str|None = None) -> str:
"""Get a printable string prompting the user to provide a new value."""
string = f"\n\n{ctext(ctext(self.name, 'HEADER'), 'BOLD')} : {ctext(self.metavar, 'GRAY')}"
if self.value is not None:
string += f" = {ctext(str(self.value), 'GRAY')}"
if self.default is not None:
string += ctext(f' (default: {self.default})', 'GRAY')
string += ctext(f'\n{self.help}', 'gray')
string += ctext(f'\n\n{self.prompt}', 'OKBLUE')
if add_in:
string += f'\n\n{add_in}'
else:
string += '\n\n'
string += ctext(f'\n{self.name} = ', 'HEADER')
return string
# ___ _
# | _ ,_ _|_ /_\ _ _|_ ° _ _
# _|_ | | |_) (_| | / \ (_, | | (_) | |
# j
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class InputAction:
"""Stores a callback for UserInterface"""
def __init__(
self,
name: str,
description: str,
callback: callable):
"""Create a new InputAction with given name, description, and callback."""
self.name = name
self.description = description
self.callback = callback
# . . ___ _
# | | _ _ ,_ | _ _|_ _ ,_ /_ __╮ _ _
# |__| _\ (/, | _|_ | | | (/, | | (_/| (_, (/,
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class UserInterface:
"""Gets input variables from the user, creating a simple menu."""
def __init__(self, name: str):
"""Create an object for managing a simple CLI menu."""
self.name = name
self.categories = {}
self.params = {}
self.actions = {}
self.option_callback = None
def __getitem__(self, key):
return self.params[key]
@staticmethod
def _clear_screen():
size = shutil.get_terminal_size()
print('\n' * size.lines)
def add_category(self, category: str, description: str):
"""Add a new submenu named "category", which organizes some parameters."""
self.categories[category] = {'desc': description, 'params': []}
def add_parameter(
self,
name,
category='',
**kwargs):
"""Add a new parameter to the menu."""
param = InputParameter(name, **kwargs)
self.categories[category]['params'].append(name)
self.params[name] = param
def add_action(
self,
name,
desc,
callback):
"""Add a new action to the menu."""
self.actions[name] = InputAction(name, desc, callback)
def get_param(self, name: str, prev_message: str = '') -> str:
"""Prompt the user to get a new value for parameter."""
param = self[name]
add_in = None
# get user input for this param, and set it
# if there is an error, print it nicely and keep trying:
while True:
try:
# clear screen
self._clear_screen()
print(prev_message)
inpt = input(param.prompt_string(add_in=add_in))
inpt = self.pre_process_input(inpt)
param.set_val(inpt)
if self.option_callback is not None:
self.option_callback(name)
return ctext(f'Set {param.name} to {param.value}.', 'OKGREEN')
except (ValueError) as e:
add_in = ctext(getattr(e, 'message', str(e)), 'WARNING')
def get_static(self):
"""Prompt the user to fill all static parameters"""
prev_message = ''
for name, param in self.params.items():
if param.static:
prev_message = self.get_param(name, prev_message=prev_message)
if prev_message:
print(prev_message)
@staticmethod
def pre_process_input(inpt: str) -> str:
"""Clean input, and also handle exit command"""
inpt = inpt.strip()
if inpt == 'exit':
sys.exit()
return inpt
def _print_main_menu(self, ex_txt: str|None = None):
# print the menu options
self._clear_screen()
cprint(self.name, 'OKBLUE')
cprint('\nActions:', 'GRAY')
for idx, items in enumerate(self.actions.items()):
name, action = items
print(f'{ctext(str(idx), "HEADER")}: {ctext(name, "OKCYAN")} {ctext(f"- {action.description}", "GRAY")}')
cprint('\nOptions:', 'GRAY')
for idx, item in enumerate(self.categories.items(), start=len(self.actions)):
category, vals = item
desc = vals['desc']
print(f'{ctext(str(idx), "HEADER")}: {ctext(category, "HEADER")} {ctext(f"- {desc}", "GRAY")}')
if ex_txt:
print('\n' + ex_txt)
else:
print('\n')
cprint('Select an action or option category:', 'GRAY')
def _print_category_menu(self, category: str, ex_txt: str|None = None):
# print the menu options
self._clear_screen()
desc = self.categories[category]['desc']
params = self.categories[category]['params']
cprint(category, 'OKBLUE')
cprint(desc, 'GRAY')
cprint('\n\nOptions:', 'GRAY')
for idx, param in enumerate(params):
print(
f'{ctext(str(idx), "HEADER")}{ctext(":", "GRAY")}'
f'{ctext(param, "HEADER")}{ctext(" = ", "GRAY")}'
f'{ctext(repr(self[param].value), "DARKBLUE")}'
f'{ctext(f" - {self[param].help}", "GRAY")}',
)
if ex_txt:
print('\n' + ex_txt)
else:
print('\n')
cprint('Select an option:', 'GRAY')
def category_menu(self, category, ex_txt=None):
"""Show the menu for this category"""
# ex txt holds feedback info to display above the menu
params = self.categories[category]['params']
while True:
# keep running the menu until back is given
self._print_category_menu(category, ex_txt=ex_txt)
choice = self.pre_process_input(input())
choice = self.filter_choice(choice, params)
if choice in {'back', '..', '-'}:
return
if choice in params:
ex_txt = self.get_param(choice)
elif choice.isnumeric() and int(choice) < len(params):
param = params[int(choice)]
ex_txt = self.get_param(param)
else:
ex_txt = ctext(f"'{choice}' isn't a valid choice.", 'WARNING')
def main_menu(self, ex_txt: str|None = None):
"""Show the main menu"""
actions = list(self.actions.keys())
categories = list(self.categories.keys())
all_options = actions + categories
while True:
self._print_main_menu(ex_txt=ex_txt)
choice = self.pre_process_input(input())
choice = self.filter_choice(choice, all_options)
if choice in self.actions:
ex_txt = self.actions[choice].callback()
elif choice in self.categories:
self.category_menu(choice)
ex_txt = None
else:
ex_txt = ctext(f"'{choice}' isn't a valid choice.", 'WARNING')
@staticmethod
def filter_choice(choice: str, options: list) -> str:
"""Try fitting choice to option, so user input doesn't need to be so specific."""
if choice in options:
return choice
if choice.isnumeric() and int(choice) < len(options):
return options[int(choice)]
# finally, try fuzzy matching choice to options
options = [opt for opt in options if opt.lower().startswith(choice.lower())]
print(options)
if len(options) == 1:
return options[0]
return choice
def verify_all_filled(self):
"""Force all values to be filled (except for those that are allowed to be None)"""
for name, param in self.params.items():
if param.value is None and not param.allow_none:
self.get_param(name)
# ||==============================================================================================||
# || __ __ ____ __ _ _____ ____ _____ ____ _____ ________ ||
# || |\\ /|| /\ || |\\ | // ` // ` || \\ || || \\ ' || ' ||
# || | \\ / || / \\ || | \\ | \\___ || ||___// || ||___// || ||
# || | \\/ || /___\\ || | \\ | \\ || || \\ || || || ||
# || | || / \\ _||_ | \\| \____// \\___/ || \\, _||_ || _||_ ||
# || ||
# ||==============================================================================================||
# ||========================================= MAIN SCRIPT ========================================||
# ||==============================================================================================||
# :------------------------------------------------------------------------------------------------:
# : ___ , , ___ ___ ___ _ ___ ___ _ ___ ___ __ , , :
# : | |\ | | | | /_\ | | _/ /_\ | | / \ |\ | :
# : _|_ | \| _|_ | _|_ / \ |__ _|_ /__, / \ | _|_ \__/ | \| :
# : :
# :------------------------------------------------------------------------------------------------:
# :---------------------------------------- Initialization ----------------------------------------:
# :------------------------------------------------------------------------------------------------:
def init_parser():
"""Get argparse arguments."""
global VERBOSE
# argparser for verbose and help messages
parser = argparse.ArgumentParser(
description=ctext(
'This tool can be used to create a high-quality image mosaic '
'by comparing given image tiles to a source image.',
'DARKBLUE',
),
)
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()
VERBOSE = args.verbose
def init_ui() -> UserInterface:
"""Create and initialize the UserInterface object
Returns:
UserInterface
"""
ui = UserInterface('hd_mosaic')
ui.add_category('input/output', 'Options for the input/output images')
ui.add_category('tiles', 'Options relating to the tiles')
ui.add_category('weights', 'Weights to use for different comparison methods')
ui.add_category('overlay', 'Options relating to the image overlay')
ui.add_category('subdivision', 'Options relating to the tile subdivision')
ui.add_category('other', 'Uncategorized options')
ui.add_parameter(
'tile_folder', category='tiles',
help='The source folder containing all the image tiles.',
prompt='Please provide the path to a folder of images to use as tiles:',
metavar='PATH', type=folder_path,
)
ui.add_parameter(
'tile_load_resolution', category='tiles',
help='The resolution to load the tiles in with.',
prompt="""Please provide the resolution you would like to load the tiles in with:
(Small resolutions might look bad, big resolutions might be very slow. 128x128 is an okay starting point.)
(Changing this value will require a re-load of the input tiles.)""",
metavar='INT|INTxINT', type=InputScale,
)
ui.add_parameter(
'xy_tiles', category='tiles',
help='The number of horizontal and vertical tiles to use in the output mosaic.',
prompt='Please provide the number of horizontal/vertical tiles you would like to use:',
metavar='INT|INTxINT', type=InputScale,
)
ui.add_parameter(
'source_image', category='input/output',
help='The source image to base the mosaic on.',
prompt='Provide the path to an image to base this mosaic on:',
metavar='PATH', type=file_path,
)
ui.add_parameter(
'output', category='input/output',
help='The source image to base the mosaic on.',
prompt='Provide the path/name of the output image:',
metavar='PATH', allow_none=True,
)
ui.add_parameter(
'input_rescale', category='input/output',
help='Multiplier to rescale source image by.',
prompt='Enter a rescale amount for the source_image:',
metavar='FLOAT', default=DEFAULT_SCALE, type=float,
)
ui.add_parameter(
'compare_res', category='tiles',
help='The resolution that tiles will be compared at.',
prompt='Enter a new compare scale:',
metavar='INT|INTxINT', default=DEFAULT_COMPARE, type=InputScale,
)
ui.add_parameter(
'linear_error_weight', category='weights',
help="How much the 'linear' comparison affects the output.",
prompt='Enter a new linear weight:',
metavar='FLOAT', default=DEFAULT_LINEAR_WEIGHT, type=float,
)
ui.add_parameter(
'kernel_error_weight', category='weights',
help="How much the 'kernel difference' comparion affects the output.",
prompt='Enter a new kernel weight:',
metavar='FLOAT', default=DEFAULT_KERNEL_WEIGHT, type=float,
)
ui.add_parameter(
'overlay_opacity', category='overlay',
help="The alpha for a 'normal' overlay of the target image over the mosaic.",
prompt='Enter a new overlay alpha:',
metavar='FLOAT', default=DEFAULT_OVERLAY, type=float,
)
ui.add_parameter(
'subtle_overlay', category='overlay',
help='The alpha for an alternate, less sharp method of overlaying the target image on the mosaic.',
prompt='Enter a new subtle overlay alpha:',
metavar='FLOAT', default=DEFAULT_SUBTLE_OVERLAY, type=float,
)
ui.add_parameter(
'repeat_penalty', category='weights',
help='How much to penalize repetition when selecting tiles.',
prompt='Enter a new repetition penalty:',
metavar='FLOAT', default=DEFAULT_REPEAT_PENALTY, type=float,
)
ui.add_parameter(
'show', category='other',
help='If True, opens a preview of the output image upon completion.',
prompt="Enter True or False to enable/disable 'show':",
metavar='BOOL', default=False, type=bool,
)
ui.add_parameter(
'subdivisions', category='subdivision',
help='Max number of subdivisions allowed in each main tile.',
prompt='Enter the new number of subdivisions:',
metavar='INT', default=DEFAULT_SUBDIVISIONS, type=int,
)
ui.add_parameter(
'subdivision_threshold', category='subdivision',
help='Detail values higher than this threshold will create a subdivision.',
prompt='Enter a new subdiv theshold:',
metavar='INT', default=DEFAULT_SUBDIVISION_THRESHOLD, type=int,
)
ui.add_parameter(
'detail_map', category='subdivision',
help='An image that controls where extra subdivisions are added.',
prompt='Enter the path to an image to use as a detail map:',
metavar='PATH', allow_none=True, type=file_path,
)
return ui
def set_cwd():
"""Fix issue where CWD might be in System32
If you run the script by double clicking the file in windows,
the CWD might be in System32 instead of in the folder where the script is located.
To fix this, we can just check if this is the CWD on startup and set it to the script location.
"""
if 'system32' in os.getcwd().lower():
try:
os.chdir(os.path.split(__file__)[0])
except (NameError, OSError) as e:
if VERBOSE:
print(e)
# :------------------------------------------------------------------------------------------------:
# : __ _ __ _ __ __ :
# : / ` /_\ | | |__) /_\ / ` |_/ (__` :
# : \__, / \ |__ |__ |__) / \ \__, | \ .__) :
# : :
# :------------------------------------------------------------------------------------------------:
# :------------------------------------------- Callbacks ------------------------------------------:
# :------------------------------------------------------------------------------------------------:
def load_options_into_mosaic(modified_option):
"""Load given option from USER_INPUT into MOSAIC"""
global SHOW_PREVIEW
val = USER_INPUT[modified_option].value
match modified_option:
case 'source_image':
MOSAIC.config(source_image_path=val)
case 'xy_tiles':
MOSAIC.config(output_tiles_res=val)
case 'input_rescale':
MOSAIC.config(source_image_rescale=val)
case 'overlay_opacity':
MOSAIC.config(overlay_alpha=val)
case 'subtle_overlay':
MOSAIC.config(subtle_overlay_alpha=val)
case 'detail_map':
MOSAIC.config(detail_map_path=val)
case 'show':
SHOW_PREVIEW = val
case 'tile_folder':
MOSAIC.config(tile_load_dir=val)
case 'output':
# avoid any keys not used by MOSAIC
return
case _:
MOSAIC.config(**{modified_option: val})
def make_mosaic() -> str:
"""Make a mosaic using the Mosaic class."""
USER_INPUT.verify_all_filled()
MOSAIC.fit_tiles()
output_path = USER_INPUT['output'].value
if output_path is None:
output_path = gen_output_path()
MOSAIC.save(output_path=output_path, show_preview=SHOW_PREVIEW)
return ctext(f'Saved as "{output_path}"', 'OKGREEN')
# :------------------------------------------------------------------------------------------------:
# : _ _ __ __ __ __ __ :
# : |__| |_ | |__) |_ |__) (__` :
# : | | |__ |__ | |__ | \_ .__) :
# : :
# :------------------------------------------------------------------------------------------------:
# :-------------------------------------------- Helpers -------------------------------------------:
# :------------------------------------------------------------------------------------------------:
def gen_output_path() -> str:
"""Generate a default output filename."""
output_name = 'mosaic'
for param_name, symbol in [
('xy_tiles', ''),
('input_rescale', 'S'),
('compare_res', 'c'),
('linear_error_weight', 'l'),
('kernel_error_weight', 'k'),
('overlay_opacity', 'o'),
('subtle_overlay', 's'),
('repeat_penalty', 'r'),
('subdivisions', 'd'),
('subdivision_threshold', 't'),
]:
param = USER_INPUT[param_name]
if param.value != param.default:
output_name += f'_{symbol}{param.value}'
output_name += '.jpg'
return output_name
def file_path(path: str) -> str:
"""Verify (and clean) a path to an image
Raises:
ValueError: When path is not valid
"""
# remove filepath quotes
for quote in ("'", '"'):
if path.startswith(quote) and path.endswith(quote):
path = path.removeprefix(quote).removesuffix(quote)
if os.path.exists(path) and os.path.isfile(path):
return path
msg = f"Couldn't find a file at '{path}'. Make sure this is a valid path to an image."
raise ValueError(msg)
def folder_path(path: str) -> str:
"""Verify (and clean) a path to a folder
Raises:
ValueError: when path isn't correct.
"""
# remove filepath quotes
for quote in ("'", '"'):
if path.startswith(quote) and path.endswith(quote):
path = path.removeprefix(quote).removesuffix(quote)
if os.path.exists(path) and os.path.isdir(path):
return path
msg = f"Couldn't find a folder at '{path}'. Make sure this is a valid path to a folder of images."
raise ValueError(msg)
def crop_from_rescale(old_size, new_size) -> tuple[int, int, int, int]:
"""Create a crop for a scale that maintains the aspect ratio"""
ow, oh = old_size
nw, nh = new_size
width_shrink = (ow - nw) // 2
height_shrink = (oh - nh) // 2
return (
width_shrink,
height_shrink,
ow - width_shrink,
oh - height_shrink,
)
# |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
# | __ __ |
# | |\\ /|| __ ° |
# | | \\ / || __\ ╮ __ |
# | | \\/ || / | | ╮/ | |
# | | || \__/|, |, | |, |
# | |
# |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
# |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
# |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
def main():
"""Run the main script."""
global USER_INPUT, MOSAIC
# setup parser and ui
set_cwd()
init_parser()
ui = USER_INPUT = init_ui()
# add mosaic action to ui
ui.add_action('Make_Mosaic', 'Generate the output mosaic', make_mosaic)
# get static params, use those to configure a new Mosaic
MOSAIC = Mosaic()
ui.option_callback = load_options_into_mosaic
# load all default vals
for name, param in ui.params.items():
if param.value is not None:
load_options_into_mosaic(name)
# start the main menu of the program
ui.main_menu()
# ||==============================================================================================||
# || __ __ _____ __ _____ _____ _____ ____ __ _____ _____ _____ _____ ||
# || || |||| `|| || \\|| `|| \\ // `|| /\ // `// `|| `// ` ||
# || ||____||||___ || ||___//||___ ||___// || || / \\ \\___ \\___ ||___ \\___ ||
# || || |||| || || || || \\ || || /___\\ \\ \\|| \\ ||
# || || ||||____,||___,|| ||____,|| \\, \\___/||___,/ \\\____//\____//||____,\____// ||
# || ||
# ||==============================================================================================||
# ||====================================== Helper Classes ======================================||
# ||==============================================================================================||
# :------------------------------------------------------------------------------------------------:
# : __ __ ___ , , ___ __ __ :
# : |__) |__) | |\ | | |_ |__) :
# : | | \_ _|_ | \| | |__ | \_ :
# : :
# :------------------------------------------------------------------------------------------------:
# :-------------------------------------------- Printer -------------------------------------------:
# :------------------------------------------------------------------------------------------------:
class Printer:
"""Simple helper for printing progress text."""
_last_line_len = 0
_max_line_len = 0
_load_chars = ['⢿', '⣻', '⣽', '⣾', '⣷', '⣯', '⣟', '⡿']
_char_idx = 0
_prntclrs = {
'GRAY': '\033[90m',
'DARKBLUE': '\033[34m',
'DARKMAGENTA': '\033[35m',
'HEADER': '\033[95m',
'OKBLUE': '\033[94m',
'OKCYAN': '\033[96m',
'OKGREEN': '\033[92m',
'WARNING': '\033[93m',
'FAIL': '\033[91m',
'ENDC': '\033[0m',
'BOLD': '\033[1m',
'UNDERLINE': '\033[4m',
}
def next_char(self) -> str:
"""Get the next loading character"""
self._char_idx = (self._char_idx + 1) % len(self._load_chars)
return self._load_chars[self._char_idx]
def _pad_text(self, text: str) -> str:
newtext = \
f"{text}{' ' * (self._last_line_len - len(text))}" \
if len(text) < self._last_line_len \
else text
self._last_line_len = len(text)
return newtext
def update_text_len(self):
"""Update printer max text len (based on terminal size)"""
self._max_line_len = shutil.get_terminal_size().columns
def _ensure_length(self, text: str) -> str:
"""Prevent text len from being too long."""
if len(text) > self._max_line_len:
return f'{text[:self._max_line_len - 3]}...'
return text
@classmethod
def ctext(cls, text: str, color: str) -> str:
"""Generate a colored string and return it."""
color = cls._prntclrs.get(color.upper(), 'ENDC')
return f"{color}{text}{cls._prntclrs['ENDC']}"
def cprint(self, text: str, color: str):
"""Print in color (and pad lines to erase old text)"""
text = self._pad_text(str(text))
print(self.ctext(text, color))
def write_progress(self, text):
"""Write status to the terminal without starting a new line, erasing old text."""
text = f' {self.next_char()} - {text}...'
text = self._ensure_length(self._pad_text(text))
print(self.ctext(text, 'OKCYAN'), end='\r')
# printer is the main way this script prints information.
# so we'll simplify its method calls for readability:
Printer = Printer()
Printer.update_text_len()
cprint = Printer.cprint
ctext = Printer.ctext
cwrite = Printer.write_progress
# :------------------------------------------------------------------------------------------------:
# : _ __ __ . . __ ___ ___ , , __ __ :
# : | \ |_ |__) | | / _ | | |\_/| |_ |__) :
# : |__/ |__ |__) |__| \__) | _|_ | | |__ | \_ :
# : :
# :------------------------------------------------------------------------------------------------:
# :------------------------------------------ DebugTimer ------------------------------------------:
# :------------------------------------------------------------------------------------------------:
class DebugTimer:
"""Simple helper for timing various operations"""
def __init__(self, text: str):
"""Create a DebugTimer that times a task named `text`"""
self.text = text
self.start_time = time.time()
def print(self):
"""Print the result of the timer"""
cprint(
f'{self.text}: {time.time() - self.start_time:.2f}s',
'UNDERLINE',
)
# :------------------------------------------------------------------------------------------------:
# : __ __ _ __ :
# : (__` / ` /_\ | |_ :
# : .__) \__, / \ |__ |__ :
# : :
# :------------------------------------------------------------------------------------------------:
# :--------------------------------------------- Scale --------------------------------------------:
# :------------------------------------------------------------------------------------------------:
class Scale:
"""A simple helper for bundling width/height information"""
def __init__(self, width: int, height: int):
"""Create a Scale with given width and height"""
self.w = width
self.h = height
def __iter__(self):
yield from (self.w, self.h)
def __len__(self):
return 2
def __eq__(self, other):
if isinstance(other, str):
return f'{self.w}x{self.h}' == other.lower()
if isinstance(other, tuple) or hasattr(other, '__iter__'):
return tuple(self) == tuple(other)
return NotImplemented
def __hash__(self):
return hash(tuple(self))
def __getitem__(self, idx):
if idx == 0:
return self.w
return self.h
def __repr__(self):
return f'{self.w}x{self.h}'
class InputScale(Scale):
"""Convert an input string into a Scale"""
def __init__(self, intext: str):
"""Create a Scale from an input str
Raises:
ValueError: When string can't be understood as a height/width
"""
text = intext.lower().replace(',', 'x').replace('.', 'x')
try:
if 'x' in text:
width, height = text.split('x')
width, height = int(width), int(height)
else:
width = height = int(text)
except ValueError:
msg = f"'{intext}' can't be interpreted as a scale. (Expected format is 'INT' or 'INTxINT')"
raise ValueError(msg) # noqa: B904
if width == 0 or height == 0:
msg = f'{width}x{height} is too small. Values smaller than 1 are impossible.'
raise ValueError(msg)
super().__init__(width, height)
# ||==============================================================================================||
# || ____ __ _ _____ __ _ ________ ________ ____ __ _____ ||
# || || |\\ | || \\ || | ' || ' ' || ' || || || ` ||
# || || | \\ | ||___// || | || || || || ||___ ||
# || || | \\ | || || | || || || || || ||
# || _||_ | \\| || \\___/ _||_ _||_ _||_ ||___, ||____, ||
# || ||
# ||==============================================================================================||
# ||========================================== InputTile =========================================||
# ||==============================================================================================||
class InputTile:
"""Load/store images and make comparisons between them"""
compare_res = None
kernel_error_weight = DEFAULT_KERNEL_WEIGHT
linear_error_weight = DEFAULT_LINEAR_WEIGHT
repeat_penalty = DEFAULT_REPEAT_PENALTY
"""A class to hold and work on input tiles"""
def __init__(self, img, tile_size):
"""Load one image tile, converted to proper output size"""
if isinstance(img, Image.Image):
self.img = img
else:
self.img = Image.open(img)
# calculate image cropped size to match tile aspect ratio
trgt_w, trgt_h = self._crop_from_ratio((self.img.width, self.img.height), tile_size)
w_delta = self.img.width - trgt_w
h_delta = self.img.height - trgt_h
crop = (
w_delta // 2,
h_delta // 2,
self.img.width - (w_delta // 2),
self.img.height - (h_delta // 2),
)
# ONLY resize when the new size is smaller than the og size
if tile_size.w <= self.img.width and tile_size.h <= self.img.height:
# crop and resize image to tile size
self.img = self.img.resize(tile_size, box=crop)
else:
self.img = self.img.crop(crop)
self.img = self.img.convert(mode='RGB')
self.linear_array = None
self.kernel_diff_array = None
self.repeat_error = 0.0
def setup_compare_arrays(self):
"""Create numpy arrays for comparing image similarity"""
compare_img = self.img.resize(self.compare_res).convert(mode='LAB')
self.linear_array = self._as_linear_array(compare_img)
self.kernel_diff_array = self._as_kernel_diff_array(compare_img)
def get_image(self, resize=None) -> Image.Image:
"""Get the resized tile, and track usage."""
self.repeat_error += InputTile.repeat_penalty
return self.img.resize(resize) if resize else self.img
def compare(self, source) -> float:
"""Get total error score for this tile"""
err = self.repeat_error
err += (np.mean(np.abs(source.linear_array - self.linear_array)) / 255) * InputTile.linear_error_weight
err += (
np.mean(np.abs(source.kernel_diff_array - self.kernel_diff_array)) / 255
) * InputTile.kernel_error_weight
return err
@staticmethod
def _as_kernel_diff_array(img) -> np.array:
"""For each pixel, avg val with neighbors to determine pixel kernel.
return array representing the differences between the pixels and the pixel kernels.
"""
arr = np.array([])
for y in range(img.height):
for x in range(img.width):
# get all neighbors
avg_val = 0
for ky in range(3):
for kx in range(3):
dx = x - 1 + kx
dy = y - 1 + ky
if 0 <= dx < img.width \
and 0 <= dy < img.height:
avg_val += img.getpixel((dx, dy))[0] / 9
# compare to real val
arr = np.append(arr, abs(img.getpixel((x, y))[0] - avg_val))
return arr
@staticmethod
def _as_linear_array(img) -> np.array:
"""Convert Image to an array for comparison"""
# convert to Lab color space for more accurate comparisons
return np.array(
[img.getpixel((x, y)) for y in range(img.height) for x in range(img.width)],
)
@staticmethod
def _crop_from_ratio(width_height, ratio) -> Scale:
"""Return the cropped width/height to match the given ratio"""
w, h = width_height
rw, rh = ratio
s_width_factor = w / h
r_width_factor = rw / rh
width_factor = s_width_factor / r_width_factor
# output must be smaller than input res
if width_factor > 1:
w /= width_factor
else:
h *= width_factor
return Scale(int(w), int(h))
# ||==============================================================================================||
# || __ __ ____ _____ ____ ____ ||
# || |\\ /|| // \\ // ` /\ || // ` ||
# || | \\ / || || || \\___ / \\ || || ||
# || | \\/ || || || \\ /___\\ || || ||
# || | || \\__// \____// / \\ _||_ \\___/ ||
# || ||
# ||==============================================================================================||
# ||=========================================== Mosaic ===========================================||
# ||==============================================================================================||
class Mosaic:
"""A class to hold and work on the mosaic tiles."""
tile_load_resolution = None
arrays_made = False
# debug stuff