generate_imgs_by_fonts.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import argparse
  2. import datetime
  3. import os
  4. import uuid
  5. from PIL import Image, ImageFont, ImageDraw
  6. from tqdm import tqdm
  7. def create_img(font_path, text, save_path, cnt):
  8. fontSize = 25
  9. # 字体样式,
  10. font = ImageFont.truetype(font_path, fontSize, encoding="gbk")
  11. im = Image.new("RGB", (int(font.getbbox(text.rstrip('\n'))[2]), font.getbbox(text)[3]), (255, 255, 255))
  12. dr = ImageDraw.Draw(im)
  13. # 文字颜色
  14. dr.text((0, 0), text, font=font, fill="#000000")
  15. time = datetime.datetime.now()
  16. t = str(time.year).zfill(4) + '-' + str(time.month).zfill(2) + '-' + str(time.day).zfill(2)
  17. if not os.path.exists("%s/%s/" % (save_path, font_path.split('/')[-1][0:-4])):
  18. os.makedirs("%s/%s/" % (save_path, font_path.split('/')[-1][0:-4]))
  19. # 图片命名
  20. img_name = 'kdan_' + t + '_' + str(cnt).zfill(4) + '_' + str(uuid.uuid1())[0:8] + '.jpg'
  21. save_path = "%s/%s/" % (save_path, font_path.split('/')[-1][0:-4]) + img_name
  22. # 保存
  23. im.save(save_path)
  24. def get_all_labels(img_fold):
  25. # 获取字体文件夹列表
  26. img_fold_list = os.listdir(img_fold)
  27. # label_list.txt文件
  28. fp_label = open(str(img_fold) + '/label_list.txt', 'w')
  29. cnt = 0
  30. for img_fold_in in img_fold_list:
  31. if img_fold_in.endswith('.txt'):
  32. continue
  33. # 字体名以及对应id写入label_list.txt
  34. fp_label.write(str(cnt) + ' ' + str(img_fold_in) + '\n')
  35. cnt += 1
  36. fp_label.close()
  37. def work(font_path, text_path, save_path):
  38. fontPath_list = os.listdir(font_path)
  39. print('generate images for fonts based on %s' % text_path)
  40. for fontPath in tqdm(fontPath_list):
  41. with open(text_path, 'r') as fpp:
  42. t = fpp.readlines()
  43. fpp.close()
  44. cnt = 0
  45. for text in t:
  46. create_img(str(font_path) + '/' + str(fontPath), text, save_path, cnt)
  47. cnt += 1
  48. get_all_labels(save_path)
  49. if __name__ == '__main__':
  50. parser = argparse.ArgumentParser()
  51. parser.add_argument('--font_dir', type=str, default='./font')
  52. parser.add_argument('--text_path', type=str, default='./text/eng_text_test.txt')
  53. parser.add_argument('--save_dir', type=str, default='./images')
  54. args = parser.parse_args()
  55. work(args.font_dir, args.text_path, args.save_dir)