text-art/draw.py
Michael Pilosov c94cd44243 first commit
2022-05-18 21:34:04 -06:00

130 lines
3.2 KiB
Python

from matplotlib import pyplot as plt
import random
from collections import Counter
filename = 'flower.txt'
with open(filename, 'r') as f:
full_text = f.readlines()
txt = ''.join(full_text)
print(txt)
sorted_chars = sorted(Counter(txt.replace('\n', '').replace(' ', '')).items(), key=lambda x: x[1], reverse=True)
# print(sorted_chars)
color = '#383DF6'
fig, ax = plt.subplots(facecolor=(0, 0, 0))
fig.patch.set_alpha(0.)
ax.patch.set_alpha(0.)
ax.set_aspect(1)
# ax.set_xlim([0,0.2])
character_colors = {
'.': '#383DF6',
'-': '#13E813',
'|': '#EE192F',
',': '#13E813',
';': '#13E813',
'#': '#383DF6',
'{': '#137FDA',
'}': '#137FDA',
'\\': '#EE192F',
'/': '#EE192F',
'(': '#6EF558',
')': '#6EF558',
'_': '#13E813',
'\'': '#13E813',
'`': '#383DF6',
':': '#383DF6',
' ': '#000000'
}
# color_pallet = ['#e8f7ee', '#b8c4bb', '#663f46', '#3c362a', '#c9d6ea']
# color_pallet = ['#53131e', '#e56399', '#de6e4b', '#0acdff']
# color_pallet = ['#af9ab2', '#315659', '#2978a0', '#bcab79', '#c6e0ff', '#de6e4b']
color_pallet = ['#53131e', '#14453d', '#e56399', '#2978a0', '#ffcb77', '#17c3b2', '#9c3848']
# 9, 22, 45, 1992
seed = 1992
random.seed(seed)
for idx, _char_with_count in enumerate(sorted_chars):
char, _ = _char_with_count
# color = color_pallet[idx%len(color_pallet)]
color = random.choice(color_pallet)
character_colors[char] = color
# some manual overrides for aesthetics:
character_colors['('] = character_colors[')']
character_colors['{'] = character_colors['}']
character_colors['|'] = '#b5d6b2'
print(character_colors)
top = 1
lineheight=0.0575
left = 0
charwidth=0.0275
max_chars = max(map(len, full_text))
prob_fill_white = 0
whitespace_char = 'X'
whitespace_fsize = 14
whitespace_alpha = 0.2
for row, line in enumerate(full_text):
for col, char in enumerate(line):
fsize = 14 # default font size
alpha = 1 # default transparency
# if space, replace with random character
if char == ' ':
if random.random() > 1 - prob_fill_white:
char = whitespace_char
fsize = whitespace_fsize
alpha = whitespace_alpha
color = character_colors.get(char, '#000000')
ax.text(
x=0, y=0, s=char,
alpha=alpha, # transparency
fontsize=fsize,
color=color,
position=(left + charwidth*col, top-lineheight*row),
family='monospace'
)
# pad each line with space
for c in range(col, max_chars):
if random.random() > 1 - prob_fill_white:
color = character_colors.get(whitespace_char, '#000000')
ax.text(
x=0, y=0, s=whitespace_char,
alpha=whitespace_alpha, # transparency
fontsize=whitespace_fsize,
color=color,
position=(left + charwidth*c, top-lineheight*row),
family='monospace'
)
c = '-'.join(color_pallet)
ax.axis('off')
fig.savefig(
f'img-{seed}-{c}.png',
dpi=300,
bbox_inches='tight',
)
fig.savefig(
f'img-{seed}-{c}.svg',
dpi=300,
bbox_inches='tight',
)
fig.savefig(
f'img.png',
dpi=300,
bbox_inches='tight',
)