Created
May 18, 2020 07:55
-
-
Save ryul99/b0cbcae041e725d413454b173067bc47 to your computer and use it in GitHub Desktop.
write text to image with PILLOW
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 glob | |
from PIL import ImageFont, ImageDraw, Image | |
from multiprocessing import Pool | |
from functools import partial | |
import random | |
import tqdm | |
def imwrite(input_, save_dir): | |
i, data = input_ | |
bg, word, font = data | |
# print(data) | |
# coordinates of text | |
x = random.randint(0, 4) | |
y = random.randint(0, 4) | |
word.strip() | |
font = ImageFont.truetype(font, 45) # (true type font, font size) | |
img = Image.open(bg) | |
img = img.resize((50,50)) # resize background image | |
img = img.convert('RGB') | |
draw = ImageDraw.Draw(img) | |
draw.text((x, y), word, fill=(0,0,0), font=font) # (coordinates, text, fill=color, font=ImageFont) | |
img.save(save_dir + '/' + str(i) + '.jpg') | |
if __name__ == '__main__': | |
num_process = 16 | |
background = glob.glob('background/*') # background images | |
with open('lexicon.txt', 'r', encoding='utf-8') as f: | |
lexicon = f.readlines() | |
fonts = ['batang.ttc', 'gulim.ttf', 'NanumGothicCoding.ttf'] # list of true type fonts | |
dataset = [(bg, word, font) for word in lexicon for bg in background for font in fonts] | |
if num_process == 1: | |
r = list(tqdm.tqdm(map(partial(imwrite, save_dir='output') ,enumerate(dataset)), total=len(dataset))) | |
else: | |
with Pool(processes=num_process) as p: | |
r = list(tqdm.tqdm(p.imap(partial(imwrite, save_dir='output') ,enumerate(dataset)), total=len(dataset))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment