-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainstormer.py
3507 lines (2652 loc) · 139 KB
/
brainstormer.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
# I M P O R T S
# Standard Library
import os
import io
import warnings
# Third Party
from PIL import Image, ImageDraw, ImageFont, ImageTk, ImageOps, ImageEnhance, ImageFilter
from PIL import ImageStat
from PIL import ImageGrab
import tkinter as tk
from tkinter import ttk
from stability_sdk import client
from stability_sdk import api
import stability_sdk.interfaces.gooseai.generation.generation_pb2 as generation
from stability_sdk.animation import AnimationArgs, Animator
from tqdm import tqdm
import cv2
import numpy as np
import random
import openai
from midiutil import MIDIFile
from pydub import AudioSegment
from pydub.generators import Sine
import time
import requests
from tkinter import filedialog
from tkinter import colorchooser
from tkinter import messagebox
import io
import datetime
# My Library
import words
from words import sample_words
#======================================================================================================================
#======================================================================================================================
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
#======================================================================================================================
#======================================================================================================================
# A P I K E Y S
# Set your OpenAI API key
openai.api_key = 'PUT YOUR OPENAI API KEY HERE'
# Set up environment variables
os.environ['STABILITY_HOST'] = 'grpc.stability.ai:443'
os.environ['STABILITY_KEY'] = 'PUT YOUR STABILITY AI API KEY HERE'
# Set up connection to the API
stability_api = client.StabilityInference(
key=os.environ['STABILITY_KEY'],
verbose=True,
engine="stable-diffusion-xl-beta-v2-2-2",
upscale_engine="stable-diffusion-x4-latent-upscaler", # Use x4 upscaler
)
STABILITY_HOST = "grpc.stability.ai:443"
STABILITY_KEY = "PUT YOUR STABILITY AI API KEY HERE" # Your API key from dreamstudio.ai
api_context = api.Context(STABILITY_HOST, STABILITY_KEY)
#======================================================================================================================
#======================================================================================================================
# S A V E C H A T B O T
# Function to save a specific conversation to a text file
def save_specific_conversation(tab_index):
# Ensure the directory exists
if not os.path.exists('conversations'):
os.makedirs('conversations')
conversation = conversations[tab_index]
# Use current datetime to create a unique filename
timestamp_str = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
with open(f'conversations/conversation_{tab_index}_{timestamp_str}.json', 'w') as f:
# Use json.dump to write the conversation to the file
json.dump(conversation, f)
#======================================================================================================================
#======================================================================================================================
# B U T T O N C L I C K S
# RANDOMIZER
def button_randomize_click():
text_entry.delete(0, tk.END)
random_sentence = words.generate_random_sentence()
text_entry.insert(0, random_sentence)
#======================================================================================================================
#======================================================================================================================
# D A L L E T E X T T O I M A G E
def generate_image_dalle():
prompt = text_entry.get()
# Directly use the "Create" mode
response = openai.Image.create(
prompt=prompt,
n=1,
size="512x512"
)
image_url = response['data'][0]['url']
# Download the image from the URL
img_data = requests.get(image_url).content
img = Image.open(io.BytesIO(img_data))
# Save the image
image_filename = f"{prompt}.png"
img.save(image_filename)
# Display the image in the GUI
img.thumbnail((256, 256)) # Resize the image to fit the GUI
img_tk = ImageTk.PhotoImage(img)
lbl.config(image=img_tk)
lbl.image = img_tk
#======================================================================================================================
#======================================================================================================================
# D A L L E V A R I A T I O N S
# Create a function to generate variations of the image using DALL·E
def generate_variations():
try:
global img_for_itf # Ensure that img_for_itf variable is global
image = img_for_itf # Use the uploaded image
# Convert image to bytes
image_bytes = io.BytesIO()
image.save(image_bytes, format="PNG")
response = openai.Image.create_variation(
image=image_bytes.getvalue(),
n=1, # Number of variations to generate
size="1024x1024", # Size of the generated images
response_format="url" # Format of the generated images
)
generated_image_url = response['data'][0]['url']
response = requests.get(generated_image_url)
generated_image = Image.open(io.BytesIO(response.content))
# Resize the image
resized_image = generated_image.resize((256, 256), Image.ANTIALIAS)
# Save and display the generated image
variation_filename = "{}_variation.png".format(timestamp)
resized_image.save(variation_filename)
img_tk = ImageTk.PhotoImage(resized_image)
fx_image_label.config(image=img_tk)
fx_image_label.image = img_tk
result_label.config(text="Variations generated successfully!")
except Exception as e:
result_label.config(text="Error: " + str(e))
#======================================================================================================================
#======================================================================================================================
# S T A B L E D I F F U S I O N T E X T T O I M A G E
def text_to_seed(text):
return sum([ord(c) for c in text])
def generate_image_diffusion(prompt, seed, steps):
answers = stability_api.generate(
prompt=prompt,
seed=seed,
steps=steps,
cfg_scale=8.0,
width=512,
height=512,
samples=1,
sampler=generation.SAMPLER_K_DPMPP_2M
)
return answers
def generate_image_and_save():
input_text = text_entry.get()
seed = text_to_seed(input_text)
# Get the number of steps from the steps_entry field
try:
steps = int(steps_entry.get())
except ValueError:
print("Invalid steps value. Please enter a valid integer.")
return
# Pass the steps value to the generate_image_diffusion function
answers = generate_image_diffusion(input_text, seed, steps)
for resp in answers:
for artifact in resp.artifacts:
if artifact.finish_reason == generation.FILTER:
warnings.warn(
"Your request activated the API's safety filters and could not be processed."
"Please modify the prompt and try again."
)
if artifact.type == generation.ARTIFACT_IMAGE:
img = Image.open(io.BytesIO(artifact.binary))
image_filename = f"{input_text}.png"
img.save(image_filename)
# Display the image in the GUI
img.thumbnail((256, 256)) # Resize the image to fit the GUI
img_tk = ImageTk.PhotoImage(img)
lbl.config(image=img_tk)
lbl.image = img_tk
#======================================================================================================================
#======================================================================================================================
# G P T S M A R T C H A O S
def random_chaos_single():
# Generate 1 sentence with ChatGPT
messages = [
{"role": "system", "content": "You will act as if you are a creative screenwriter."},
{"role": "user", "content": "Invent a movie scene in 1 sentence that is 15 words or less:"}
]
response = openai.ChatCompletion.create(
model="gpt-4",
messages=messages,
max_tokens=100,
temperature=1
)
sentence = response['choices'][0]['message']['content'].strip()
# Insert the sentence into the specific text field
text_entry.delete(0, tk.END)
text_entry.insert(0, sentence)
#======================================================================================================================
#======================================================================================================================
# I M A G E T O I M A G E F U N C T I O N S
def upload_image_for_itf():
global img_for_itf # Declare global variable to store the uploaded image for image-to-image function
global current_img # Declare global variable to store the current image
file_path = filedialog.askopenfilename()
img_for_itf = Image.open(file_path)
img_for_itf.thumbnail((256, 256)) # Adjust the thumbnail size to be multiples of 64
img_tk = ImageTk.PhotoImage(img_for_itf)
lbl.configure(image=img_tk)
lbl.image = img_tk
current_img = img_for_itf # Update the current image
#----------------------------------------------------------------------------------------------------------------------
# image to image parameters
def image_to_image():
global current_img # Ensure that the current_img variable is global
# Retrieve user input from the Image-to-Image prompt entry widget
image_to_image_prompt = image_to_image_entry.get()
# Use the current image as the input image
img = current_img
answers = stability_api.generate(
prompt=image_to_image_prompt, # Use the user's prompt
init_image=img,
start_schedule=0.6,
seed=123467458,
steps=30,
cfg_scale=8.0,
width=1024,
height=1024,
sampler=generation.SAMPLER_K_DPMPP_2M
)
for resp in answers:
for artifact in resp.artifacts:
if artifact.finish_reason == generation.FILTER:
warnings.warn(
"Your request activated the API's safety filters and could not be processed."
"Please modify the prompt and try again.")
if artifact.type == generation.ARTIFACT_IMAGE:
img = Image.open(io.BytesIO(artifact.binary))
img.thumbnail((256, 256)) # Resize the image to fit the GUI
img_tk = ImageTk.PhotoImage(img)
lbl.config(image=img_tk)
lbl.image = img_tk
img.save(f"./{image_to_image_prompt}_img2img.png") # Save the image in the same directory as the script
current_img = img # Update the current image
# Assuming the image_label is the label we want to display the image in
image_label.grid(row=2, column=3)
#======================================================================================================================
#======================================================================================================================
# F X A N D I M A G E E D I T I N G
# M I R R O R I M A G E
def mirror_image():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Mirror the image
img_mirrored = ImageOps.mirror(img)
# Save and display the mirrored image
mirrored_filename = f"{input_text}_mirrored.png"
img_mirrored.save(mirrored_filename)
img_mirrored.thumbnail((256, 256)) # Resize the image to fit the GUI
img_mirrored_tk = ImageTk.PhotoImage(img_mirrored)
fx_image_label.config(image=img_mirrored_tk)
fx_image_label.image = img_mirrored_tk
except Exception as e:
print("An error occurred during the image mirroring:", e)
#----------------------------------------------------------------------------------------------------------------------
# I N V E R T C O L O R S
def invert_colors():
try:
input_text = text_entry.get()
seed = text_to_seed(input_text)
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Invert the colors of the image
img_inverted = ImageOps.invert(img)
# Save and display the inverted image
inverted_filename = f"{input_text}_inverted.png"
img_inverted.save(inverted_filename)
img_inverted.thumbnail((256, 256)) # Resize the image to fit the GUI
img_inverted_tk = ImageTk.PhotoImage(img_inverted)
fx_image_label.config(image=img_inverted_tk)
fx_image_label.image = img_inverted_tk
except Exception as e:
print("An error occurred during the color inversion:", e)
#----------------------------------------------------------------------------------------------------------------------
# P I X E L A T E
def pixelate_image():
input_text = text_entry.get()
seed = text_to_seed(input_text)
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Pixelate the image
pixel_size = 5 # Define the size of the pixels
img_pixelated = img.resize(
(img.size[0] // pixel_size, img.size[1] // pixel_size),
Image.NEAREST
).resize(img.size, Image.NEAREST)
# Save and display the pixelated image
pixelated_filename = f"{input_text}_pixelated.png"
img_pixelated.save(pixelated_filename)
img_pixelated.thumbnail((256, 256)) # Resize the image to fit the GUI
img_pixelated_tk = ImageTk.PhotoImage(img_pixelated)
fx_image_label.config(image=img_pixelated_tk)
fx_image_label.image = img_pixelated_tk
#----------------------------------------------------------------------------------------------------------------------
# R E M O V E B A C K G R O U N D
def remove_background():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Convert the image to OpenCV format (BGR)
cv_img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
# Define mask, bgdModel, fgdModel
mask = np.zeros(cv_img.shape[:2], np.uint8)
bgd_model = np.zeros((1, 65), np.float64)
fgd_model = np.zeros((1, 65), np.float64)
# Define rectangle for GrabCut
rect = (50, 50, cv_img.shape[1]-100, cv_img.shape[0]-100)
# Apply GrabCut
cv2.grabCut(cv_img, mask, rect, bgd_model, fgd_model, 5, cv2.GC_INIT_WITH_RECT)
# Create binary mask where foreground is 1 and background is 0
binary_mask = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
# Multiply original image with binary mask to get result
result = cv_img * binary_mask[:, :, np.newaxis]
# Convert the result back to PIL format (RGB)
img_removed_bg = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
# Save and display the image with the background removed
removed_bg_filename = f"{input_text}_removed_bg.png"
img_removed_bg.save(removed_bg_filename)
img_removed_bg.thumbnail((256, 256)) # Resize the image to fit the GUI
img_removed_bg_tk = ImageTk.PhotoImage(img_removed_bg)
fx_image_label.config(image=img_removed_bg_tk)
fx_image_label.image = img_removed_bg_tk
except Exception as e:
print("An error occurred while removing the background:", e)
#----------------------------------------------------------------------------------------------------------------------
# G R E Y S C A L E
def greyscale_image():
try:
input_text = text_entry.get()
seed = text_to_seed(input_text)
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Convert the image to greyscale
img_greyscale = img.convert('L')
# Save and display the greyscale image
greyscale_filename = f"{input_text}_greyscale.png"
img_greyscale.save(greyscale_filename)
img_greyscale.thumbnail((256, 256)) # Resize the image to fit the GUI
img_greyscale_tk = ImageTk.PhotoImage(img_greyscale)
fx_image_label.config(image=img_greyscale_tk)
fx_image_label.image = img_greyscale_tk
except Exception as e:
print("An error occurred during the greyscale conversion:", e)
#----------------------------------------------------------------------------------------------------------------------
# S A T U R A T E
def enhance_saturation():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Enhance the saturation of the image
enhancer = ImageEnhance.Color(img)
enhanced_img = enhancer.enhance(1.5) # Increase the saturation
# Save and display the enhanced image
enhanced_filename = f"{input_text}_saturate.png"
enhanced_img.save(enhanced_filename)
enhanced_img.thumbnail((256, 256)) # Resize the image to fit the GUI
enhanced_img_tk = ImageTk.PhotoImage(enhanced_img)
fx_image_label.config(image=enhanced_img_tk)
fx_image_label.image = enhanced_img_tk
except Exception as e:
print("An error occurred during enhancing saturation:", e)
#----------------------------------------------------------------------------------------------------------------------
# S E P I A
def sepia_tone():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Convert the image to sepia tone
img_sepia = img.convert("L").convert("RGB")
sepia_data = img_sepia.load()
width, height = img_sepia.size
for y in range(height):
for x in range(width):
r, g, b = img_sepia.getpixel((x, y))
sepia_red = int(r * 0.393 + g * 0.769 + b * 0.189)
sepia_green = int(r * 0.349 + g * 0.686 + b * 0.168)
sepia_blue = int(r * 0.272 + g * 0.534 + b * 0.131)
sepia_data[x, y] = (sepia_red, sepia_green, sepia_blue)
# Save and display the sepia tone image
sepia_filename = f"{input_text}_sepia.png"
img_sepia.save(sepia_filename)
img_sepia.thumbnail((256, 256)) # Resize the image to fit the GUI
img_sepia_tk = ImageTk.PhotoImage(img_sepia)
fx_image_label.config(image=img_sepia_tk)
fx_image_label.image = img_sepia_tk
except Exception as e:
print("An error occurred during applying sepia tone:", e)
#----------------------------------------------------------------------------------------------------------------------
# B L U R
def blur_image():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Blur the image
img_blurred = img.filter(ImageFilter.BLUR)
# Save and display the blurred image
blurred_filename = f"{input_text}_blur.png"
img_blurred.save(blurred_filename)
img_blurred.thumbnail((256, 256)) # Resize the image to fit the GUI
img_blurred_tk = ImageTk.PhotoImage(img_blurred)
fx_image_label.config(image=img_blurred_tk)
fx_image_label.image = img_blurred_tk
except Exception as e:
print("An error occurred during image blurring:", e)
#----------------------------------------------------------------------------------------------------------------------
# emboss
def emboss_image():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Apply emboss filter
img_emboss = img.filter(ImageFilter.EMBOSS)
# Save and display the embossed image
emboss_filename = f"{input_text}_emboss.png"
img_emboss.save(emboss_filename)
img_emboss.thumbnail((256, 256)) # Resize the image to fit the GUI
img_emboss_tk = ImageTk.PhotoImage(img_emboss)
fx_image_label.config(image=img_emboss_tk)
fx_image_label.image = img_emboss_tk
except Exception as e:
print("An error occurred during the emboss filter:", e)
#---------------------------------------------------------------------------------------------------------------------
# solarize
def solarize_image():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Apply solarize filter
img_solarize = ImageOps.solarize(img, threshold=128)
# Save and display the solarized image
solarize_filename = f"{input_text}_solarize.png"
img_solarize.save(solarize_filename)
img_solarize.thumbnail((256, 256)) # Resize the image to fit the GUI
img_solarize_tk = ImageTk.PhotoImage(img_solarize)
fx_image_label.config(image=img_solarize_tk)
fx_image_label.image = img_solarize_tk
except Exception as e:
print("An error occurred during the solarize filter:", e)
#----------------------------------------------------------------------------------------------------------------------
# posterize
def posterize_image():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Apply posterize filter
img_posterize = ImageOps.posterize(img, bits=3) # Reduce to 4 bits
# Save and display the posterized image
posterize_filename = f"{input_text}_posterize.png"
img_posterize.save(posterize_filename)
img_posterize.thumbnail((256, 256)) # Resize the image to fit the GUI
img_posterize_tk = ImageTk.PhotoImage(img_posterize)
fx_image_label.config(image=img_posterize_tk)
fx_image_label.image = img_posterize_tk
except Exception as e:
print("An error occurred during the posterize filter:", e)
#----------------------------------------------------------------------------------------------------------------------
# sharpen
def sharpen_image():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Apply sharpen filter
img_sharpen = img.filter(ImageFilter.SHARPEN)
# Save and display the sharpened image
sharpen_filename = f"{input_text}_sharpen.png"
img_sharpen.save(sharpen_filename)
img_sharpen.thumbnail((256, 256)) # Resize the image to fit the GUI
img_sharpen_tk = ImageTk.PhotoImage(img_sharpen)
fx_image_label.config(image=img_sharpen_tk)
fx_image_label.image = img_sharpen_tk
except Exception as e:
print("An error occurred during the sharpen filter:", e)
#----------------------------------------------------------------------------------------------------------------------
# VHS Glitch Effect
def apply_vhs_glitch_effect():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Convert the image to a numpy array for manipulation
img_array = np.array(img)
# Apply VHS glitch-style effect to the image (more dramatic)
red_channel = img_array[:, :, 0]
green_channel = img_array[:, :, 1]
blue_channel = img_array[:, :, 2]
shifted_red = np.roll(red_channel, 30, axis=1)
shifted_green = np.roll(green_channel, -20, axis=0)
shifted_blue = np.roll(blue_channel, 40, axis=1)
glitched_img_array = np.stack((shifted_red, shifted_green, shifted_blue), axis=2)
glitched_img = Image.fromarray(glitched_img_array)
# Save and display the glitched image
glitched_filename = f"{input_text}_glitch.png"
glitched_img.save(glitched_filename)
glitched_img.thumbnail((256, 256)) # Resize the image to fit the GUI
glitched_img_tk = ImageTk.PhotoImage(glitched_img)
fx_image_label.config(image=glitched_img_tk)
fx_image_label.image = glitched_img_tk
except Exception as e:
print("An error occurred during applying VHS glitch effect:", e)
#----------------------------------------------------------------------------------------------------------------------
# oil painting
def apply_oil_painting_effect():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Apply the oil painting effect
img = img.filter(ImageFilter.ModeFilter(size=5)) # Increase size for larger "brush strokes"
img = img.filter(ImageFilter.MaxFilter(size=5)) # Increase size for larger "brush strokes"
# Define a convolution matrix for edge enhancement
convolution_matrix = ImageFilter.Kernel(
size=(3, 3),
kernel=[-2, -1, 0, -1, 1, 1, 0, 1, 2],
scale=sum([-2, -1, 0, -1, 1, 1, 0, 1, 2]),
)
img = img.filter(convolution_matrix)
# Apply sharpening filter multiple times
for _ in range(3):
img = img.filter(ImageFilter.SHARPEN)
# Save and display the oil painting effect image
oil_painting_filename = f"{input_text}_oil_painting.png"
img.save(oil_painting_filename)
img.thumbnail((256, 256)) # Resize the image to fit the GUI
img = ImageTk.PhotoImage(img)
fx_image_label.config(image=img)
fx_image_label.image = img
except Exception as e:
print("An error occurred during applying oil painting effect:", e)
#----------------------------------------------------------------------------------------------------------------------
# Flip Vertically
def flip_vertically():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Flip the image vertically
flipped_img = img.transpose(Image.FLIP_TOP_BOTTOM)
# Save and display the flipped image
flipped_filename = f"{input_text}_flipped.png"
flipped_img.save(flipped_filename)
flipped_img.thumbnail((256, 256)) # Resize the image to fit the GUI
flipped_img_tk = ImageTk.PhotoImage(flipped_img)
fx_image_label.config(image=flipped_img_tk)
fx_image_label.image = flipped_img_tk
except Exception as e:
print("An error occurred during flipping the image vertically:", e)
#----------------------------------------------------------------------------------------------------------------------
# Edge Detection
def edge_detection():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = Image.open(image_filename)
# Apply edge detection filter
img_edges = img.filter(ImageFilter.FIND_EDGES)
# Save and display the edge detected image
edges_filename = f"{input_text}_edges.png"
img_edges.save(edges_filename)
img_edges.thumbnail((256, 256))
img_edges_tk = ImageTk.PhotoImage(img_edges)
fx_image_label.config(image=img_edges_tk)
fx_image_label.image = img_edges_tk
except Exception as e:
print("An error occurred during edge detection:", e)
#----------------------------------------------------------------------------------------------------------------------
def mosaic():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = cv2.imread(image_filename)
# Mosaic effect
block_size = 8 # Smaller blocks for more detail
img_mosaic = img.copy()
for x in range(0, img.shape[0], block_size):
for y in range(0, img.shape[1], block_size):
img_mosaic[x:x+block_size, y:y+block_size] = np.mean(np.mean(img[x:x+block_size, y:y+block_size], axis=0), axis=0)
# Edge detection
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_edges = cv2.Canny(img_gray, 50, 150)
# Blend the mosaic and edges
alpha = 0.7 # Change this to control blending (0 = only mosaic, 1 = only edges)
img_mosaic = cv2.cvtColor(img_mosaic, cv2.COLOR_BGR2GRAY)
img_blend = cv2.addWeighted(img_mosaic, alpha, img_edges, 1-alpha, 0)
# Save and display the blended image
blend_filename = f"{input_text}_blend.png"
cv2.imwrite(blend_filename, img_blend)
img_blend = Image.open(blend_filename)
img_blend.thumbnail((256, 256)) # Resize the image to fit the GUI
img_blend_tk = ImageTk.PhotoImage(img_blend)
fx_image_label.config(image=img_blend_tk)
fx_image_label.image = img_blend_tk
except Exception as e:
print("An error occurred during creative mosaic effect:", e)
#----------------------------------------------------------------------------------------------------------------------
# Noise Reduction
def noise_reduction():
try:
# Use cv2.fastNlMeansDenoisingColored for noise reduction
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = cv2.imread(image_filename)
# Apply noise reduction
img_noise_reduced = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21)
# Save and display the noise-reduced image
noise_reduced_filename = f"{input_text}_noise_reduced.png"
cv2.imwrite(noise_reduced_filename, img_noise_reduced)
img_noise_reduced = Image.open(noise_reduced_filename)
img_noise_reduced.thumbnail((256, 256)) # Resize the image to fit the GUI
img_noise_reduced_tk = ImageTk.PhotoImage(img_noise_reduced)
fx_image_label.config(image=img_noise_reduced_tk)
fx_image_label.image = img_noise_reduced_tk
except Exception as e:
print("An error occurred during noise reduction:", e)
#----------------------------------------------------------------------------------------------------------------------
# Pencil Sketch
def pencil_sketch():
try:
# Create a pencil sketch by first converting the image to grayscale, and then applying an inversion and a binary threshold
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = cv2.imread(image_filename)
# Convert to grayscale
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply inversion
img_inverted = cv2.bitwise_not(img_gray)
# Apply binary threshold
_, img_pencil_sketch = cv2.threshold(img_inverted, 150, 255, cv2.THRESH_BINARY)
# Save and display the pencil sketch image
pencil_sketch_filename = f"{input_text}_pencil_sketch.png"
cv2.imwrite(pencil_sketch_filename, img_pencil_sketch)
img_pencil_sketch = Image.open(pencil_sketch_filename)
img_pencil_sketch.thumbnail((256, 256)) # Resize the image to fit the GUI
img_pencil_sketch_tk = ImageTk.PhotoImage(img_pencil_sketch)
fx_image_label.config(image=img_pencil_sketch_tk)
fx_image_label.image = img_pencil_sketch_tk
except Exception as e:
print("An error occurred during pencil sketch effect:", e)
#----------------------------------------------------------------------------------------------------------------------
# Cartoonize
def cartoonize():
try:
# Cartoonizing an image involves reducing the color palette and applying bilateral filter to remove noise
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = cv2.imread(image_filename)
# Reduce color palette
img_reduced_color = cv2.pyrMeanShiftFiltering(img, sp=20, sr=60)
# Convert to grayscale
img_gray = cv2.cvtColor(img_reduced_color, cv2.COLOR_BGR2GRAY)
# Apply median blur
img_blur = cv2.medianBlur(img_gray, 3)
# Use adaptive threshold to create an edge mask
img_edge = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, blockSize=9, C=2)
# Combine the color image with the edge mask to create a cartoon effect
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2BGR)
img_cartoonized = cv2.bitwise_and(img_reduced_color, img_edge)
# Save and display the cartoonized image
cartoonized_filename = f"{input_text}_cartoonized.png"
cv2.imwrite(cartoonized_filename, img_cartoonized)
img_cartoonized = Image.open(cartoonized_filename)
img_cartoonized.thumbnail((256, 256))
img_cartoonized_tk = ImageTk.PhotoImage(img_cartoonized)
fx_image_label.config(image=img_cartoonized_tk)
fx_image_label.image = img_cartoonized_tk
except Exception as e:
print("An error occurred during cartoonize:", e)
#----------------------------------------------------------------------------------------------------------------------
# Watercolor
def watercolor():
try:
# Watercolor effect can be achieved by applying a stylization filter
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = cv2.imread(image_filename)
# Apply stylization
img_stylized = cv2.stylization(img, sigma_s=60, sigma_r=0.07)
# Save and display the stylized image
watercolor_filename = f"{input_text}_watercolor.png"
cv2.imwrite(watercolor_filename, img_stylized)
img_watercolor = Image.open(watercolor_filename)
img_watercolor.thumbnail((256, 256))
img_watercolor_tk = ImageTk.PhotoImage(img_watercolor)
fx_image_label.config(image=img_watercolor_tk)
fx_image_label.image = img_watercolor_tk
except Exception as e:
print("An error occurred during watercolor effect:", e)
#----------------------------------------------------------------------------------------------------------------------
# Vignette Effect
def vignette():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = cv2.imread(image_filename)
rows, cols = img.shape[:2]
# Generate vignette mask using Gaussian kernels
kernel_x = cv2.getGaussianKernel(int(1.5*cols),200)
kernel_y = cv2.getGaussianKernel(int(1.5*rows),200)
kernel = kernel_y @ kernel_x.T
mask = kernel[int(0.5*rows):, int(0.5*cols):]
mask = cv2.resize(mask, (cols, rows))
mask = mask / mask.max()
img_vignette = np.copy(img)
# Apply the mask to each channel in the input image
for i in range(3):
img_vignette[:,:,i] = img_vignette[:,:,i] * mask
# Save and display the vignetted image
vignette_filename = f"{input_text}_vignette.png"
cv2.imwrite(vignette_filename, img_vignette)
img_vignette = Image.open(vignette_filename)
img_vignette.thumbnail((256, 256)) # Resize the image to fit the GUI
img_vignette_tk = ImageTk.PhotoImage(img_vignette)
fx_image_label.config(image=img_vignette_tk)
fx_image_label.image = img_vignette_tk
except Exception as e:
print("An error occurred during vignette effect:", e)
#----------------------------------------------------------------------------------------------------------------------
#vintage
def vintage_filter():
try:
input_text = text_entry.get()
image_filename = f"{input_text}.png"
img = cv2.imread(image_filename)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Convert to sepia
sepia_filter = np.array([[0.272, 0.534, 0.131],
[0.349, 0.686, 0.168],
[0.393, 0.769, 0.189]])
img_sepia = cv2.transform(img, sepia_filter)
img_sepia = np.clip(img_sepia, 0, 255)
# Apply a subtle vignette
rows, cols = img.shape[:2]
X_resultant_kernel = cv2.getGaussianKernel(cols, cols//2)
Y_resultant_kernel = cv2.getGaussianKernel(rows, rows//2)
resultant_kernel = Y_resultant_kernel * X_resultant_kernel.T
mask = 255 * resultant_kernel / np.linalg.norm(resultant_kernel)
img_vignette = np.copy(img_sepia)
img_vignette[:,:,0] = img_vignette[:,:,0] * mask
img_vignette[:,:,1] = img_vignette[:,:,1] * mask
img_vignette[:,:,2] = img_vignette[:,:,2] * mask
# Add some noise
intensity = 0.05
noise = np.random.normal(size=img_vignette.shape, scale=intensity*255)
img_vintage = np.clip(img_vignette + noise, 0, 255).astype(np.uint8)
# Save and display the vintage image
vintage_filename = f"{input_text}_vintage.png"