Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_tight_contour_patterns.py
- import tkinter as tk
- from PIL import Image, ImageTk, ImageDraw, ImageFilter, ImageChops
- import random
- ww = 640
- hh = 640
- p = 64
- cx = ww // 2
- cy = hh // 2
- root = tk.Tk()
- root.title("Tight Contour Patterns")
- root.geometry(f"+-10+0")
- canvas = tk.Canvas(root, width=ww, height=hh)
- canvas.pack()
- img = Image.new("L", (ww + p, hh + p), 255)
- contours = main_line = Image.new("RGBA", (ww + p, hh + p), (0, 0, 0, 0))
- transparent_img = Image.new("RGBA", img.size, (255, 255, 255, 0))
- r = 300
- bg_circle = Image.new("RGBA", (ww + p, hh + p), (255, 255, 255, 255))
- draw = ImageDraw.Draw(bg_circle)
- draw.ellipse((ww // 2 - r + p // 2, hh // 2 - r + p // 2, ww // 2 + r + p // 2, hh // 2 + r + p // 2), fill=(0, 255, 0, 255))
- fg_cache = [(x, y) for x in range(ww + p) for y in range(hh + p)]
- def pil_perlin_noise(img):
- draw = ImageDraw.Draw(img)
- for y in range(0, hh + p, 32):
- for x in range(0, ww + p, 32):
- draw.rectangle((x, y, x + 32, y + 32), fill=random.choice([0, 255]))
- img = img.filter(ImageFilter.GaussianBlur(25))
- return img
- def mask(img):
- mask_img = Image.eval(img, lambda p: 255 if p == 255 else 0).convert("L")
- return Image.composite(transparent_img, img, mask_img)
- def polarize(img, contrast=128):
- return img.point(lambda p: 255 if p < contrast else 0)
- def thicken(main_line, blur=4):
- main_line = main_line.filter(ImageFilter.GaussianBlur(blur))
- main_line = polarize(main_line, contrast=250)
- main_line = ImageChops.invert(main_line)
- return main_line
- def darken(p):
- if p > 180:
- return p
- else:
- return p * 0.7
- def draw_contour(img):
- img = polarize(img)
- img = img.filter(ImageFilter.FIND_EDGES)
- img = img.filter(ImageFilter.MaxFilter(3))
- img = polarize(img)
- return img
- def display_pattern(img):
- blur = img.filter(ImageFilter.GaussianBlur(2))
- blur = blur.point(darken)
- combined = Image.alpha_composite(bg_circle, blur)
- tk_image = ImageTk.PhotoImage(combined)
- canvas.create_image(cx, cy, anchor="center", image=tk_image)
- canvas.tk_image = tk_image
- def add_contour_lines():
- global main_line, contours
- main_line = thicken(main_line)
- img = draw_contour(main_line)
- img = mask(img)
- prev = contours
- contours = Image.alpha_composite(contours, img)
- if prev != contours:
- add_contour_lines()
- display_pattern(contours)
- def create_pattern(event):
- global main_line, contours
- canvas.delete('all')
- canvas.create_text(cx, cy, text="Processing Image...", anchor="center", fill='purple', font='ariel 40 bold')
- canvas.update()
- main_line = pil_perlin_noise(img)
- main_line = draw_contour(main_line.convert('RGBA'))
- contours = mask(main_line)
- display_pattern(contours)
- add_contour_lines()
- root.bind("<space>", create_pattern)
- create_pattern(0)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement