-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpixelsort.py
1503 lines (1346 loc) · 51.5 KB
/
pixelsort.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
# -*- coding: utf-8 -*-
import argparse
import random as rand
import socket
from colorsys import rgb_to_hsv
from datetime import datetime
from json import dumps, loads
from os import name, path, remove, system
from string import ascii_lowercase, ascii_uppercase, digits
from subprocess import run
from urllib.parse import urlparse
def HasInternet(host="1.1.1.1", port=53, timeout=3):
r"""
Checks for internet.
------
:param host: 1.1.1.1 (Cloudfare public DNS)
:param port: 53
:param timeout: 3
Service: domain (DNS/TCP)
Example
------
>>> internet = HasInternet("1.1.1.1", 53, 3)
>>> internet
>>> True
"""
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
return True
except OSError:
return False
try:
from numpy import array, mgrid
from numpy.random import choice, shuffle
from PIL import Image, ImageFilter
from requests import get, post, request, put, ConnectionError
from tqdm import tqdm, trange
except ImportError:
if HasInternet():
# Upgrade/Install all packages
print("No required packages found, installing remaining ones now!")
run(
[
"pip",
"install",
"pillow",
"numpy",
"tqdm",
"requests",
"--upgrade",
]
)
from numpy import array, mgrid
from numpy.random import choice, shuffle
from PIL import Image, ImageFilter
from requests import get, post, request, put, ConnectionError
from tqdm import tqdm, trange
else:
print(
"Dependecies not installed! Unable to install any automatically, script is unable to function without them."
)
exit()
BlackPixel = (0, 0, 0, 255)
WhitePixel = (255, 255, 255, 255)
# SORTING PIXELS #
lightness = lambda p: rgb_to_hsv(p[0], p[1], p[2])[2] / 255.0
intensity = lambda p: p[0] + p[1] + p[2]
hue = lambda p: rgb_to_hsv(p[0], p[1], p[2])[0] / 255.0
saturation = lambda p: rgb_to_hsv(p[0], p[1], p[2])[1] / 255.0
minimum = lambda p: min(p[0], p[1], p[2])
# LAMBDA FUNCTIONS #
RemoveOld = lambda f: remove(f) if path.exists(f) else None
Append = lambda l, obj: l.append(obj)
AppendPIL = lambda l, x, y, d: l[y].append(d[x, y])
Append3D = lambda l, x, y, d: l.append(d[y][x])
AppendInPlace = lambda l, y, x: l[y].append(x)
RandomWidth = lambda c: (c * (1 - rand.random()))
ImgPixels = lambda i, x, y, d: i.putpixel((x, y), d[y][x])
IDGen = lambda length: "".join(
rand.choice(ascii_lowercase + ascii_uppercase + digits) for _ in range(length)
)
ProgressBars = lambda r, desc: trange(r, desc=("{:30}".format(desc)))
AppendBW = (
lambda lst, x, y, data, thresh: AppendInPlace(lst, y, WhitePixel)
if (lightness(data[y][x]) < thresh)
else AppendInPlace(lst, y, BlackPixel)
)
# MISC FUNCTIONS #
def clear():
r"""
Clears the screen when called.
:return: OS system call to clear the screen based on os type.
"""
return system("cls" if name == "nt" else "clear")
def PixelAppend(size1, size0, data, msg):
r"""
Making a 3D array of pixel values from a PIL image.
-----
:param size1: img.size[1]/height
:param size0: img.size[0]/width
:param data: PixelAccess object from img.load()
:param msg: Message for the progress bar
:returns: 3D array of pixel values.
Example
-----
>>> pixels = PixelAppend(size1, size0, data, "Appending")
"""
pixels = []
for y in ProgressBars(size1, msg):
Append(pixels, [])
for x in range(size0):
AppendPIL(pixels, x, y, data)
return pixels
def ElementaryCA(pixels, args, width, height):
r"""
Generate images of elementary cellular automata.
Selected rules from https://en.wikipedia.org/wiki/Elementary_cellular_automaton
------
:param pixels: 2D list of RGB values.
:param args: namespace of arguments.
:param width: used for image size.
:param height: used for image size.
:returns: PIL Image object.
"""
width /= 4 if width <= 2500 else 8
height /= 4 if height <= 2500 else 8
if args["filelink"] in ["False", ""]:
rules = [26, 19, 23, 25, 35, 106, 11, 110, 45, 41, 105, 54, 3, 15, 9, 154, 142]
if args["presetname"] not in ["Snap", "Random"]:
ruleprompt = input(
f"Rule selection (max of 255)(leave blank for random)\n"
f"(Recommended to leave blank, most of the rules aren't good): "
)
try:
if int(ruleprompt) in range(255):
rulenumber = int(ruleprompt)
else:
print("Number not in range, using random rule.")
rulenumber = rules[rand.randrange(0, len(rules))]
except ValueError:
rulenumber = rules[rand.randrange(0, len(rules))]
else:
rulenumber = rules[rand.randrange(0, len(rules))]
scalefactor = 1
# Define colors of the output image
true_pixel = (255, 255, 255)
false_pixel = (0, 0, 0)
# Generates a dictionary that tells you what your state should be based on the rule number
# and the states of the adjacent cells in the previous generation
def generate_rule(rulenumber) -> dict:
rule = {}
for left in [False, True]:
for middle in [False, True]:
for right in [False, True]:
rule[(left, middle, right)] = rulenumber % 2 == 1
rulenumber //= 2
return rule
# Generates a 2d representation of the state of the automaton at each generation
def generate_ca(rule):
ca = []
# Initialize the first row of ca randomly
Append(ca, [])
for x in range(int(width)):
AppendInPlace(ca, 0, bool(rand.getrandbits(1)))
# Generate the succeeding generation
# Cells at the eges are initialized randomly
for y in range(1, int(height)):
Append(ca, [])
AppendInPlace(ca, y, bool(rand.getrandbits(1)))
for x in range(1, int(width) - 1):
AppendInPlace(
ca,
y,
(rule[(ca[y - 1][x - 1], ca[y - 1][x], ca[y - 1][x + 1])]),
)
AppendInPlace(ca, y, bool(rand.getrandbits(1)))
return ca
rule = generate_rule(rulenumber)
ca = generate_ca(rule)
newImg = Image.new("RGB", [int(width), int(height)])
print(f"Creating file image..\nRule: {rulenumber}")
for y in ProgressBars(int(height), "Placing pixels..."):
for x in range(int(width)):
newImg.putpixel(
(x, y),
true_pixel
if ca[int(y / scalefactor)][int(x / scalefactor)]
else false_pixel,
)
print("File image created!")
newImg.save("images/ElementaryCA.png")
return newImg
else:
print("Using file image from DB...")
img = ImgOpen(args["filelink"], args["internet"])
img.save("images/ElementaryCA.png")
return img
def UploadImg(img):
r"""
Upload an image to put.re/imgur
This section is currently completely unused but still left in place as it might one day get used again.
-----
:param img: A string of a local file.
:returns: String of link of the uploaded file.
Example
-----
>>> link = UploadImg("https://i.redd.it/ufj4p5zwf9v21.jpg")
>>> link
>>> "https://s.put.re/Uc2A2Z7t.jpg"
(those links are actually correct.)
"""
try:
r = post("https://api.put.re/upload", files={"file": (img, open(img, "rb"))})
print(r.text)
output = loads(r.text)
link = output["data"]["link"]
return link, True
except FileNotFoundError:
print(f"{'---'*15}\n'{img}' not usable!\n{'---'*15}")
return "", False
def CheckUrl(inputStr):
r"""
Performs a very rough check if the file exists as a path or if it is a URL
------
:param inputStr: the input string, file path or url
:returns: true if the file path exists, false if it does not.
"""
if path.exists(inputStr):
return True
else:
return False
def ImgOpen(url, internet):
r"""
Opens the image from a direct url if the internet is connected.
------
:param url: The URL of a direct image.
:param internet: a bool if the internet is connected.
:returns: Callable 'Image' object from Pillow.
Example
-----
>>> img = ImgOpen(url, internet)
>>> img
>>> <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=2560x1974 at 0x29C74D7A518>
"""
isUrl = CheckUrl(url)
if not isUrl:
try:
img = Image.open((get(url, stream=True).raw) if internet else url).convert(
"RGBA"
)
return img
except OSError:
print(
f"{'---'*15}\nURL '{url}' not usable!\nPlease find the direct image url to use this script!\n{'---'*15}"
)
exit()
else:
img = Image.open(url).convert("RGBA")
return img
def CropTo(image_to_crop, args):
r"""
Crops image to the size of a reference image. This function assumes
that the relevant image is located in the center and you want to crop away
equal sizes on both the left and right as well on both the top and bottom.
:param image_to_crop
:param reference_image
:return: image cropped to the size of the reference image
"""
reference_image = ImgOpen(args["url"], args["internet"])
reference_size = reference_image.size
current_size = image_to_crop.size
dx = current_size[0] - reference_size[0]
dy = current_size[1] - reference_size[1]
left = dx / 2
upper = dy / 2
right = dx / 2 + reference_size[0]
lower = dy / 2 + reference_size[1]
return image_to_crop.crop(box=(int(left), int(upper), int(right), int(lower)))
def ArgParsing():
"""
This function is purely because it is hard to minimize every arg in the main function and it reduces the complexity of the main function.
"""
# arg parsing arguments
parse = argparse.ArgumentParser(description="pixel mangle an image")
parse_util = argparse.ArgumentParser(description="misc. args used in program")
"""
(Taken args)
//user read//
:-t,--bottom_threshold -> bottom/lower threshold
:-u,--upper_threshold -> top/upper threshold
:-c,--clength -> character length
:-a,--angle -> angle for rotation
:-r,--randomness -> randomness
//not accessible to user//
:-l,--url -> url
:-i,--int_function -> interval function
:-s,--sorting_function -> sorting function
:-p --preset -> is preset used
:-d --dbpreset -> is dbpreset used
:-y --internet -> is internet there
:-k --filelink -> for DBpreset
:-b --presetname -> name of preset used
"""
parse.add_argument(
"-t",
"--bottom_threshold",
type=float,
help="Pixels darker than this are not sorted, between 0 and 1",
default=0.25,
)
parse.add_argument(
"-u",
"--upper_threshold",
type=float,
help="Pixels darker than this are not sorted, between 0 and 1",
default=0.8,
)
parse.add_argument(
"-c",
"--clength",
type=int,
help="Characteristic length of random intervals",
default=50,
)
parse.add_argument(
"-a",
"--angle",
type=float,
help="Rotate the image by an angle (in degrees) before sorting",
default=0,
)
parse.add_argument(
"-r",
"--randomness",
type=float,
help="What percentage of intervals are NOT sorted",
default=10,
)
parse_util.add_argument(
"-l",
"--url",
help="URL of a given image. Used as the input image.",
default="https://s.put.re/QsUQbC1R.jpg",
)
parse_util.add_argument(
"-i",
"--int_function",
help="random, threshold, edges, waves, snap, shuffle-total, shuffle-axis, file, file-edges, none",
default="random",
)
parse_util.add_argument(
"-s",
"--sorting_function",
help="lightness, intensity, hue, saturation, minimum",
default="lightness",
)
parse_util.add_argument(
"-p",
"--preset",
type=bool,
help="Is a preset used or not? Boolean.",
default=False,
)
parse_util.add_argument(
"-d",
"--dbpreset",
help="Boolean for if preset is used or not.",
type=bool,
default=False,
)
parse_util.add_argument(
"-y",
"--internet",
help="Boolean for if internet is preset or not.",
type=bool,
default=True,
)
parse_util.add_argument(
"-b", "--presetname", help="Name of the preset used.", default="None"
)
parse_util.add_argument(
"-k", "--filelink", help="File image used, only in DB preset mode.", default=""
)
return parse, parse_util
# READING FUNCTIONS #
def ReadImageInput(url_input, misc_variables, internet=HasInternet()):
r"""
Reading the image input.
-----
:param url_input: The inputted URL, number of default image, or local file path.
:param internet: true/false for having internet.
:returns: (in order) url[str], url_given[bool], url_random[bool], random_url[str]
Explination on returns:
- url -> the url or local image string.
- url_given -> was the url given? or randomized?
- url_random -> was the url randomized or chosen from preset images?
- random_url -> if the url was randomly chose, the string of what number was chosen
"""
print("Opening image...")
url_options = {
"0": "https://s.put.re/SRcqAfhP.jpg",
"1": "https://s.put.re/Ds9KV8jX.jpg",
"2": "https://s.put.re/QsUQbC1R.jpg",
"3": "https://s.put.re/5zgcV3TT.jpg",
"4": "https://s.put.re/567w8wpK.jpg",
"5": "https://s.put.re/gcYkpmbd.jpg",
"6": "https://s.put.re/K49iqXVJ.png",
}
random_url = str(rand.randint(0, len(url_options)))
img_parse = urlparse(url_input)
try:
assert url_input not in ["0", "1", "2", "3", "4", "5", "6"]
if internet and url_input not in ["", " "]:
if img_parse.scheme not in ["http", "https"]:
print("Local image detected! Uploading to put.re...")
url_input, misc_variables["image_upload_failed"] = UploadImg(url_input)
return url_input, True, False, random_url
ImgOpen(url_input, internet)
return url_input, True, False, None
else:
if url_input in ["", " "]:
print("Using included default image")
url = "images/default.jpg"
else:
url = url_input
return url, True, False, False
except (IOError, AssertionError):
try:
return (
(
url_options[
(
url_input
if url_input in ["0", "1", "2", "3", "4", "5", "6"]
else random_url
)
]
if url_input in ["", " ", "0", "1", "2", "3", "4", "5", "6"]
else url_input
),
(
False
if url_input in ["", " ", "0", "1", "2", "3", "4", "5", "6"]
else True
),
(True if url_input in ["", " "] else False),
(random_url if url_input in ["", " "] else None),
)
except KeyError:
return url_options[random_url], False, True, random_url
def ReadIntervalFunction(int_func_input):
r"""
Reading the interval function.
-----
:param int_func_input: A (lowercase) string.
:returns: Interval function.
:raises KeyError: String not in selection.
Example
-----
>>> interval = ReadIntervalFunction("random")
>>> interval
>>> function<random>
"""
try:
return {
"random": random,
"threshold": threshold,
"edges": edge,
"waves": waves,
"snap": snap_sort,
"file": file_mask,
"file-edges": file_edges,
"shuffle-total": shuffle_total,
"shuffle-axis": shuffled_axis,
"none": none,
}[int_func_input]
except KeyError:
return random
def ReadSortingFunction(sort_func_input):
r"""
Reading the sorting function.
-----
:param sort_func_input: A (lowercase) string.
:returns: Sorting function.
:raises KeyError: String not in selection.
Example
-----
>>> sortFunc = ReadSortingFunction("hue")
>>> sortFunc
>>> lambda<hue>
"""
try:
return {
"lightness": lightness,
"hue": hue,
"intensity": intensity,
"minimum": minimum,
"saturation": saturation,
}[sort_func_input]
except KeyError:
return lightness
def ReadPreset(preset_input, width, presets):
r"""
Returning values for 'presets'.
-----
:param preset_input: A (lowercase) string.
:param width: the input img width, used for size reference
:returns: (in order) arg_parse_input, int_func_input, sort_func_input, preset_true, int_rand, sort_rand, int_chosen, sort_chosen, shuffled, snapped, file_sorted, db_preset, db_file_img
:raises KeyError: String not in selection.
Explination of returns
-----
- arg_parse_input -> what the arg parse input is
- int_func_input -> what the chosen interval function is
- sort_func_input -> what the sorting function is
- preset_true -> is the preset true
- int_rand -> was the interval function chosen at random?
- sort_rand -> was the sorting function chosen at random?
- int_chosen -> was the interval function chosen chosen?
- sort_chosen -> was the sorting function chosen?
- shuffled -> is the interval function shuffled?
- snapped -> is the interval function snapped?
- file_sorted -> is the interval function file?
- db_preset -> is the preset gathered from the database?
- db_file_img -> if the preset is from the database, the file image link
"""
try:
# order-- arg_parse_input, int_func_input, sort_func_input, preset_true, int_rand, sort_rand, int_chosen, sort_chosen, shuffled, snapped, file_sorted, db_preset, db_file_img
if HasInternet():
r = get(
"https://pixelsorting-a289.restdb.io/rest/outputs",
headers={
"Content-Type": "application/json",
"x-apikey": "acc71784a255a80c2fd25e081890a1767edaf",
},
)
for data in r.json():
try:
if preset_input in data["preset_id"]:
return (
data["args"],
data["int_func"],
data["sort_func"],
True,
False,
False,
True,
True,
(
True
if data["int_func"] in ["shuffle-total", "shuffle-axis"]
else False
),
(True if data["int_func"] in ["snap"] else False),
(
True
if data["int_func"] in ["file", "file-edges"]
else False
),
True,
data["file_link"],
)
except KeyError:
continue
print(presets[preset_input][1])
return presets[preset_input][1]
except KeyError:
print("[WARNING] Invalid preset name, no preset will be applied")
return (
"",
"",
"",
False,
False,
False,
False,
False,
False,
False,
False,
False,
"",
)
# SORTER #
def SortImage(pixels, intervals, args, sorting_function):
r"""
Sorts the image.
-----
:param pixels of pixel values.
:param intervals of pixel values after being run through selected interval function.
:param args: Arguments.
:param sorting_function: Sorting function used in sorting of pixels.
:returns of sorted pixels.
"""
sorted_pixels = []
sort_interval = lambda lst, func: [] if lst == [] else sorted(lst, key=func)
for y in ProgressBars(len(pixels), "Sorting..."):
row = []
x_min = 0
for x_max in intervals[y]:
interval = []
for x in range(int(x_min), int(x_max)):
Append3D(interval, x, y, pixels)
if rand.randint(0, 100) >= args["randomness"]:
row += sort_interval(interval, sorting_function)
else:
row += interval
x_min = x_max
Append3D(row, 0, y, pixels)
Append(sorted_pixels, row)
return sorted_pixels
# INTERVALS #
def edge(pixels, args):
edge_data = (
ImgOpen(args["url"], args["internet"])
.rotate(args["angle"], expand=True)
.filter(ImageFilter.FIND_EDGES)
.convert("RGBA")
.load()
)
filter_pixels = PixelAppend(
len(pixels), len(pixels[0]), edge_data, "Finding threshold..."
)
edge_pixels = []
intervals = []
for y in ProgressBars(len(pixels), "Thresholding..."):
Append(edge_pixels, [])
for x in range(len(pixels[0])):
AppendBW(edge_pixels, x, y, filter_pixels, args["bottom_threshold"])
for y in tqdm(
range(len(pixels) - 1, 1, -1), desc=("{:30}".format("Cleaning up..."))
):
for x in range(len(pixels[0]) - 1, 1, -1):
if edge_pixels[y][x] == BlackPixel and edge_pixels[y][x - 1] == BlackPixel:
edge_pixels[y][x] = WhitePixel
for y in ProgressBars(len(pixels), "Defining intervals..."):
Append(intervals, [])
for x in range(len(pixels[0])):
if edge_pixels[y][x] == BlackPixel:
AppendInPlace(intervals, y, x)
AppendInPlace(intervals, y, len(pixels[0]))
return intervals
def threshold(pixels, args):
intervals = []
for y in ProgressBars(len(pixels), "Determining intervals..."):
Append(intervals, [])
for x in range(len(pixels[0])):
if (
lightness(pixels[y][x]) < args["bottom_threshold"]
or lightness(pixels[y][x]) > args["upper_threshold"]
):
AppendInPlace(intervals, y, x)
AppendInPlace(intervals, y, len(pixels[0]))
return intervals
def random(pixels, args):
intervals = []
for y in ProgressBars(len(pixels), "Determining intervals..."):
Append(intervals, [])
x = 0
while True:
width = RandomWidth(args["clength"])
x += width
if x > len(pixels[0]):
AppendInPlace(intervals, y, len(pixels[0]))
break
else:
AppendInPlace(intervals, y, x)
return intervals
def waves(pixels, args):
intervals = []
for y in ProgressBars(len(pixels), "Determining intervals..."):
Append(intervals, [])
x = 0
while True:
width = args["clength"] + rand.randint(0, 10)
x += width
if x > len(pixels[0]):
AppendInPlace(intervals, y, len(pixels[0]))
break
else:
AppendInPlace(intervals, y, x)
return intervals
def file_mask(pixels, args):
img = ElementaryCA(pixels, args, int(len(pixels)), int(len(pixels[0]))).resize(
(len(pixels[0]), len(pixels)), Image.ANTIALIAS
)
data = img.load()
file_pixels = PixelAppend(len(pixels), len(pixels[0]), data, "Defining edges...")
intervals = []
for y in tqdm(
range(len(pixels) - 1, 1, -1), desc=("{:30}".format("Cleaning up edges..."))
):
for x in range(len(pixels[0]) - 1, 1, -1):
if file_pixels[y][x] == BlackPixel and file_pixels[y][x - 1] == BlackPixel:
file_pixels[y][x] = WhitePixel
for y in ProgressBars(len(pixels), "Defining intervals..."):
Append(intervals, [])
for x in range(len(pixels[0])):
if file_pixels[y][x] == BlackPixel:
AppendInPlace(intervals, y, x)
AppendInPlace(intervals, y, len(pixels[0]))
return intervals
def file_edges(pixels, args):
edge_data = (
ElementaryCA(pixels, args, int(len(pixels)), int(len(pixels[0])))
.rotate(args["angle"], expand=True)
.resize((len(pixels[0]), len(pixels)), Image.ANTIALIAS)
.filter(ImageFilter.FIND_EDGES)
.convert("RGBA")
.load()
)
filter_pixels = PixelAppend(
len(pixels), len(pixels[0]), edge_data, "Defining edges..."
)
edge_pixels = []
intervals = []
for y in ProgressBars(len(pixels), "Thresholding..."):
Append(edge_pixels, [])
for x in range(len(pixels[0])):
AppendBW(edge_pixels, x, y, filter_pixels, args["bottom_threshold"])
for y in tqdm(
range(len(pixels) - 1, 1, -1), desc=("{:30}".format("Cleaning up edges..."))
):
for x in range(len(pixels[0]) - 1, 1, -1):
if edge_pixels[y][x] == BlackPixel and edge_pixels[y][x - 1] == BlackPixel:
edge_pixels[y][x] = WhitePixel
for y in ProgressBars(len(pixels), "Defining intervals..."):
Append(intervals, [])
for x in range(len(pixels[0])):
if edge_pixels[y][x] == BlackPixel:
AppendInPlace(intervals, y, x)
AppendInPlace(intervals, y, len(pixels[0]))
return intervals
def snap_sort(pixels, args):
input_img = ImgOpen("images/thanos_img.png", False)
pixels_snap = array(input_img)
print("The hardest choices require the strongest wills...")
nx, ny = input_img.size
xy = mgrid[:nx, :ny].reshape(2, -1).T
rounded = int(round(int(xy.shape[0] / 2), 0))
numbers_that_dont_feel_so_good = xy.take(
choice(xy.shape[0], rounded, replace=False), axis=0
)
print(f'Number of those worthy of the sacrifice: {("{:,}".format(rounded))}')
for i in ProgressBars(len(numbers_that_dont_feel_so_good), "Snapping..."):
pixels_snap[numbers_that_dont_feel_so_good[i][1]][
numbers_that_dont_feel_so_good[i][0]
] = [0, 0, 0, 0]
print("Sorted perfectly in half.")
returned_souls = Image.fromarray(pixels_snap, "RGBA")
returned_souls.save("images/snapped_pixels.png")
snapped_img = ImgOpen("images/snapped_pixels.png", False)
data = snapped_img.load()
size0, size1 = snapped_img.size
pixels_return = PixelAppend(size1, size0, data, "I hope they remember you...")
RemoveOld("images/snapped_pixels.png")
RemoveOld("images/thanos_img.png")
print(f"{('/' * 45)}\nPerfectly balanced, as all things should be.\n{('/' * 45)}")
return pixels_return
def shuffle_total(pixels, args):
print("Creating array from image...")
input_img = ImgOpen(args["url"], args["internet"]).convert("RGBA")
height = input_img.size[1]
shuffled = array(input_img)
for i in ProgressBars(int(height), "Shuffling image..."):
shuffle(shuffled[i])
print("Saving shuffled image...")
shuffled_img = Image.fromarray(shuffled, "RGBA")
data = shuffled_img.load()
size0, size1 = input_img.size
pixels = PixelAppend(size1, size0, data, "Recreating image...")
RemoveOld("images/shuffled.png")
return pixels
def shuffled_axis(pixels, args):
print("Creating array from image...")
input_img = ImgOpen(args["url"], args["internet"]).convert("RGBA")
height = input_img.size[1]
shuffled = array(input_img)
for _ in ProgressBars(height, "Shuffling image..."):
shuffle(shuffled)
print("Saving shuffled image...")
shuffled_img = Image.fromarray(shuffled, "RGBA")
data = shuffled_img.load()
size0, size1 = input_img.size
pixels = PixelAppend(size1, size0, data, "Recreating image...")
RemoveOld("images/shuffled.png")
return pixels
def none(pixels, args):
intervals = []
for y in ProgressBars(len(pixels), "Determining intervals..."):
Append(intervals, [len(pixels[y])])
return intervals
# MAIN #
def main():
"""
Pixelsorting an image.
"""
parse, parse_util = ArgParsing()
clear()
# remove old image files that didn't get deleted before
RemoveOld("images/image.png")
RemoveOld("images/thanos_img.png")
RemoveOld("images/snapped_pixels.png")
RemoveOld("images/ElementaryCA.png")
# variables
misc_variables = {
"internet": HasInternet(),
"preset_true": False,
"snapped": False,
"shuffled": False,
"int_rand": False,
"sort_rand": False,
"int_chosen": False,
"sort_chosen": False,
"file_sorted": False,
"image_upload_failed": False,
"resolution_msg": "",
"image_msg": "",
"int_msg": "",
"sort_msg": "",
"site_msg": "",
"link": "",
"date_time": datetime.now().strftime("(%m%d%Y%H%M)"),
"preset_id": datetime.now().strftime("%m%d%Y%H%M"),
"sort_func_options": ["lightness", "hue", "intensity", "minimum", "saturation"],
"int_func_options": [
"random",
"threshold",
"edges",
"waves",
"snap",
"file",
"file-edges",
"none",
"shuffle-total",
"shuffle-axis",
],
}
presets = {
"Main": [
"Main args (r: 35-65, c: random gen, a: 0-360, random, intensity)",
(
(
f"-r {rand.randrange(35, 65)} "
f"-c {(rand.randrange(150, 350, 25))} "
f"-a {rand.randrange(0, 360)} "
),
"random",
"intensity",
True,
False,
False,
True,
True,
False,
False,
False,
False,
"",
),
],
"File": [
"Main args, but only for file edges",
(
(
f"-r {rand.randrange(15, 65)} "
f"-t {float(rand.randrange(65, 90)/100)}"
),
"file-edges",
"minimum",
True,
False,
False,
True,
True,
False,
False,
True,
False,
"",
),
],
"Random": [
"Randomness in every arg!",
(
(
f"-a {rand.randrange(0, 360)} "