Last active
October 5, 2019 15:44
-
-
Save nevack/c663796c2becff2a7d4921bf338c5e3a to your computer and use it in GitHub Desktop.
Text to image, that should be tilted to be readable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from PIL import Image, ImageDraw, ImageFont | |
import numpy | |
def find_coefficients(pa, pb): | |
matrix = [] | |
for p1, p2 in zip(pa, pb): | |
matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]]) | |
matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]]) | |
a = numpy.matrix(matrix, dtype=numpy.float) | |
b = numpy.array(pb).reshape(8) | |
res = numpy.dot(numpy.linalg.inv(a.T * a) * a.T, b) | |
return numpy.array(res).reshape(8) | |
colors = ['black', 'white'] | |
mode = 0 | |
try: | |
mode = int(input('Mode (1 or 2): ')) - 1 | |
except ValueError: | |
print('Wrong number: using 1') | |
background = colors[mode % len(colors)] | |
foreground = colors[(mode + 1) % len(colors)] | |
font_name = font # you need to specify path there | |
font_size = 45 | |
font = ImageFont.truetype(font_name, font_size) | |
txt = input('Text: ') | |
w, h = font.getsize(txt) | |
perspective = 8 | |
coefficients = find_coefficients( | |
[(0, 0), (w, 0), (w / perspective * (perspective - 1), h), (w / perspective, h)], | |
[(0, 0), (w, 0), (w, h), (0, h)]) | |
image = Image.new('RGBA', (w, h), background) | |
draw = ImageDraw.Draw(image) | |
draw.text((0, 0), txt, fill=foreground, font=font) | |
save_location = os.getcwd() | |
image = image.transform((w, h), Image.PERSPECTIVE, coefficients, Image.BILINEAR) | |
image = image.resize((w, h * 40), Image.BILINEAR) | |
image.save(save_location + '/output.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment