-
Notifications
You must be signed in to change notification settings - Fork 7
/
images_to_grids.py
1375 lines (1124 loc) · 47.9 KB
/
images_to_grids.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
# 2024 skunkworxdark (https://github.com/skunkworxdark)
import csv
import io
import json
import math
import os
import re
import textwrap
from itertools import product
from typing import Any, Literal, Union
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFilter, ImageFont, ImageOps
from PIL.Image import Image as PILImageType
from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
from invokeai.app.invocations.image import PIL_RESAMPLING_MAP, PIL_RESAMPLING_MODES
from invokeai.app.invocations.model import MainModelLoaderInvocation
from invokeai.app.invocations.sdxl import SDXLModelLoaderInvocation, SDXLModelLoaderOutput
from invokeai.invocation_api import (
SCHEDULER_NAME_VALUES,
BaseInvocation,
BaseInvocationOutput,
ColorField,
FieldDescriptions,
FloatOutput,
ImageCollectionOutput,
ImageField,
ImageOutput,
Input,
InputField,
IntegerOutput,
InvocationContext,
LatentsField,
LatentsOutput,
ModelIdentifierField,
ModelLoaderOutput,
OutputField,
SchedulerOutput,
StringCollectionOutput,
StringOutput,
UIComponent,
UIType,
WithBoard,
WithMetadata,
invocation,
invocation_output,
)
_downsampling_factor = LATENT_SCALE_FACTOR
# numeric pattern
# - ^s* - start of line then any whitespace
# - [-+]? - optional -+ at a start
# - \s* - any whitespace before number
# - (\d+(\.\d*)?|\.\d+) - number.(number)optional|.number
# - \s* - any whitespace after the number
# - %?\s*$ - optional % and any whitespace after
num_pattern = re.compile(r"^\s*[-+]?\s*(\d+(\.\d*)?|\.\d+)\s*%?\s*$")
def is_numeric(s: str) -> bool:
"""checks if a string is numeric ignoring leading + trailing % and any whitespace."""
return bool(num_pattern.match(s))
def prep_num(s: str) -> str:
"""removes all + or % or whitespace"""
return "".join(s.split()).replace("%", "").replace("+", "")
def is_all_numeric(array: list[str]) -> bool:
"""returns if all elements in an array are numeric or not"""
return all(is_numeric(item) for item in array)
def sort_array(array: list[str]) -> list[str]:
"""sort array of str but if they are all numeric then it will sort the as numbers"""
return sorted(array, key=lambda x: float(prep_num(x))) if is_all_numeric(array) else sorted(array)
def is_all_numeric2(array: list[tuple[str, str, str]], i: int) -> bool:
"""returns if all elements in a 2D array index i are numeric or not"""
return all(is_numeric(item[i]) for item in array)
def sort_array2(array: list[tuple[str, str, str]]) -> list[tuple[str, str, str]]:
"""sort 2D array of str but if they are all numeric then it will sort them as numeric
specifically it will sort them index 1,0 because it is expecting x,y.
This is to ensure it is in the right order for XY grid processing"""
isNum0 = is_all_numeric2(array, 0)
isNum1 = is_all_numeric2(array, 1)
return sorted(
array,
key=lambda x: (
(float(prep_num(x[1])) if isNum1 else x[1]),
(float(prep_num(x[0])) if isNum0 else x[0]),
),
)
def shift(arr: np.ndarray[Any, Any], num: int, fill_value: float = 255.0) -> np.ndarray[Any, Any]:
result = np.full_like(arr, fill_value)
if num > 0:
result[num:] = arr[:-num]
elif num < 0:
result[:num] = arr[-num:]
else:
result[:] = arr
return result
BLEND_MODES = Literal[
"Linear",
"seam-grad",
"seam-sobel1",
"seam-sobel3",
"seam-sobel5",
"seam-sobel7",
"seam-scharr",
]
def get_seam_line(
i1: PILImageType,
i2: PILImageType,
rotate: bool,
gutter: int,
search_size: int = 1,
blend_mode: BLEND_MODES = "seam-grad",
) -> PILImageType:
ia1 = np.array(i1.convert("RGB")) / 255.0
# BT.601 luminance conversion
lc = np.array([0.2989, 0.5870, 0.1140])
if i1.mode != "L":
ia1 = np.tensordot(ia1, lc, axes=1)
ia2 = np.array(i2.convert("RGB")) / 255.0
if i2.mode != "L":
ia2 = np.tensordot(ia2, lc, axes=1)
# calc difference between images
ia = ia2 - ia1
if rotate:
ia = np.rot90(ia, 1)
# array is y by x
max_y, max_x = ia.shape
max_x -= gutter
min_x = gutter
if blend_mode == "seam-sobel1":
# Use Sobel operator for energy calculation
# gx = cv2.Sobel(ia, cv2.CV_64F, 1, 0, ksize=1)
gx = cv2.Sobel(ia, -1, 1, 0, ksize=1)
gy = cv2.Sobel(ia, -1, 0, 1, ksize=1)
energy = np.hypot(gx, gy)
elif blend_mode == "seam-sobel3":
# Use Sobel operator for energy calculation
gx = cv2.Sobel(ia, -1, 1, 0, ksize=3)
gy = cv2.Sobel(ia, -1, 0, 1, ksize=3)
energy = np.hypot(gx, gy)
elif blend_mode == "seam-sobel5":
# Use Sobel operator for energy calculation
gx = cv2.Sobel(ia, -1, 1, 0, ksize=5)
gy = cv2.Sobel(ia, -1, 0, 1, ksize=5)
energy = np.hypot(gx, gy)
elif blend_mode == "seam-sobel7":
# Use Sobel operator for energy calculation
gx = cv2.Sobel(ia, -1, 1, 0, ksize=7)
gy = cv2.Sobel(ia, -1, 0, 1, ksize=7)
energy = np.hypot(gx, gy)
elif blend_mode == "seam-scharr":
# Use Sobel operator for energy calculation
gx = cv2.Scharr(ia, -1, 1, 0)
gy = cv2.Scharr(ia, -1, 0, 1)
energy = np.hypot(gx, gy)
elif blend_mode == "seam-grad":
# Calc the energy in the difference
energy = np.abs(np.gradient(ia, axis=0)) + np.abs(np.gradient(ia, axis=1))
else:
raise ValueError(f"Unsupported blend mode: '{blend_mode}'.")
ie = Image.fromarray((energy * 255.0).astype("uint8"))
print(f"energy{ie.size}")
res = np.copy(energy)
for y in range(1, max_y):
row = res[y, :]
rowl = shift(row, -1)
rowr = shift(row, 1)
res[y, :] = res[y - 1, :] + np.min([row, rowl, rowr], axis=0)
# create an array max_y long
lowest_energy_line = np.empty([max_y], dtype="uint16")
lowest_energy_line[max_y - 1] = np.argmin(res[max_y - 1, min_x : max_x - 1])
for ypos in range(max_y - 2, -1, -1):
lowest_pos = lowest_energy_line[ypos + 1]
lpos = lowest_pos - search_size
rpos = lowest_pos + search_size
lpos = np.clip(lpos, min_x, max_x - 1)
rpos = np.clip(rpos, min_x, max_x - 1)
lowest_energy_line[ypos] = np.argmin(energy[ypos, lpos : rpos + 1]) + lpos
mask = np.zeros_like(ia)
for ypos in range(0, max_y):
to_fill = lowest_energy_line[ypos]
mask[ypos, 0:to_fill] = 1
if rotate:
mask = np.rot90(mask, 3)
image = Image.fromarray((mask * 255.0).astype("uint8"))
return image
def seam_mask(
i1: PILImageType,
i2: PILImageType,
rotate: bool,
blur_size: int,
search_size: int = 1,
blend_mode: BLEND_MODES = "seam-grad",
) -> PILImageType:
seam = get_seam_line(i1, i2, rotate, blur_size + 1, search_size=search_size, blend_mode=blend_mode)
# blur = ImageFilter.GaussianBlur(float(blur_size))
blur = ImageFilter.BoxBlur(float(blur_size))
mask = seam.filter(blur)
mask = ImageOps.invert(mask)
return mask
def csv_line_to_list(csv_string: str) -> list[str]:
"""Converts the first line of a CSV into a list of strings"""
with io.StringIO(csv_string) as input:
reader = csv.reader(input)
return next(reader)
@invocation(
"main_model_loader_input",
title="Main Model Input",
tags=["model"],
category="model",
version="1.1.0",
)
class MainModelLoaderInputInvocation(MainModelLoaderInvocation):
"""Loads a main model from an input, outputting its submodels."""
model: ModelIdentifierField = InputField(description=FieldDescriptions.main_model, ui_type=UIType.MainModel)
def invoke(self, context: InvocationContext) -> ModelLoaderOutput:
return super().invoke(context)
@invocation(
"sdxl_model_loader_input",
title="SDXL Main Model Input",
tags=["model", "sdxl"],
category="model",
version="1.1.0",
)
class SDXLModelLoaderInputInvocation(SDXLModelLoaderInvocation):
"""Loads a sdxl model from an input, outputting its submodels."""
model: ModelIdentifierField = InputField(description=FieldDescriptions.main_model, ui_type=UIType.SDXLMainModel)
def invoke(self, context: InvocationContext) -> SDXLModelLoaderOutput:
return super().invoke(context)
@invocation_output("string_to_model_output")
class StringToModelOutput(BaseInvocationOutput):
"""String to SDXL model output"""
model: ModelIdentifierField = OutputField(description=FieldDescriptions.main_model, title="Model")
name: str = OutputField(description="Model Name", title="Name")
@invocation(
"string_to_main_model",
title="String To Main Model",
tags=["model"],
category="model",
version="1.1.0",
)
class StringToMainModelInvocation(BaseInvocation):
"""Loads a main model from a json string, outputting its submodels."""
model_string: str = InputField(description="string containing a Model to convert")
def invoke(self, context: InvocationContext) -> StringToModelOutput:
model = ModelIdentifierField.model_validate_json(self.model_string)
return StringToModelOutput(model=model, name=f"{model.base}: {model.name}")
@invocation_output("string_to_sdxl_model_output")
class StringToSDXLModelOutput(BaseInvocationOutput):
"""String to SDXL main model output"""
model: ModelIdentifierField = OutputField(
description=FieldDescriptions.main_model, title="Model", ui_type=UIType.SDXLMainModel
)
name: str = OutputField(description="Model Name", title="Name")
@invocation(
"string_to_sdxl_model",
title="String To SDXL Main Model",
tags=["model", "sdxl"],
category="model",
version="1.1.0",
)
class StringToSDXLModelInvocation(BaseInvocation):
"""Loads a SDXL model from a json string, outputting its submodels."""
model_string: str = InputField(description="string containing a Model to convert")
def invoke(self, context: InvocationContext) -> StringToSDXLModelOutput:
model = ModelIdentifierField.model_validate_json(self.model_string)
return StringToSDXLModelOutput(model=model, name=f"{model.base}: {model.name}")
@invocation(
"main_model_to_string",
title="Main Model To String",
tags=["model", "picker"],
category="model",
version="1.1.0",
)
class MainModelToStringInvocation(BaseInvocation):
"""Converts a Main Model to a JSONString"""
model: ModelIdentifierField = InputField(description=FieldDescriptions.main_model, ui_type=UIType.MainModel)
def invoke(self, context: InvocationContext) -> StringOutput:
return StringOutput(value=self.model.model_dump_json())
@invocation(
"sdxl_model_to_string",
title="SDXL Model To String",
tags=["model", "sdxl"],
category="model",
version="1.1.0",
)
class SDXLModelToStringInvocation(BaseInvocation):
"""Converts an SDXL Model to a JSONString"""
model: ModelIdentifierField = InputField(
description=FieldDescriptions.sdxl_main_model, ui_type=UIType.SDXLMainModel
)
def invoke(self, context: InvocationContext) -> StringOutput:
return StringOutput(value=self.model.model_dump_json())
@invocation(
"scheduler_to_string",
title="Scheduler To String",
tags=["scheduler"],
category="model",
version="1.0.1",
)
class SchedulerToStringInvocation(BaseInvocation):
"""Converts a Scheduler to a string"""
scheduler: SCHEDULER_NAME_VALUES = InputField(
default="euler",
description=FieldDescriptions.scheduler,
ui_type=UIType.Scheduler,
)
def invoke(self, context: InvocationContext) -> StringOutput:
return StringOutput(value=self.scheduler)
@invocation(
"floats_to_strings",
title="Floats To Strings",
tags=["float", "string"],
category="util",
version="1.0.1",
)
class FloatsToStringsInvocation(BaseInvocation):
"""Converts a float or collections of floats to a collection of strings"""
floats: Union[float, list[float]] = InputField(
default=[],
description="float or collection of floats",
input=Input.Connection,
)
def invoke(self, context: InvocationContext) -> StringCollectionOutput:
return StringCollectionOutput(
collection=[str(x) for x in self.floats] if isinstance(self.floats, list) else [str(self.floats)]
)
@invocation(
"ints_to_strings",
title="Ints To Strings",
tags=["int", "string"],
category="util",
version="1.1.1",
)
class IntsToStringsInvocation(BaseInvocation):
"""Converts an integer or collection of integers to a collection of strings"""
ints: Union[int, list[int]] = InputField(
default=[],
description="int or collection of ints",
input=Input.Connection,
)
def invoke(self, context: InvocationContext) -> StringCollectionOutput:
return StringCollectionOutput(
collection=[str(x) for x in self.ints] if isinstance(self.ints, list) else [str(self.ints)]
)
@invocation(
"csv_to_strings",
title="CSV To Strings",
tags=["xy", "grid", "csv"],
category="util",
version="1.1.0",
)
class CSVToStringsInvocation(BaseInvocation):
"""Converts a CSV string to a collection of strings"""
csv_string: str = InputField(description="csv string")
def invoke(self, context: InvocationContext) -> StringCollectionOutput:
return StringCollectionOutput(collection=csv_line_to_list(self.csv_string))
@invocation(
"string_to_float",
title="String To Float",
tags=["float", "string"],
category="util",
version="1.0.1",
)
class StringToFloatInvocation(BaseInvocation):
"""Converts a string to a float"""
float_string: str = InputField(description="string containing a float to convert")
def invoke(self, context: InvocationContext) -> FloatOutput:
return FloatOutput(value=float(prep_num(self.float_string)))
@invocation(
"percent_to_float",
title="Percent To Float",
tags=["float", "percentage"],
category="string",
version="1.0.1",
)
class PercentToFloatInvocation(BaseInvocation):
"""Converts a string to a float and divides it by 100."""
text: str = InputField(
title="Text",
description="Input text",
)
def invoke(self, context: InvocationContext) -> FloatOutput:
output = float(prep_num(self.text)) / 100
return FloatOutput(value=output)
@invocation(
"string_to_int",
title="String To Int",
tags=["int"],
category="util",
version="1.0.1",
)
class StringToIntInvocation(BaseInvocation):
"""Converts a string to an integer"""
int_string: str = InputField(description="string containing an integer to convert")
def invoke(self, context: InvocationContext) -> IntegerOutput:
return IntegerOutput(value=int(prep_num(self.int_string)))
@invocation(
"string_to_scheduler",
title="String To Scheduler",
tags=["scheduler"],
category="util",
version="1.0.0",
)
class StringToSchedulerInvocation(BaseInvocation):
"""Converts a string to a scheduler"""
# ddim,ddpm,deis,lms,lms_k,pndm,heun,heun_k,euler,euler_k,euler_a,kdpm_2,kdpm_2_a,dpmpp_2s,dpmpp_2s_k,dpmpp_2m,dpmpp_2m_k,dpmpp_2m_sde,dpmpp_2m_sde_k,dpmpp_sde,dpmpp_sde_k,unipc
scheduler_string: str = InputField(description="string containing a scheduler to convert")
def invoke(self, context: InvocationContext) -> SchedulerOutput:
return SchedulerOutput(scheduler=self.scheduler_string.strip().lower())
@invocation_output("xy_collect_output")
class XYProductOutput(BaseInvocationOutput):
"""XYCProductOutput a collection that contains every combination of the input collections"""
xy_item_collection: list[str] = OutputField(description="The XY Item collection")
@invocation(
"xy_product",
title="XY Product",
tags=["xy", "grid", "collect"],
category="grid",
version="1.1.0",
)
class XYProductInvocation(BaseInvocation):
"""Takes X and Y string collections and outputs a XY Item collection with every combination of X and Y"""
x_collection: list[str] = InputField(default=[], description="The X collection")
y_collection: list[str] = InputField(default=[], description="The Y collection")
def invoke(self, context: InvocationContext) -> XYProductOutput:
combinations = list(product(self.x_collection, self.y_collection))
json_combinations = [json.dumps(list(comb)) for comb in combinations]
return XYProductOutput(xy_item_collection=json_combinations)
@invocation(
"xy_product_csv",
title="XY Product CSV",
tags=["xy", "grid", "csv"],
category="grid",
version="1.0.1",
)
class XYProductCSVInvocation(BaseInvocation):
"""Converts X and Y CSV strings to an XY Item collection with every combination of X and Y"""
x: str = InputField(description="x string", ui_component=UIComponent.Textarea)
y: str = InputField(description="y string", ui_component=UIComponent.Textarea)
def invoke(self, context: InvocationContext) -> XYProductOutput:
x_list = csv_line_to_list(self.x)
y_list = csv_line_to_list(self.y)
combinations = list(product(x_list, y_list))
json_combinations = [json.dumps(list(comb)) for comb in combinations]
return XYProductOutput(xy_item_collection=json_combinations)
@invocation_output("xy_expand_output")
class XYExpandOutput(BaseInvocationOutput):
"""Two strings that are expanded from an XY Item"""
x_item: str = OutputField(description="The X item")
y_item: str = OutputField(description="The y item")
@invocation(
"xy_expand",
title="XY Expand",
tags=["xy", "grid"],
category="grid",
version="1.0.0",
)
class XYExpandInvocation(BaseInvocation):
"""Takes an XY Item and outputs the X and Y as individual strings"""
xy_item: str = InputField(description="The XY Item")
def invoke(self, context: InvocationContext) -> XYExpandOutput:
lst = json.loads(self.xy_item)
x_item = str(lst[0]) if len(lst) > 0 else ""
y_item = str(lst[1]) if len(lst) > 1 else ""
return XYExpandOutput(x_item=x_item, y_item=y_item)
@invocation_output("xy_image_expand_output")
class XYImageExpandOutput(BaseInvocationOutput):
"""XY Image Expand Output"""
x_item: str = OutputField(description="The X item")
y_item: str = OutputField(description="The y item")
image: ImageField = OutputField(description="The Image item")
width: int = OutputField(description="The width of the image in pixels")
height: int = OutputField(description="The height of the image in pixels")
@invocation(
"xy_image_expand",
title="XYImage Expand",
tags=["xy", "grid"],
category="grid",
version="1.1.1",
)
class XYImageExpandInvocation(BaseInvocation):
"""Takes an XYImage item and outputs the XItem,YItem, Image, width & height"""
xyimage_item: str = InputField(description="The XYImage collection item")
def invoke(self, context: InvocationContext) -> XYImageExpandOutput:
lst = json.loads(self.xyimage_item)
x_item = str(lst[0]) if len(lst) > 0 else ""
y_item = str(lst[1]) if len(lst) > 1 else ""
image_name = str(lst[2]) if len(lst) > 2 else ""
image = context.images.get_pil(image_name)
return XYImageExpandOutput(
x_item=x_item,
y_item=y_item,
image=ImageField(image_name=image_name),
width=image.width,
height=image.height,
)
@invocation(
"xy_image_collect",
title="XYImage Collect",
tags=["xy", "grid", "image"],
category="grid",
version="1.0.0",
)
class XYImageCollectInvocation(BaseInvocation):
"""Takes xItem, yItem and an Image and outputs it as an XYImage Item (x_item,y_item,image_name)array converted to json"""
x_item: str = InputField(description="The X item")
y_item: str = InputField(description="The Y item")
image: ImageField = InputField(description="The image to turn into grids")
def invoke(self, context: InvocationContext) -> StringOutput:
return StringOutput(value=json.dumps([self.x_item, self.y_item, self.image.image_name]))
@invocation(
"xy_images_to_grid",
title="XYImages To Grid",
tags=["xy", "grid", "image"],
category="grid",
version="1.3.1",
)
class XYImagesToGridInvocation(BaseInvocation, WithMetadata, WithBoard):
"""Takes Collection of XYImages (json of (x_item,y_item,image_name)array), sorts the images into X,Y and creates a grid image with labels"""
# board: Optional[BoardField] = InputField(default=None, description=FieldDescriptions.board, input=Input.Direct)
xyimages: list[str] = InputField(
default=[],
description="The XYImage item Collection",
)
scale_factor: float = InputField(
default=1.0,
gt=0,
description="The factor by which to scale the images",
)
resample_mode: PIL_RESAMPLING_MODES = InputField(
default="bicubic",
description="The resampling mode",
)
left_label_width: int = InputField(
default=100,
description="Width of the left label area",
)
label_font_size: int = InputField(
default=16,
description="Size of the font to use for labels",
)
def invoke(self, context: InvocationContext) -> ImageOutput:
left_label_width = self.left_label_width
new_array = [json.loads(s) for s in self.xyimages]
sorted_array = sort_array2(new_array)
images = [context.images.get_pil(item[2]) for item in sorted_array]
x_labels = sort_array(list({item[0] for item in sorted_array}))
y_labels = sort_array(list({item[1] for item in sorted_array}))
columns = len(x_labels)
rows = len(y_labels)
column_width = int(max([image.width for image in images]) * self.scale_factor)
row_height = int(max([image.height for image in images]) * self.scale_factor)
resample_mode = PIL_RESAMPLING_MAP[self.resample_mode]
import invokeai.assets.fonts.inter as fp
font_path = os.path.join(fp.__path__[0], "Inter-Regular.ttf")
assert os.path.exists(font_path), f"Font file not found: {font_path}"
font = ImageFont.truetype(font_path, self.label_font_size)
# Wrap labels
x_labels_max_chars = int(column_width // (self.label_font_size * 0.6))
y_labels_max_chars = int(left_label_width // (self.label_font_size * 0.6))
x_labels_wrapped = [textwrap.wrap(x.rstrip(), x_labels_max_chars) for x in x_labels]
y_labels_wrapped = [textwrap.wrap(y.rstrip(), y_labels_max_chars) for y in y_labels]
# Calculate x_label_height based on the number of lines they are wrapped to
font_height = sum(font.getmetrics())
max_lines = max(len(label) for label in x_labels_wrapped)
top_label_height = (max_lines * font_height) + 5
# Calculate output image size
output_width = column_width * columns + left_label_width
output_height = row_height * rows + top_label_height
# create output image and draw object
output_image = Image.new("RGBA", (output_width, output_height), (255, 255, 255))
draw = ImageDraw.Draw(output_image)
# Draw images and labels into output_image
y = top_label_height
for iy in range(rows):
iy_off = iy * columns
x = left_label_width
for ix in range(columns):
image = images[iy_off + ix]
if not self.scale_factor == 1.0:
image = image.resize(
(
int(image.width * self.scale_factor),
int(image.height * self.scale_factor),
),
resample=resample_mode,
)
output_image.paste(image, (x, y))
# Add x label on the top row
if iy == 0:
w, h = draw.multiline_textbbox((0, 0), "\n".join(x_labels_wrapped[ix]), font=font)[2:4]
draw.text(
(x + ((column_width - w) / 2), 0),
"\n".join(x_labels_wrapped[ix]),
fill="black",
font=font,
)
# Add y label on the first column
if ix == 0:
w, h = draw.multiline_textbbox((0, 0), "\n".join(y_labels_wrapped[iy]), font=font)[2:4]
draw.text(
(((left_label_width - w) / 2), y + ((row_height - h) / 2)),
"\n".join(y_labels_wrapped[iy]),
fill="black",
font=font,
)
x += column_width
y += row_height
image_dto = context.images.save(output_image)
return ImageOutput.build(image_dto)
@invocation(
"images_to_grids",
title="Images To Grids",
tags=["grid", "image"],
category="grid",
version="1.3.0",
)
class ImagesToGridsInvocation(BaseInvocation, WithMetadata, WithBoard):
"""Takes a collection of images and outputs a collection of generated grid images"""
# board: Optional[BoardField] = InputField(default=None, description=FieldDescriptions.board, input=Input.Direct)
images: list[ImageField] = InputField(
default=[],
description="The image collection to turn into grids",
)
columns: int = InputField(
default=1,
ge=1,
description="The number of columns in each grid",
)
rows: int = InputField(
default=1,
ge=1,
description="The number of rows to have in each grid",
)
space: int = InputField(
default=1,
ge=0,
description="The space to be added between images",
)
scale_factor: float = InputField(
default=1.0,
gt=0,
description="The factor by which to scale the images",
)
resample_mode: PIL_RESAMPLING_MODES = InputField(
default="bicubic",
description="The resampling mode",
)
background_color: ColorField = InputField(
default=ColorField(r=0, g=0, b=0, a=255),
description="The color to use as the background",
)
def invoke(self, context: InvocationContext) -> ImageCollectionOutput:
"""Convert an image list into a grids of images"""
images = [context.images.get_pil(image.image_name) for image in self.images]
column_width = int(max([image.width for image in images]) * self.scale_factor)
row_height = int(max([image.height for image in images]) * self.scale_factor)
output_width = column_width * self.columns + (self.space * (self.columns - 1))
output_height = row_height * self.rows + (self.space * (self.rows - 1))
resample_mode = PIL_RESAMPLING_MAP[self.resample_mode]
column = 0
row = 0
x_offset = 0
y_offset = 0
output_image = Image.new("RGBA", (output_width, output_height), self.background_color.tuple())
grid_images: list[ImageField] = []
for image in images:
if not self.scale_factor == 1.0:
image = image.resize(
(
int(image.width * self.scale_factor),
int(image.width * self.scale_factor),
),
resample=resample_mode,
)
output_image.paste(image, (x_offset, y_offset))
column += 1
x_offset += column_width + self.space
if column >= self.columns:
column = 0
x_offset = 0
y_offset += row_height + self.space
row += 1
if row >= self.rows:
row = 0
y_offset = 0
image_dto = context.images.save(output_image)
grid_images.append(ImageField(image_name=image_dto.image_name))
output_image = Image.new(
"RGBA",
(output_width, output_height),
self.background_color.tuple(),
)
# if we are not on column and row 0 then we have a part done grid and need to save it
if column > 0 or row > 0:
image_dto = context.images.save(output_image)
grid_images.append(ImageField(image_name=image_dto.image_name))
return ImageCollectionOutput(collection=grid_images)
@invocation(
"image_to_xy_image_collection",
title="Image To XYImage Collection",
tags=["xy", "grid", "image"],
category="grid",
version="1.1.1",
)
class ImageToXYImageCollectionInvocation(BaseInvocation, WithMetadata):
"""Cuts an image up into columns and rows and outputs XYImage Collection"""
# Inputs
image: ImageField = InputField(description="The input image")
columns: int = InputField(default=2, ge=2, le=256, description="The number of columns")
rows: int = InputField(default=2, ge=2, le=256, description="The number of rows")
def invoke(self, context: InvocationContext) -> StringCollectionOutput:
img = context.images.get_pil(self.image.image_name)
dy = img.height // self.rows
dx = img.width // self.columns
xyimages: list[str] = []
for iy in range(self.rows):
for ix in range(self.columns):
x = ix * dx
y = iy * dy
box = (x, y, x + dx, y + dy)
img_crop = img.crop(box)
image_dto = context.images.save(img_crop)
xyimages.append(json.dumps([str(x), str(y), image_dto.image_name]))
return StringCollectionOutput(collection=xyimages)
@invocation_output("tiles_output")
class TilesOutput(BaseInvocationOutput):
"""Tiles Output"""
tiles: list[str] = OutputField(description="Tiles Collection")
@invocation(
"default_xy_tile_generator",
title="Default XYImage Tile Generator",
tags=["xy", "tile"],
category="tile",
version="1.1.1",
)
class DefaultXYTileGenerator(BaseInvocation):
"""Cuts up an image into overlapping tiles and outputs a string representation of the tiles to use"""
# Inputs
image: ImageField = InputField(description="The input image")
tile_width: int = InputField(
default=576,
ge=1,
multiple_of=_downsampling_factor,
description="x resolution of generation tile (must be a multiple of 8)",
)
tile_height: int = InputField(
default=576,
ge=1,
multiple_of=_downsampling_factor,
description="y resolution of generation tile (must be a multiple of 8)",
)
overlap: int = InputField(
default=128,
ge=0,
multiple_of=_downsampling_factor,
description="tile overlap size (must be a multiple of 8)",
)
adjust_tile_size: bool = InputField(
default=True,
description="adjust tile size to account for overlap",
)
def invoke(self, context: InvocationContext) -> TilesOutput:
img = context.images.get_pil(self.image.image_name)
if self.adjust_tile_size:
tiles_x = img.width // self.tile_width
tiles_y = img.height // self.tile_height
self.tile_width = (img.width + self.overlap * (tiles_x - 1)) // tiles_x
self.tile_height = (img.height + self.overlap * (tiles_y - 1)) // tiles_y
if img.width < self.tile_width:
self.tile_width = img.width
if img.height < self.tile_height:
self.tile_height = img.height
dx = self.tile_width - self.overlap
dy = self.tile_height - self.overlap
x_tiles = math.ceil(((img.width - self.overlap) / dx))
y_tiles = math.ceil(((img.height - self.overlap) / dy))
xytiles: list[str] = []
xytiles.append(json.dumps(str(self.image.image_name)))
for iy in range(y_tiles):
y1 = iy * dy
y2 = y1 + self.tile_height
if y1 > img.height:
break # avoid exceeding limits
# if block exceed height then make it a full block starting at the bottom
if y2 > img.height:
y1 = img.height - self.tile_height
y2 = img.height
for ix in range(x_tiles):
x1 = ix * dx
x2 = x1 + self.tile_width
if x1 > img.width:
break # avoid exceeding limits
# if block exceeds width then make it a full block starting at the right
if x2 > img.width:
x1 = img.width - self.tile_width
x2 = img.width
xytiles.append(json.dumps([str(x1), str(y1), str(x2), str(y2)]))
return TilesOutput(tiles=xytiles)
@invocation(
"minimum_overlap_xy_tile_generator",
title="Minimum Overlap XYImage Tile Generator",
tags=["xy", "tile"],
category="tile",
version="1.1.1",
)
class MinimumOverlapXYTileGenerator(BaseInvocation):